Java Code Examples for java.nio.ByteBuffer.get()

The following are Jave code examples for showing how to use get() of the java.nio.ByteBuffer class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: chromium-net-for-android   File: TestUrlRequestCallback.java   View Source Code Vote up 6 votes
@Override
public void onReadCompleted(UrlRequest request, UrlResponseInfo info, ByteBuffer byteBuffer) {
    assertEquals(mExecutorThread, Thread.currentThread());
    assertFalse(request.isDone());
    assertTrue(mResponseStep == ResponseStep.ON_RESPONSE_STARTED
            || mResponseStep == ResponseStep.ON_READ_COMPLETED);
    assertNull(mError);

    mResponseStep = ResponseStep.ON_READ_COMPLETED;

    final byte[] lastDataReceivedAsBytes;
    final int bytesRead = byteBuffer.position() - mBufferPositionBeforeRead;
    mHttpResponseDataLength += bytesRead;
    lastDataReceivedAsBytes = new byte[bytesRead];
    // Rewind |byteBuffer.position()| to pre-read() position.
    byteBuffer.position(mBufferPositionBeforeRead);
    // This restores |byteBuffer.position()| to its value on entrance to
    // this function.
    byteBuffer.get(lastDataReceivedAsBytes);
    mResponseAsString += new String(lastDataReceivedAsBytes);

    if (maybeThrowCancelOrPause(request)) {
        return;
    }
    startNextRead(request);
}
 
Example 2
Project: Virtual-Hosts   File: Packet.java   View Source Code Vote up 6 votes
private IP4Header(ByteBuffer buffer) throws UnknownHostException
{
    byte versionAndIHL = buffer.get();
    this.version = (byte) (versionAndIHL >> 4);
    this.IHL = (byte) (versionAndIHL & 0x0F);
    this.headerLength = this.IHL << 2;

    this.typeOfService = BitUtils.getUnsignedByte(buffer.get());
    this.totalLength = BitUtils.getUnsignedShort(buffer.getShort());

    this.identificationAndFlagsAndFragmentOffset = buffer.getInt();

    this.TTL = BitUtils.getUnsignedByte(buffer.get());
    this.protocolNum = BitUtils.getUnsignedByte(buffer.get());
    this.protocol = TransportProtocol.numberToEnum(protocolNum);
    this.headerChecksum = BitUtils.getUnsignedShort(buffer.getShort());

    byte[] addressBytes = new byte[4];
    buffer.get(addressBytes, 0, 4);
    this.sourceAddress = InetAddress.getByAddress(addressBytes);

    buffer.get(addressBytes, 0, 4);
    this.destinationAddress = InetAddress.getByAddress(addressBytes);

    //this.optionsAndPadding = buffer.getInt();
}
 
Example 3
Project: directory-mavibot   File: RevisionNameSerializer.java   View Source Code Vote up 6 votes
/**
 * {@inheritDoc}
 */
@Override
public RevisionName deserialize( ByteBuffer buffer ) throws IOException
{
    // The revision
    long revision = buffer.getLong();

    // The name's length
    int len = buffer.getInt();

    switch ( len )
    {
        case 0:
            return new RevisionName( revision, "" );

        case -1:
            return new RevisionName( revision, null );

        default:
            byte[] nameBytes = new byte[len];
            buffer.get( nameBytes );

            return new RevisionName( revision, Strings.utf8ToString( nameBytes ) );
    }
}
 
Example 4
Project: openjdk-jdk10   File: DirectByteBufferTest.java   View Source Code Vote up 6 votes
byte[] alignedWriteSnippet(byte a, byte b, short c, int d, long e, double f, float g) {
    byte[] ret = new byte[28];
    ByteBuffer buffer = makeDirect(28, byteOrder);

    buffer.put(a);
    buffer.put(b);
    buffer.putShort(c);
    buffer.putInt(d);
    buffer.putLong(e);
    buffer.putDouble(f);
    buffer.putFloat(g);

    buffer.position(0);
    buffer.get(ret);

    return ret;
}
 
Example 5
Project: rcom   File: UserCollectorTemplate.java   View Source Code Vote up 6 votes
public void append(char c)
{
		if(validChar(c))
		{
			str.append(c);
		}else
		{
			cb.clear();
			cb.put(c);
			cb.flip();
			ByteBuffer out=StandardCharsets.UTF_8.encode(cb);
			while(out.hasRemaining())
			{
				str.append("\\\\x");
				bs[0]=out.get();
				str.append(UtilString.toHexPadZero(bs));
			}
		}
}
 
Example 6
Project: rmq4note   File: RocketMQSerializable.java   View Source Code Vote up 5 votes
public static RemotingCommand rocketMQProtocolDecode(final byte[] headerArray) {
    RemotingCommand cmd = new RemotingCommand();
    ByteBuffer headerBuffer = ByteBuffer.wrap(headerArray);
    // int code(~32767)
    cmd.setCode(headerBuffer.getShort());
    // LanguageCode language
    cmd.setLanguage(LanguageCode.valueOf(headerBuffer.get()));
    // int version(~32767)
    cmd.setVersion(headerBuffer.getShort());
    // int opaque
    cmd.setOpaque(headerBuffer.getInt());
    // int flag
    cmd.setFlag(headerBuffer.getInt());
    // String remark
    int remarkLength = headerBuffer.getInt();
    if (remarkLength > 0) {
        byte[] remarkContent = new byte[remarkLength];
        headerBuffer.get(remarkContent);
        cmd.setRemark(new String(remarkContent, CHARSET_UTF8));
    }

    // HashMap<String, String> extFields
    int extFieldsLength = headerBuffer.getInt();
    if (extFieldsLength > 0) {
        byte[] extFieldsBytes = new byte[extFieldsLength];
        headerBuffer.get(extFieldsBytes);
        cmd.setExtFields(mapDeserialize(extFieldsBytes));
    }
    return cmd;
}
 
Example 7
Project: sstable-adaptor   File: FastByteOperations.java   View Source Code Vote up 5 votes
public int compare(ByteBuffer buffer1, ByteBuffer buffer2)
{
    int end1 = buffer1.limit();
    int end2 = buffer2.limit();
    for (int i = buffer1.position(), j = buffer2.position(); i < end1 && j < end2; i++, j++)
    {
        int a = (buffer1.get(i) & 0xff);
        int b = (buffer2.get(j) & 0xff);
        if (a != b)
        {
            return a - b;
        }
    }
    return buffer1.remaining() - buffer2.remaining();
}
 
Example 8
Project: openjdk-jdk10   File: DirectByteBufferTest.java   View Source Code Vote up 5 votes
Ret unalignedReadSnippet(byte[] arg) {
    ByteBuffer buffer = makeDirect(arg, byteOrder);

    Ret ret = new Ret();
    ret.byteValue = buffer.get();
    ret.shortValue = buffer.getShort();
    ret.intValue = buffer.getInt();
    ret.longValue = buffer.getLong();
    ret.doubleValue = buffer.getDouble();
    ret.floatValue = buffer.getFloat();

    return ret;
}
 
Example 9
Project: s-store   File: CompressionService.java   View Source Code Vote up 5 votes
public static byte[] compressBuffer(ByteBuffer buffer) throws IOException {
    assert(buffer.isDirect());
    IOBuffers buffers = getBuffersForCompression(buffer.remaining(), true);
    ByteBuffer output = buffers.output;

    final int compressedSize = Snappy.compress(buffer, output);
    byte result[] = new byte[compressedSize];
    output.get(result);
    return result;
}
 
Example 10
Project: jdk8u-jdk   File: TrueTypeFont.java   View Source Code Vote up 5 votes
protected void initAllNames(int requestedID, HashSet names) {

        byte[] name = new byte[256];
        ByteBuffer buffer = getTableBuffer(nameTag);

        if (buffer != null) {
            ShortBuffer sbuffer = buffer.asShortBuffer();
            sbuffer.get(); // format - not needed.
            short numRecords = sbuffer.get();

            /* The name table uses unsigned shorts. Many of these
             * are known small values that fit in a short.
             * The values that are sizes or offsets into the table could be
             * greater than 32767, so read and store those as ints
             */
            int stringPtr = ((int) sbuffer.get()) & 0xffff;
            for (int i=0; i<numRecords; i++) {
                short platformID = sbuffer.get();
                if (platformID != MS_PLATFORM_ID) {
                    sbuffer.position(sbuffer.position()+5);
                    continue; // skip over this record.
                }
                short encodingID = sbuffer.get();
                short langID     = sbuffer.get();
                short nameID     = sbuffer.get();
                int   nameLen    = ((int) sbuffer.get()) & 0xffff;
                int   namePtr    = (((int) sbuffer.get()) & 0xffff) + stringPtr;

                if (nameID == requestedID) {
                    buffer.position(namePtr);
                    buffer.get(name, 0, nameLen);
                    names.add(makeString(name, nameLen, encodingID));
                }
            }
        }
    }
 
Example 11
Project: fresco_floodlight   File: BPDU.java   View Source Code Vote up 5 votes
@Override
public IPacket deserialize(byte[] data, int offset, int length) {
    ByteBuffer bb = ByteBuffer.wrap(data, offset, length);
    
    // LLC header
    llcHeader.deserialize(data, offset, 3);
    
    this.protocolId = bb.getShort();
    this.version = bb.get();
    this.type = bb.get();
    
    // These fields only exist if it's a configuration BPDU
    if (this.type == 0x0) {
        this.flags = bb.get();
        bb.get(rootBridgeId, 0, 6);
        this.rootPathCost = bb.getInt();
        bb.get(this.senderBridgeId, 0, 6);
        this.portId = bb.getShort();
        this.messageAge = bb.getShort();
        this.maxAge = bb.getShort();
        this.helloTime = bb.getShort();
        this.forwardDelay = bb.getShort();
    }
    // TODO should we set other fields to 0?
    
    return this;
}
 
Example 12
Project: mp4parser_android   File: AbstractBox.java   View Source Code Vote up 5 votes
/**
 * Verifies that a box can be reconstructed byte-exact after parsing.
 *
 * @param content the raw content of the box
 * @return <code>true</code> if raw content exactly matches the reconstructed content
 */
private boolean verify(ByteBuffer content) {
    ByteBuffer bb = ByteBuffer.allocate(l2i(getContentSize() + (deadBytes != null ? deadBytes.limit() : 0)));
    getContent(bb);
    if (deadBytes != null) {
        deadBytes.rewind();
        while (deadBytes.remaining() > 0) {
            bb.put(deadBytes);
        }
    }
    content.rewind();
    bb.rewind();


    if (content.remaining() != bb.remaining()) {
        LOG.severe(this.getType() + ": remaining differs " + content.remaining() + " vs. " + bb.remaining());
        return false;
    }
    int p = content.position();
    for (int i = content.limit() - 1, j = bb.limit() - 1; i >= p; i--, j--) {
        byte v1 = content.get(i);
        byte v2 = bb.get(j);
        if (v1 != v2) {
            LOG.severe(String.format("%s: buffers differ at %d: %2X/%2X", this.getType(), i, v1, v2));
            byte[] b1 = new byte[content.remaining()];
            byte[] b2 = new byte[bb.remaining()];
            content.get(b1);
            bb.get(b2);
            System.err.println("original      : " + Hex.encodeHex(b1, 4));
            System.err.println("reconstructed : " + Hex.encodeHex(b2, 4));
            return false;
        }
    }
    return true;

}
 
Example 13
Project: mycat-src-1.6.1-RELEASE   File: EmptyQueryResponse.java   View Source Code Vote up 5 votes
public static EmptyQueryResponse parse(ByteBuffer buffer, int offset) {
	if (buffer.get(offset) != PacketMarker.B_EmptyQueryResponse.getValue()) {
		throw new IllegalArgumentException(
				"this packetData not is EmptyQueryResponse");
	}
	int _offset = offset + 1;
	EmptyQueryResponse pack = new EmptyQueryResponse();
	pack.length = PIOUtils.redInteger4(buffer, _offset);
	return pack;
}
 
Example 14
Project: mycat-src-1.6.1-RELEASE   File: OkPacket.java   View Source Code Vote up 5 votes
public byte[] writeToBytes(FrontendConnection c) {
	ByteBuffer buffer = c.allocate();
	this.write(buffer, c);
	buffer.flip();
	byte[] data = new byte[buffer.limit()];
	buffer.get(data);
	c.recycle(buffer);
	return data;
}
 
Example 15
Project: ditb   File: ByteBufferUtils.java   View Source Code Vote up 5 votes
/**
 * Copy the bytes from position to limit into a new byte[] of the exact length and sets the
 * position and limit back to their original values (though not thread safe).
 * @param buffer copy from here
 * @param startPosition put buffer.get(startPosition) into byte[0]
 * @return a new byte[] containing the bytes in the specified range
 */
public static byte[] toBytes(ByteBuffer buffer, int startPosition) {
  int originalPosition = buffer.position();
  byte[] output = new byte[buffer.limit() - startPosition];
  buffer.position(startPosition);
  buffer.get(output);
  buffer.position(originalPosition);
  return output;
}
 
Example 16
Project: dibd   File: ChannelLineBuffersTest.java   View Source Code Vote up 4 votes
@Test
public void bWriteTest() throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, UnsupportedEncodingException, ClosedChannelException{
	//Class<?> clazz = Class.forName("dibd.daemon.LineEncoder");
   	//Constructor<?> con = clazz.getConstructors()[0];
	//Constructor<?> con = clazz.getConstructor(new Class<?>[]{CharBuffer.class, Charset.class});
   	/*for( Class<?> p : con.getParameterTypes() )
		System.out.println("c: "+p);*/
   	//con.setAccessible(true);
   	//Method encode = clazz.getDeclaredMethods()[0];
   	//Method encode = clazz.getDeclaredMethod("encode", new Class<?>[]{ChannelLineBuffers.class});
   	/*for( Class<?> p : encode.getParameterTypes() )
		System.out.println(encode.getName()+": "+p);*/
   	//encode.setAccessible(true);
   	

   	
	
	
	//daemon.ConnectionWorker thread
	//daemon.command.****Command
	//  daemon.NNTPConnection.println
	//    daemon.NNTPConnection.writeToChannel
   	Charset charset = Charset.forName("UTF-8");
	String ts [] = {"blah", "\r\n", "205 cya", "\r\n"}; int i=0;
	LineEncoder lineEncoder = new LineEncoder(charset, clBuffers);
	lineEncoder.encode(CharBuffer.wrap(ts[0]));
   	//Object iLineEncoder = con.newInstance(new Object[]{CharBuffer.wrap(ts[0]), Charset.forName("UTF-8")});
   	//encode.invoke(iLineEncoder, clBuffers);
	lineEncoder.encode(CharBuffer.wrap("\r\n"));
   	//iLineEncoder = con.newInstance(new Object[]{CharBuffer.wrap("\r\n"), Charset.forName("UTF-8")});
   	//encode.invoke(iLineEncoder, clBuffers);
   	//    writeToChannel again for \r\n
	lineEncoder.encode(CharBuffer.wrap(ts[2]));
   	//iLineEncoder = con.newInstance(new Object[]{CharBuffer.wrap(ts[2]), Charset.forName("UTF-8")});
   	//encode.invoke(iLineEncoder, clBuffers);
	lineEncoder.encode(CharBuffer.wrap("\r\n"));
   	//iLineEncoder = con.newInstance(new Object[]{CharBuffer.wrap("\r\n"), Charset.forName("UTF-8")});
   	//encode.invoke(iLineEncoder, clBuffers);
   	
   	//daemon.ChannelWriter thread
   	ByteBuffer buf = clBuffers.getOutputBuffer();//recycle is inside,  "buf" is not a part of ChannelLineBuffers here
   	while (buf != null){
   		byte[] dst = new byte[buf.limit()];
   		buf.get(dst);
   		
   		//System.out.println(new String(dst, "UTF-8").replaceAll("\r\n", "\\\\r\\\\n"));
   		assertEquals(ts[i++],new String(dst, "UTF-8"));
   		buf = clBuffers.getOutputBuffer();
   	}
   	
       
   	//System.out.println(this.freeSmallBuffers.size());
   	//System.out.println(this.size);
   	assertTrue(this.size == ChannelLineBuffersTest.freeSmallBuffers.size());    
}
 
Example 17
Project: ditb   File: Bytes.java   View Source Code Vote up 4 votes
private static byte[] readBytes(ByteBuffer buf) {
  byte [] result = new byte[buf.remaining()];
  buf.get(result);
  return result;
}
 
Example 18
Project: aos-MediaLib   File: AvosMediaMetadata.java   View Source Code Vote up 4 votes
public boolean parse(byte[] bytes) {
    mParcel = Parcel.obtain();

    mKeyToPosMap.clear();
    mBegin = mParcel.dataPosition();
    // Placeholder for the length of the metadata
    mParcel.writeInt(-1);
    // Write the header. The java layer will look for the marker.
    mParcel.writeInt(kMetaMarker);

    ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
    byteBuffer.order(ByteOrder.nativeOrder());
    while (byteBuffer.hasRemaining()) {
        int id = byteBuffer.getInt();
        int type = byteBuffer.getInt();
        int size = byteBuffer.getInt();
        boolean ok = false;

        switch (type) {
        case AVOS_MSG_TYPE_INT:
            ok = appendInt(id, byteBuffer.getInt());
            break;
        case AVOS_MSG_TYPE_INT64:
            ok = appendLong(id, byteBuffer.getLong());
            break;
        case AVOS_MSG_TYPE_BOOL:
            ok = appendBool(id, byteBuffer.getInt() == 0 ? false : true);
            break;
        case AVOS_MSG_TYPE_STR:
            byte[] data = new byte[size - 1]; // no '\n'
            byteBuffer.get(data);
            ok = appendString(id, data);
            byteBuffer.get();
            break;
        }
        if (!ok) {
            Log.d(TAG, "parse error");
            mParcel.recycle();
            mKeyToPosMap.clear();
            return false;
        }
    }

    int end = mParcel.dataPosition();
    mParcel.setDataPosition(mBegin);
    mParcel.writeInt(end - mBegin);

    mParcel.setDataPosition(mBegin);

    return true;
}
 
Example 19
Project: MetadataEditor   File: ID3SyncSafeInteger.java   View Source Code Vote up 3 votes
/**
 * Read syncsafe value from buffer in format specified in spec and convert to int.
 *
 * The buffers position is moved to just after the location of the syncsafe integer
 *
 * @param buffer syncsafe integer
 * @return decoded int
 */
public static int bufferToValue(ByteBuffer buffer)
{
    byte byteBuffer[] = new byte[INTEGRAL_SIZE];
    buffer.get(byteBuffer, 0, INTEGRAL_SIZE);
    return bufferToValue(byteBuffer);
}
 
Example 20
Project: incubator-netbeans   File: Archive.java   View Source Code Vote up 3 votes
public @Override boolean equals(Object o) {
    if (! (o instanceof Entry)) return false;
    Entry e = (Entry)o;
    
    if (source != e.master.getChar(e.offset)) return false;
    if (utf.length != e.master.getChar(e.offset+6)) return false;

    ByteBuffer clone = e.master.duplicate();
    clone.position(((Entry)o).offset+8);
    
    
    for (byte b : utf) if (b != clone.get()) return false;

    return true;
}