Example usage for java.nio ByteBuffer get

List of usage examples for java.nio ByteBuffer get

Introduction

In this page you can find the example usage for java.nio ByteBuffer get.

Prototype

public abstract byte get();

Source Link

Document

Returns the byte at the current position and increases the position by 1.

Usage

From source file:rx.apache.http.consumers.ResponseConsumerEventStream.java

@Override
protected void onByteReceived(ByteBuffer buf, IOControl ioctrl) throws IOException {
    if (parentSubscription.isUnsubscribed()) {
        ioctrl.shutdown();//from  w w w  . j  av  a  2s  . c  om
    }
    while (buf.position() < buf.limit()) {
        byte b = buf.get();
        if (b == 10 || b == 13) {
            if (dataBuffer.hasContent()) {
                contentSubject.onNext(dataBuffer.getBytes());
            }
            dataBuffer.reset();
        } else {
            dataBuffer.addByte(b);
        }
    }
}

From source file:com.btoddb.trellis.common.serialization.JavaSerializer.java

@Override
public Serializable deserialize(final ByteBuffer bb) {
    try {//w w w  . j a v  a2 s  .co m
        ObjectInputStream ois;
        ois = new ObjectInputStream(new InputStream() {
            @Override
            public int read() throws IOException {
                return bb.get();
            }
        });
        Object obj = ois.readObject();
        return (Serializable) obj;
    } catch (IOException e) {
        throw new TrellisException("exception while deserializing Java Serializable object", e);
    } catch (ClassNotFoundException e) {
        throw new TrellisException("exception while deserializing Java Serializable object", e);
    }
}

From source file:edu.umass.cs.gigapaxos.paxospackets.PValuePacket.java

protected PValuePacket(ByteBuffer bbuf) throws UnsupportedEncodingException, UnknownHostException {
    super(bbuf);/*from   w w w  . java  2s  .c o  m*/
    this.ballot = new Ballot(bbuf.getInt(), bbuf.getInt());
    this.recovery = bbuf.get() == (byte) 1;
    this.medianCheckpointedSlot = bbuf.getInt();
    this.noCoalesce = bbuf.get() == (byte) 1;
}

From source file:com.streamsets.pipeline.lib.util.AvroSchemaHelper.java

/**
 * Checks for a magic byte in the data and if present extracts the schemaId
 * @param data byte array representing a kafka message
 * @return parsed schema ID//from www. j  a v  a 2 s .  co m
 */
public Optional<Integer> detectSchemaId(byte[] data) {
    if (data.length < 5) {
        return Optional.empty();
    }

    ByteBuffer wrapped = ByteBuffer.wrap(data);
    // 5 == MAGIC_BYTE + ID_SIZE
    if (wrapped.get() != MAGIC_BYTE) {
        return Optional.empty();
    }

    return Optional.of(wrapped.getInt());
}

From source file:net.jenet.Packet.java

/**
 * Copies part of the given buffer into this packet's data.
 * @param buffer// ww w .  j  a v  a 2 s. c  o m
 *              Buffer to copy from
 * @param fragmentOffset
 *              Position of the first byte to copy
 * @param length
 *              Total number of bytes to copy
 */
public void fromBuffer(ByteBuffer buffer, int fragmentOffset, int length) {
    data.position(fragmentOffset);
    for (int i = 0; i < length; i++) {
        data.put(buffer.get());
    }
    data.position(dataLength);
    data.limit(dataLength);
}

From source file:com.dianping.puma.parser.mysql.event.TableMapEvent.java

@Override
public void doParse(ByteBuffer buf, PumaContext context) throws IOException {
    tableId = PacketUtils.readLong(buf, 6);
    reserved = PacketUtils.readInt(buf, 2);
    databaseNameLength = buf.get();
    databaseName = PacketUtils.readNullTerminatedString(buf);
    tableNameLength = buf.get();//from w  w w.j  a  v a 2  s.co  m
    tableName = PacketUtils.readNullTerminatedString(buf);
    columnCount = PacketUtils.readLengthCodedUnsignedLong(buf);
    columnTypes = PacketUtils.readBytes(buf, columnCount.intValue());
    columnMetadataCount = PacketUtils.readLengthCodedUnsignedLong(buf);

    columnMetadata = Metadata.valueOf(columnTypes, PacketUtils.readBytes(buf, columnMetadataCount.intValue()));
    columnNullabilities = PacketUtils.readBitSet(buf, columnCount.intValue());

    context.getTableMaps().put(tableId, this);
}

From source file:com.byteatebit.nbserver.task.TestWriteMessageTask.java

@Test
public void testWriteMessageInParts() throws IOException {
    SocketChannel socket = mock(SocketChannel.class);
    ByteArrayOutputStream messageStream = new ByteArrayOutputStream();
    String messagePart1 = "messagePart1 ";
    String messagePart2 = "messagePart2";
    String message = messagePart1 + messagePart2;
    when(socket.write(any(ByteBuffer.class))).then(new Answer<Integer>() {
        @Override//  w ww .  j  a v  a  2 s  .  co  m
        public Integer answer(InvocationOnMock invocationOnMock) throws Throwable {
            ByteBuffer buffer = (ByteBuffer) invocationOnMock.getArguments()[0];
            for (int i = 0; i < messagePart1.length(); i++)
                messageStream.write(buffer.get());
            return messagePart1.length();
        }
    }).then(new Answer<Integer>() {
        @Override
        public Integer answer(InvocationOnMock invocationOnMock) throws Throwable {
            ByteBuffer buffer = (ByteBuffer) invocationOnMock.getArguments()[0];
            for (int i = 0; i < messagePart2.length(); i++)
                messageStream.write(buffer.get());
            return messagePart2.length();
        }
    });
    INbContext nbContext = mock(INbContext.class);
    SelectionKey selectionKey = mock(SelectionKey.class);
    when(selectionKey.channel()).thenReturn(socket);
    when(selectionKey.isValid()).thenReturn(true);
    when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_WRITE);

    WriteMessageTask writeTask = WriteMessageTask.Builder.builder().withByteBuffer(ByteBuffer.allocate(100))
            .build();
    List<String> callbackInvoked = new ArrayList<>();
    Runnable callback = () -> callbackInvoked.add("");
    Consumer<Exception> exceptionHandler = e -> Assert.fail(e.getMessage());
    writeTask.writeMessage(message.getBytes(StandardCharsets.UTF_8), nbContext, socket, callback,
            exceptionHandler);
    verify(nbContext, times(1)).register(any(SocketChannel.class), eq(SelectionKey.OP_WRITE), any(), any());
    // simulate first write
    writeTask.write(selectionKey, callback, exceptionHandler);
    verify(selectionKey, times(0)).interestOps(0);
    // simulate second write
    writeTask.write(selectionKey, callback, exceptionHandler);
    verify(selectionKey, times(1)).interestOps(0);

    Assert.assertEquals(message, messageStream.toString(StandardCharsets.UTF_8));
    Assert.assertEquals(1, callbackInvoked.size());
}

From source file:com.hortonworks.registries.schemaregistry.serdes.avro.AvroSnapshotDeserializer.java

protected SchemaIdVersion retrieveSchemaIdVersion(InputStream payloadInputStream) throws SerDesException {
    // it can be enhanced to have respective protocol handlers for different versions
    // first byte is protocol version/id.
    // protocol format:
    // 1 byte  : protocol version
    // 8 bytes : schema metadata Id
    // 4 bytes : schema version
    ByteBuffer byteBuffer = ByteBuffer.allocate(13);
    try {/*from  www. j a  v  a  2s  .  co m*/
        payloadInputStream.read(byteBuffer.array());
    } catch (IOException e) {
        throw new SerDesException(e);
    }

    byte protocolId = byteBuffer.get();
    if (protocolId != AvroSchemaProvider.CURRENT_PROTOCOL_VERSION) {
        throw new SerDesException(
                "Unknown protocol id [" + protocolId + "] received while deserializing the payload");
    }
    long schemaMetadataId = byteBuffer.getLong();
    int schemaVersion = byteBuffer.getInt();

    return new SchemaIdVersion(schemaMetadataId, schemaVersion);
}

From source file:io.warp10.continuum.gts.GTSDecoder.java

public static GTSDecoder fromBlock(byte[] block, byte[] key) throws IOException {

    if (block.length < 6) {
        throw new IOException("Invalid block.");
    }//from   w w  w .j a va2 s.  c  o  m

    ByteBuffer buffer = ByteBuffer.wrap(block);

    //
    // Extract size
    //

    buffer.order(ByteOrder.BIG_ENDIAN);
    int size = buffer.getInt();

    // Check size

    if (block.length != size) {
        throw new IOException("Invalid block size, expected " + size + ", block is " + block.length);
    }

    // Extract compression

    byte comp = buffer.get();

    boolean compress = false;

    if (0 == comp) {
        compress = false;
    } else if (1 == comp) {
        compress = true;
    } else {
        throw new IOException("Invalid compression flag");
    }

    // Extract base timestamp

    long base = Varint.decodeSignedLong(buffer);

    InputStream in;

    ByteArrayInputStream bain = new ByteArrayInputStream(block, buffer.position(), buffer.remaining());

    if (compress) {
        in = new GZIPInputStream(bain);
    } else {
        in = bain;
    }

    byte[] buf = new byte[1024];

    ByteArrayOutputStream out = new ByteArrayOutputStream(buffer.remaining());

    while (true) {
        int len = in.read(buf);

        if (len <= 0) {
            break;
        }
        out.write(buf, 0, len);
    }

    GTSDecoder decoder = new GTSDecoder(base, key, ByteBuffer.wrap(out.toByteArray()));

    return decoder;
}

From source file:com.kylinolap.common.hll.HyperLogLogPlusCounter.java

public void readRegisters(ByteBuffer in) throws IOException {
    byte scheme = in.get();
    if ((scheme & COMPRESSION_FLAG) > 0) {
        scheme ^= COMPRESSION_FLAG;/*from ww  w .j  av  a 2s . c  om*/
        int compressedLen = BytesUtil.readVInt(in);
        int end = in.position() + compressedLen;
        byte[] decompressed = DEFAULT_COMPRESSOR.decompress(in, in.position(), compressedLen);
        in.position(end);
        in = ByteBuffer.wrap(decompressed);
    }

    if (scheme == 0) { // map scheme
        clear();
        int size = BytesUtil.readVInt(in);
        if (size > m)
            throw new IllegalArgumentException(
                    "register size (" + size + ") cannot be larger than m (" + m + ")");
        int indexLen = getRegisterIndexSize();
        for (int i = 0; i < size; i++) {
            int key = BytesUtil.readUnsigned(in, indexLen);
            registers[key] = in.get();
        }
    } else { // array scheme
        for (int i = 0; i < m; i++) {
            registers[i] = in.get();
        }
    }
}