Java Code Examples for java.nio.ByteBuffer
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project adbcj, under directory /mysql/codec/src/test/java/org/adbcj/mysql/codec/.
Source file: IoUtilsTest.java

@Test(dependsOnMethods="testSafeRead") public void testReadShort() throws IOException { ByteBuffer buffer=ByteBuffer.allocate(1024); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putShort((short)0).putShort((short)1).putShort((short)2).putShort((short)-1).putShort((short)-2); InputStream in=new ByteArrayInputStream(buffer.array(),0,buffer.position()); Assert.assertEquals(IoUtils.readShort(in),0); Assert.assertEquals(IoUtils.readShort(in),1); Assert.assertEquals(IoUtils.readShort(in),2); Assert.assertEquals(IoUtils.readShort(in),-1); Assert.assertEquals(IoUtils.readShort(in),-2); }
Example 2
From project adbcj, under directory /mysql/codec/src/test/java/org/adbcj/mysql/codec/.
Source file: IoUtilsTest.java

@Test(dependsOnMethods="testSafeRead") public void testReadUnsignedShort() throws IOException { ByteBuffer buffer=ByteBuffer.allocate(1024); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putShort((short)0).putShort((short)1).putShort((short)2).putShort((short)-1).putShort((short)-2); InputStream in=new ByteArrayInputStream(buffer.array(),0,buffer.position()); Assert.assertEquals(IoUtils.readUnsignedShort(in),0); Assert.assertEquals(IoUtils.readUnsignedShort(in),1); Assert.assertEquals(IoUtils.readUnsignedShort(in),2); Assert.assertEquals(IoUtils.readUnsignedShort(in),0xffff); Assert.assertEquals(IoUtils.readUnsignedShort(in),0xfffe); }
Example 3
From project aether-core, under directory /aether-api/src/test/java/org/eclipse/aether/transfer/.
Source file: TransferEventTest.java

@Test public void testByteArrayConversion(){ byte[] buffer=new byte[]{0,1,2,3,4,5,6,7,8,9}; int length=buffer.length - 2; int offset=1; TransferEvent event=new TransferEvent.Builder(session,res).setDataBuffer(buffer,offset,length).build(); ByteBuffer bb=event.getDataBuffer(); byte[] dst=new byte[bb.remaining()]; bb.get(dst); byte[] expected=new byte[]{1,2,3,4,5,6,7,8}; assertArrayEquals(expected,dst); }
Example 4
From project aether-core, under directory /aether-connector-asynchttpclient/src/main/java/org/eclipse/aether/connector/async/.
Source file: ProgressingFileBodyGenerator.java

public long read(ByteBuffer buffer) throws IOException { ByteBuffer event=buffer.slice(); long read=delegate.read(buffer); if (read > 0) { try { event.limit((int)read); completionHandler.fireTransferProgressed(event); } catch ( TransferCancelledException e) { throw (IOException)new IOException(e.getMessage()).initCause(e); } } return read; }
Example 5
From project Aion-Extreme, under directory /AE-go_GameServer/src/com/aionemu/gameserver/network/aion/.
Source file: AionServerPacket.java

/** * Write and encrypt this packet data for given connection, to given buffer. * @param con * @param buf */ public final void write(AionConnection con,ByteBuffer buf){ buf.putShort((short)0); writeOP(buf,getOpcode()); writeImpl(con,buf); buf.flip(); buf.putShort((short)buf.limit()); ByteBuffer b=buf.slice(); buf.position(0); con.encrypt(b); }
Example 6
From project AirReceiver, under directory /src/main/java/org/phlo/AirReceiver/.
Source file: RaopRtspChallengeResponseHandler.java

private byte[] getSignature(){ final ByteBuffer sigData=ByteBuffer.allocate(16 + 16 + 6); sigData.put(m_challenge); sigData.put(m_localAddress.getAddress()); sigData.put(m_hwAddress); while (sigData.hasRemaining()) sigData.put((byte)0); try { m_rsaPkCS1PaddingCipher.init(Cipher.ENCRYPT_MODE,AirTunesCrytography.PrivateKey); return m_rsaPkCS1PaddingCipher.doFinal(sigData.array()); } catch ( final Exception e) { throw new RuntimeException("Unable to sign response",e); } }
Example 7
From project alljoyn_java, under directory /src/org/alljoyn/bus/.
Source file: BusAttachment.java

/** * Convert to UTF-8 for native code. This is intended for sensitive string data (i.e. passwords). The native code must take care of scrubbing the buffer when done. This method can be called from a listener object and must therefore be MT-Safe. * @param charArray the sensitive string * @return the UTF-8 encoded version of the string */ static byte[] encode(char[] charArray){ try { Charset charset=Charset.forName("UTF-8"); CharsetEncoder encoder=charset.newEncoder(); ByteBuffer bb=encoder.encode(CharBuffer.wrap(charArray)); byte[] ba=new byte[bb.limit()]; bb.get(ba); return ba; } catch ( CharacterCodingException ex) { BusException.log(ex); return null; } }
Example 8
From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/entity/mime/.
Source file: HttpMultipart.java

private static ByteArrayBuffer encode(final Charset charset,final String string){ ByteBuffer encoded=charset.encode(CharBuffer.wrap(string)); ByteArrayBuffer bab=new ByteArrayBuffer(encoded.remaining()); bab.append(encoded.array(),encoded.position(),encoded.remaining()); return bab; }
Example 9
From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/mysql/net/packet/.
Source file: MysqlPacketBuffer.java

public ByteBuffer toByteBuffer(){ ByteBuffer buffer=ByteBuffer.allocate(this.getPacketLength() + 4); buffer.put(this.buffer,0,this.getPacketLength() + 4); buffer.rewind(); return buffer; }
Example 10
From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/net/.
Source file: Connection.java

public void postMessage(byte[] msg){ PacketOutputStream _framer=getPacketOutputStream(); _framer.resetPacket(); try { _framer.write(msg); ByteBuffer buffer=_framer.returnPacketBuffer(); _outQueue.append(buffer); _cmgr.invokeConnectionWriteMessage(this); } catch ( IOException e) { this._cmgr.connectionFailed(this,e); } }
Example 11
From project airlift, under directory /http-client/src/main/java/io/airlift/http/client/.
Source file: HttpUriBuilder.java

private String encode(String input,byte... allowed){ StringBuilder builder=new StringBuilder(); ByteBuffer buffer=Charsets.UTF_8.encode(input); while (buffer.remaining() > 0) { byte b=buffer.get(); if (Bytes.contains(allowed,b)) { builder.append((char)b); } else { builder.append('%'); builder.append(Ascii.toUpperCase(forDigit((b >>> 4) & 0xF,16))); builder.append(Ascii.toUpperCase(forDigit(b & 0xF,16))); } } return builder.toString(); }
Example 12
From project AirReceiver, under directory /src/main/java/org/phlo/audio/.
Source file: SampleByteBufferFormat.java

public SampleIndexedAccessor getAccessor(final ByteBuffer buffer,final SampleDimensions bufferDimensions,final SampleRange range){ final ByteBuffer bufferWithByteOrder=buffer.duplicate(); bufferWithByteOrder.order(byteOrder); final SampleIndexer sampleIndexer=layout.getIndexer(bufferDimensions,range); final SampleAccessor sampleAccessor=sampleFormat.getAccessor(bufferWithByteOrder); return new SampleIndexedAccessor(){ @Override public float getSample( int channel, int sample){ return sampleAccessor.getSample(sampleIndexer.getSampleIndex(channel,sample)); } @Override public void setSample( int channel, int sample, float value){ sampleAccessor.setSample(sampleIndexer.getSampleIndex(channel,sample),value); } @Override public SampleDimensions getDimensions(){ return range.size; } @Override public SampleIndexedAccessor slice( SampleOffset offset, SampleDimensions dimensions){ return getAccessor(buffer,bufferDimensions,range.slice(offset,dimensions)); } @Override public SampleIndexedAccessor slice( SampleRange range){ return getAccessor(buffer,bufferDimensions,range.slice(range)); } } ; }
Example 13
/** * Decode chars from byte buffer using UTF8 encoding. This operation is performance-critical since a jar file contains a large number of strings for the name of each file in the archive. This routine therefore avoids using the expensive utf8Decoder when decoding is straightforward. * @param buffer the buffer that contains the encoded characterdata * @param pos the index in buffer of the first byte of the encodeddata * @param length the length of the encoded data in number ofbytes. * @return a String that contains the decoded characters. */ private String decodeChars(byte[] buffer,int pos,int length) throws IOException { String result; int i=length - 1; while ((i >= 0) && (buffer[i] <= 0x7f)) { i--; } if (i < 0) { result=stringFromSubarray(buffer,0,pos,length); } else { ByteBuffer bufferBuffer=ByteBuffer.wrap(buffer,pos,length); ByteArrayInputStream in=new ByteArrayInputStream(buffer); AlbiteStreamReader r=new AlbiteStreamReader(in,Encodings.UTF_8); char[] characters=r.read(buffer.length); result=String.valueOf(characters); } return result; }
Example 14
From project android-aac-enc, under directory /src/com/coremedia/iso/boxes/mdat/.
Source file: SampleList.java

@Override public ByteBuffer get(int index){ Long offset=getOffsetKeys().get(index); int sampleSize=l2i(offsets2Sizes.get(offset)); for ( MediaDataBox mediaDataBox : mdats) { long start=mdatStartCache.get(mediaDataBox); long end=mdatEndCache.get(mediaDataBox); if ((start <= offset) && (offset + sampleSize <= end)) { ByteBuffer bb=mediaDataBox.getContent(); bb.position(l2i(offset - start)); ByteBuffer sample=bb.slice(); sample.limit(sampleSize); return sample; } } throw new RuntimeException("The sample with offset " + offset + " and size "+ sampleSize+ " is NOT located within an mdat"); }
Example 15
From project activemq-apollo, under directory /apollo-openwire/src/main/scala/org/apache/activemq/apollo/openwire/codec/.
Source file: BooleanStream.java

public void marshal(ByteBuffer dataOut){ if (arrayLimit < 64) { dataOut.put((byte)arrayLimit); } else if (arrayLimit < 256) { dataOut.put((byte)0xC0); dataOut.put((byte)arrayLimit); } else { dataOut.put((byte)0x80); dataOut.putShort(arrayLimit); } dataOut.put(data,0,arrayLimit); }
Example 16
From project Aion-Extreme, under directory /AE-go_GameServer/src/com/aionemu/gameserver/network/aion/.
Source file: AionConnection.java

/** * Called by Dispatcher. ByteBuffer data contains one packet that should be processed. * @param data * @return True if data was processed correctly, False if some error occurred and connection should be closed NOW. */ @Override protected final boolean processData(ByteBuffer data){ if (!crypt.decrypt(data)) { log.warn("Decrypt fail!"); } AionClientPacket pck=aionPacketHandler.handle(data,this); log.debug("recived packet: " + pck); if (pck != null && pck.read()) processor.executePacket(pck); return true; }
Example 17
From project airlift, under directory /http-client/src/main/java/io/airlift/http/client/.
Source file: HttpUriBuilder.java

/** * input must be an ASCII string representing a percent-encoded UTF-8 byte sequence */ private String percentDecode(String encoded){ Preconditions.checkArgument(CharMatcher.ASCII.matchesAllOf(encoded),"string must be ASCII"); ByteArrayOutputStream out=new ByteArrayOutputStream(encoded.length()); for (int i=0; i < encoded.length(); i++) { char c=encoded.charAt(i); if (c == '%') { Preconditions.checkArgument(i + 2 < encoded.length(),"percent encoded value is truncated"); int high=Character.digit(encoded.charAt(i + 1),16); int low=Character.digit(encoded.charAt(i + 2),16); Preconditions.checkArgument(high != -1 && low != -1,"percent encoded value is not a valid hex string: ",encoded.substring(i,i + 2)); int value=(high << 4) | (low); out.write(value); i+=2; } else { out.write((int)c); } } try { return Charsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(out.toByteArray())).toString(); } catch ( CharacterCodingException e) { throw new IllegalArgumentException("input does not represent a proper UTF8-encoded string"); } }
Example 18
From project android-aac-enc, under directory /src/com/coremedia/iso/boxes/.
Source file: AlbumBox.java

@Override public void _parseDetails(ByteBuffer content){ parseVersionAndFlags(content); language=IsoTypeReader.readIso639(content); albumTitle=IsoTypeReader.readString(content); if (content.remaining() > 0) { trackNumber=IsoTypeReader.readUInt8(content); } else { trackNumber=-1; } }