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:io.druid.hll.HyperLogLogCollectorTest.java

@Test
public void testFoldWithUpperNibbleTriggersOffsetChange() throws Exception {
    byte[] arr1 = new byte[HyperLogLogCollector.getLatestNumBytesForDenseStorage()];
    Arrays.fill(arr1, (byte) 0x11);
    ByteBuffer buffer1 = ByteBuffer.wrap(arr1);
    buffer1.put(0, HLLCV1.VERSION);/*from   ww w  .j a v  a2s.c  om*/
    buffer1.put(1, (byte) 0);
    buffer1.putShort(2, (short) (2047));
    buffer1.put(HLLCV1.HEADER_NUM_BYTES, (byte) 0x1);

    byte[] arr2 = new byte[HyperLogLogCollector.getLatestNumBytesForDenseStorage()];
    Arrays.fill(arr2, (byte) 0x11);
    ByteBuffer buffer2 = ByteBuffer.wrap(arr2);
    buffer2.put(0, HLLCV1.VERSION);
    buffer2.put(1, (byte) 0);
    buffer2.putShort(2, (short) (2048));

    HyperLogLogCollector collector = HyperLogLogCollector.makeCollector(buffer1);
    collector.fold(buffer2);

    ByteBuffer outBuffer = collector.toByteBuffer();

    Assert.assertEquals(outBuffer.get(), HLLCV1.VERSION);
    Assert.assertEquals(outBuffer.get(), 1);
    Assert.assertEquals(outBuffer.getShort(), 0);
    outBuffer.get();
    outBuffer.getShort();
    Assert.assertFalse(outBuffer.hasRemaining());
}

From source file:io.druid.hll.HyperLogLogCollectorTest.java

@Test
public void testFoldWithDifferentOffsets2() throws Exception {
    ByteBuffer biggerOffset = makeCollectorBuffer(1, (byte) 0x01, 0x11);
    ByteBuffer smallerOffset = makeCollectorBuffer(0, (byte) 0x20, 0x00);

    HyperLogLogCollector collector = HyperLogLogCollector.makeLatestCollector();
    collector.fold(biggerOffset);/*  w ww .ja v  a 2 s  .  c  o m*/
    collector.fold(smallerOffset);

    ByteBuffer outBuffer = collector.toByteBuffer();

    Assert.assertEquals(outBuffer.get(), collector.getVersion());
    Assert.assertEquals(outBuffer.get(), 2);
    Assert.assertEquals(outBuffer.getShort(), 0);
    outBuffer.get();
    outBuffer.getShort();
    Assert.assertFalse(outBuffer.hasRemaining());

    collector = HyperLogLogCollector.makeLatestCollector();
    collector.fold(smallerOffset);
    collector.fold(biggerOffset);

    outBuffer = collector.toByteBuffer();

    Assert.assertEquals(outBuffer.get(), collector.getVersion());
    Assert.assertEquals(outBuffer.get(), 2);
    Assert.assertEquals(outBuffer.getShort(), 0);
    outBuffer.get();
    outBuffer.getShort();
    Assert.assertFalse(outBuffer.hasRemaining());
}

From source file:io.druid.hll.HyperLogLogCollectorTest.java

@Test
public void testSparseFoldWithDifferentOffsets1() throws Exception {
    ByteBuffer biggerOffset = makeCollectorBuffer(1, new byte[] { 0x11, 0x10 }, 0x11);
    ByteBuffer sparse = HyperLogLogCollector
            .makeCollector(makeCollectorBuffer(0, new byte[] { 0x00, 0x02 }, 0x00)).toByteBuffer();

    HyperLogLogCollector collector = HyperLogLogCollector.makeLatestCollector();
    collector.fold(biggerOffset);/*from w w w  .  j a va 2  s  .c o  m*/
    collector.fold(sparse);

    ByteBuffer outBuffer = collector.toByteBuffer();

    Assert.assertEquals(outBuffer.get(), collector.getVersion());
    Assert.assertEquals(outBuffer.get(), 2);
    Assert.assertEquals(outBuffer.getShort(), 0);
    Assert.assertEquals(outBuffer.get(), 0);
    Assert.assertEquals(outBuffer.getShort(), 0);
    Assert.assertFalse(outBuffer.hasRemaining());

    collector = HyperLogLogCollector.makeLatestCollector();
    collector.fold(sparse);
    collector.fold(biggerOffset);

    outBuffer = collector.toByteBuffer();

    Assert.assertEquals(outBuffer.get(), collector.getVersion());
    Assert.assertEquals(outBuffer.get(), 2);
    Assert.assertEquals(outBuffer.getShort(), 0);
    Assert.assertEquals(outBuffer.get(), 0);
    Assert.assertEquals(outBuffer.getShort(), 0);
    Assert.assertFalse(outBuffer.hasRemaining());
}

From source file:io.druid.hll.HyperLogLogCollectorTest.java

@Test
public void testFoldWithDifferentOffsets1() throws Exception {
    ByteBuffer biggerOffset = makeCollectorBuffer(1, (byte) 0x00, 0x11);
    ByteBuffer smallerOffset = makeCollectorBuffer(0, (byte) 0x20, 0x00);

    HyperLogLogCollector collector = HyperLogLogCollector.makeLatestCollector();
    collector.fold(biggerOffset);//from  w  ww. j a v a 2  s .c o  m
    collector.fold(smallerOffset);

    ByteBuffer outBuffer = collector.toByteBuffer();

    Assert.assertEquals(outBuffer.get(), collector.getVersion());
    Assert.assertEquals(outBuffer.get(), 1);
    Assert.assertEquals(outBuffer.getShort(), 2047);
    outBuffer.get();
    outBuffer.getShort();
    Assert.assertEquals(outBuffer.get(), 0x10);
    while (outBuffer.hasRemaining()) {
        Assert.assertEquals(outBuffer.get(), 0x11);
    }

    collector = HyperLogLogCollector.makeLatestCollector();
    collector.fold(smallerOffset);
    collector.fold(biggerOffset);

    outBuffer = collector.toByteBuffer();

    Assert.assertEquals(outBuffer.get(), collector.getVersion());
    Assert.assertEquals(outBuffer.get(), 1);
    Assert.assertEquals(outBuffer.getShort(), 2047);
    Assert.assertEquals(outBuffer.get(), 0);
    Assert.assertEquals(outBuffer.getShort(), 0);
    Assert.assertEquals(outBuffer.get(), 0x10);
    while (outBuffer.hasRemaining()) {
        Assert.assertEquals(outBuffer.get(), 0x11);
    }
}

From source file:io.druid.hll.HyperLogLogCollectorTest.java

@Test
public void testFoldWithArbitraryInitialPositions() throws Exception {
    ByteBuffer biggerOffset = shiftedBuffer(makeCollectorBuffer(1, (byte) 0x00, 0x11), 10);
    ByteBuffer smallerOffset = shiftedBuffer(makeCollectorBuffer(0, (byte) 0x20, 0x00), 15);

    HyperLogLogCollector collector = HyperLogLogCollector.makeLatestCollector();
    collector.fold(biggerOffset);/*from  w ww. j a  va 2  s  .  c  o m*/
    collector.fold(smallerOffset);

    ByteBuffer outBuffer = collector.toByteBuffer();

    Assert.assertEquals(outBuffer.get(), collector.getVersion());
    Assert.assertEquals(outBuffer.get(), 1);
    Assert.assertEquals(outBuffer.getShort(), 2047);
    outBuffer.get();
    outBuffer.getShort();
    Assert.assertEquals(outBuffer.get(), 0x10);
    while (outBuffer.hasRemaining()) {
        Assert.assertEquals(outBuffer.get(), 0x11);
    }

    collector = HyperLogLogCollector.makeLatestCollector();
    collector.fold(smallerOffset);
    collector.fold(biggerOffset);

    outBuffer = collector.toByteBuffer();

    Assert.assertEquals(outBuffer.get(), collector.getVersion());
    Assert.assertEquals(outBuffer.get(), 1);
    Assert.assertEquals(outBuffer.getShort(), 2047);
    outBuffer.get();
    outBuffer.getShort();
    Assert.assertEquals(outBuffer.get(), 0x10);
    while (outBuffer.hasRemaining()) {
        Assert.assertEquals(outBuffer.get(), 0x11);
    }
}

From source file:com.turn.ttorrent.client.ConnectionHandler.java

/**
 * Validate an expected handshake on a connection.
 *
 * <p>//from   w w  w.j  av a  2 s. c o m
 * Reads an expected handshake message from the given connected socket,
 * parses it and validates that the torrent hash_info corresponds to the
 * torrent we're sharing, and that the peerId matches the peer ID we expect
 * to see coming from the remote peer.
 * </p>
 *
 * @param channel The connected socket channel to the remote peer.
 * @param peerId The peer ID we expect in the handshake. If <em>null</em>,
 * any peer ID is accepted (this is the case for incoming connections).
 * @return The validated handshake message object.
 */
private Handshake validateHandshake(SocketChannel channel, byte[] peerId) throws IOException, ParseException {
    ByteBuffer len = ByteBuffer.allocate(1);
    ByteBuffer data;

    // Read the handshake from the wire
    logger.trace("Reading handshake size (1 byte) from {}...", this.socketRepr(channel));
    if (channel.read(len) < len.capacity()) {
        throw new IOException("Handshake size read underrrun");
    }

    len.rewind();
    int pstrlen = len.get();

    data = ByteBuffer.allocate(Handshake.BASE_HANDSHAKE_LENGTH + pstrlen);
    data.put((byte) pstrlen);
    int expected = data.remaining();
    int read = channel.read(data);
    if (read < expected) {
        throw new IOException("Handshake data read underrun (" + read + " < " + expected + " bytes)");
    }

    // Parse and check the handshake
    data.rewind();
    Handshake hs = Handshake.parse(data);
    if (!Arrays.equals(hs.getInfoHash(), this.torrent.getInfoHash())) {
        throw new ParseException("Handshake for unknow torrent " + Utils.bytesToHex(hs.getInfoHash()) + " from "
                + this.socketRepr(channel) + ".", pstrlen + 9);
    }

    if (peerId != null && !Arrays.equals(hs.getPeerId(), peerId)) {
        throw new ParseException("Announced peer ID " + Utils.bytesToHex(hs.getPeerId())
                + " did not match expected peer ID " + Utils.bytesToHex(peerId) + ".", pstrlen + 29);
    }

    return hs;
}

From source file:com.bittorrent.mpetazzoni.client.ConnectionHandler.java

/**
 * Validate an expected handshake on a connection.
 *
 * <p>/*from   w  w  w .  j  ava 2  s  .co m*/
 * Reads an expected handshake message from the given connected socket,
 * parses it and validates that the torrent hash_info corresponds to the
 * torrent we're sharing, and that the peerId matches the peer ID we expect
 * to see coming from the remote peer.
 * </p>
 *
 * @param channel The connected socket channel to the remote peer.
 * @param peerId The peer ID we expect in the handshake. If <em>null</em>,
 * any peer ID is accepted (this is the case for incoming connections).
 * @return The validated handshake message object.
 */
private Handshake validateHandshake(SocketChannel channel, byte[] peerId) throws IOException, ParseException {
    ByteBuffer len = ByteBuffer.allocate(1);
    ByteBuffer data;

    // Read the handshake from the wire
    logger.trace("Reading handshake size (1 byte) from {}...", this.socketRepr(channel));
    if (channel.read(len) < len.capacity()) {
        throw new IOException("Handshake size read underrrun");
    }

    len.rewind();
    int pstrlen = len.get();

    data = ByteBuffer.allocate(Handshake.BASE_HANDSHAKE_LENGTH + pstrlen);
    data.put((byte) pstrlen);
    int expected = data.remaining();
    int read = channel.read(data);
    if (read < expected) {
        throw new IOException("Handshake data read underrun (" + read + " < " + expected + " bytes)");
    }

    // Parse and check the handshake
    data.rewind();
    Handshake hs = Handshake.parse(data);
    if (!Arrays.equals(hs.getInfoHash(), this.torrent.getInfoHash())) {
        throw new ParseException("Handshake for unknow torrent "
                + Torrent.byteArrayToHexString(hs.getInfoHash()) + " from " + this.socketRepr(channel) + ".",
                pstrlen + 9);
    }

    if (peerId != null && !Arrays.equals(hs.getPeerId(), peerId)) {
        throw new ParseException(
                "Announced peer ID " + Torrent.byteArrayToHexString(hs.getPeerId())
                        + " did not match expected peer ID " + Torrent.byteArrayToHexString(peerId) + ".",
                pstrlen + 29);
    }

    return hs;
}

From source file:org.osgp.adapter.protocol.dlms.domain.commands.DlmsHelperService.java

public String getDebugInfoDateTimeBytes(final byte[] dateTimeValue) {

    if (dateTimeValue.length != 12) {
        throw new IllegalArgumentException("DateTime values should be 12 bytes long: " + dateTimeValue.length);
    }/*from  w  w  w.  j  a v a 2s. co  m*/

    final StringBuilder sb = new StringBuilder();

    final ByteBuffer bb = ByteBuffer.wrap(dateTimeValue);
    final int year = bb.getShort();
    final int monthOfYear = bb.get();
    final int dayOfMonth = bb.get();
    final int dayOfWeek = bb.get();
    final int hourOfDay = bb.get();
    final int minuteOfHour = bb.get();
    final int secondOfMinute = bb.get();
    final int hundredthsOfSecond = bb.get();
    final int deviation = bb.getShort();
    final int clockStatus = bb.get();

    sb.append("year=").append(year).append(", month=").append(monthOfYear).append(", day=").append(dayOfMonth)
            .append(", weekday=").append(dayOfWeek).append(", hour=").append(hourOfDay).append(", minute=")
            .append(minuteOfHour).append(", second=").append(secondOfMinute).append(", hundredths=")
            .append(hundredthsOfSecond).append(", deviation=").append(deviation).append(", clockstatus=")
            .append(clockStatus);

    return sb.toString();
}

From source file:org.osgp.adapter.protocol.dlms.domain.commands.DlmsHelperService.java

public com.alliander.osgp.dto.valueobjects.smartmetering.CosemDateTime fromDateTimeValue(
        final byte[] dateTimeValue) throws ProtocolAdapterException {

    final ByteBuffer bb = ByteBuffer.wrap(dateTimeValue);

    final int year = bb.getShort() & 0xFFFF;
    final int monthOfYear = bb.get() & 0xFF;
    final int dayOfMonth = bb.get() & 0xFF;
    final int dayOfWeek = bb.get() & 0xFF;
    final int hourOfDay = bb.get() & 0xFF;
    final int minuteOfHour = bb.get() & 0xFF;
    final int secondOfMinute = bb.get() & 0xFF;
    final int hundredthsOfSecond = bb.get() & 0xFF;
    final int deviation = bb.getShort();
    final byte clockStatusValue = bb.get();

    final com.alliander.osgp.dto.valueobjects.smartmetering.CosemDate date = new com.alliander.osgp.dto.valueobjects.smartmetering.CosemDate(
            year, monthOfYear, dayOfMonth, dayOfWeek);
    final com.alliander.osgp.dto.valueobjects.smartmetering.CosemTime time = new com.alliander.osgp.dto.valueobjects.smartmetering.CosemTime(
            hourOfDay, minuteOfHour, secondOfMinute, hundredthsOfSecond);
    final com.alliander.osgp.dto.valueobjects.smartmetering.ClockStatus clockStatus = new com.alliander.osgp.dto.valueobjects.smartmetering.ClockStatus(
            clockStatusValue);/*from w w  w .java2 s.  c  om*/
    return new com.alliander.osgp.dto.valueobjects.smartmetering.CosemDateTime(date, time, deviation,
            clockStatus);
}

From source file:edu.hawaii.soest.pacioos.text.SocketTextSource.java

@Override
protected boolean execute() {

    log.debug("SocketTextSource.execute() called.");
    // do not execute the stream if there is no connection
    if (!isConnected())
        return false;

    boolean failed = false;

    /* Get a connection to the instrument */
    SocketChannel socket = getSocketConnection();
    if (socket == null)
        return false;

    // while data are being sent, read them into the buffer
    try {/*from  www. j av  a2  s . c  o  m*/
        // create four byte placeholders used to evaluate up to a four-byte 
        // window.  The FIFO layout looks like:
        //           -------------------------
        //   in ---> | One | Two |Three|Four |  ---> out
        //           -------------------------
        byte byteOne = 0x00, // set initial placeholder values
                byteTwo = 0x00, byteThree = 0x00, byteFour = 0x00;

        // Create a buffer that will store the sample bytes as they are read
        ByteBuffer sampleBuffer = ByteBuffer.allocate(getBufferSize());

        // create a byte buffer to store bytes from the TCP stream
        ByteBuffer buffer = ByteBuffer.allocateDirect(getBufferSize());

        // while there are bytes to read from the socket ...
        while (socket.read(buffer) != -1 || buffer.position() > 0) {

            // prepare the buffer for reading
            buffer.flip();

            // while there are unread bytes in the ByteBuffer
            while (buffer.hasRemaining()) {
                byteOne = buffer.get();

                // log the byte stream
                String character = new String(new byte[] { byteOne });
                if (log.isDebugEnabled()) {
                    List<Byte> whitespaceBytes = new ArrayList<Byte>();
                    whitespaceBytes.add(new Byte((byte) 0x0A));
                    whitespaceBytes.add(new Byte((byte) 0x0D));
                    if (whitespaceBytes.contains(new Byte(byteOne))) {
                        character = new String(Hex.encodeHex((new byte[] { byteOne })));

                    }
                }
                log.debug("char: " + character + "\t" + "b1: "
                        + new String(Hex.encodeHex((new byte[] { byteOne }))) + "\t" + "b2: "
                        + new String(Hex.encodeHex((new byte[] { byteTwo }))) + "\t" + "b3: "
                        + new String(Hex.encodeHex((new byte[] { byteThree }))) + "\t" + "b4: "
                        + new String(Hex.encodeHex((new byte[] { byteFour }))) + "\t" + "sample pos: "
                        + sampleBuffer.position() + "\t" + "sample rem: " + sampleBuffer.remaining() + "\t"
                        + "sample cnt: " + sampleByteCount + "\t" + "buffer pos: " + buffer.position() + "\t"
                        + "buffer rem: " + buffer.remaining() + "\t" + "state: " + state);

                // evaluate each byte to find the record delimiter(s), and when found, validate and
                // send the sample to the DataTurbine.
                int numberOfChannelsFlushed = 0;

                if (getRecordDelimiters().length == 2) {
                    // have we hit the delimiters in the stream yet?
                    if (byteTwo == getFirstDelimiterByte() && byteOne == getSecondDelimiterByte()) {
                        sampleBuffer.put(byteOne);
                        sampleByteCount++;
                        // extract just the length of the sample bytes out of the
                        // sample buffer, and place it in the channel map as a 
                        // byte array.  Then, send it to the DataTurbine.
                        log.debug("Sample byte count: " + sampleByteCount);
                        byte[] sampleArray = new byte[sampleByteCount];
                        sampleBuffer.flip();
                        sampleBuffer.get(sampleArray);
                        String sampleString = new String(sampleArray, "US-ASCII");

                        if (validateSample(sampleString)) {
                            numberOfChannelsFlushed = sendSample(sampleString);

                        }

                        sampleBuffer.clear();
                        sampleByteCount = 0;
                        byteOne = 0x00;
                        byteTwo = 0x00;
                        byteThree = 0x00;
                        byteFour = 0x00;
                        log.debug("Cleared b1,b2,b3,b4. Cleared sampleBuffer. Cleared rbnbChannelMap.");

                    } else {
                        // still in the middle of the sample, keep adding bytes
                        sampleByteCount++; // add each byte found

                        if (sampleBuffer.remaining() > 0) {
                            sampleBuffer.put(byteOne);

                        } else {
                            sampleBuffer.compact();
                            log.debug("Compacting sampleBuffer ...");
                            sampleBuffer.put(byteOne);

                        }

                    }

                } else if (getRecordDelimiters().length == 1) {
                    // have we hit the delimiter in the stream yet?
                    if (byteOne == getFirstDelimiterByte()) {
                        sampleBuffer.put(byteOne);
                        sampleByteCount++;
                        // extract just the length of the sample bytes out of the
                        // sample buffer, and place it in the channel map as a 
                        // byte array.  Then, send it to the DataTurbine.
                        byte[] sampleArray = new byte[sampleByteCount];
                        sampleBuffer.flip();
                        sampleBuffer.get(sampleArray);
                        String sampleString = new String(sampleArray, "US-ASCII");

                        if (validateSample(sampleString)) {
                            numberOfChannelsFlushed = sendSample(sampleString);

                        }

                        sampleBuffer.clear();
                        sampleByteCount = 0;
                        byteOne = 0x00;
                        byteTwo = 0x00;
                        byteThree = 0x00;
                        byteFour = 0x00;
                        log.debug("Cleared b1,b2,b3,b4. Cleared sampleBuffer. Cleared rbnbChannelMap.");

                    } else {
                        // still in the middle of the sample, keep adding bytes
                        sampleByteCount++; // add each byte found

                        if (sampleBuffer.remaining() > 0) {
                            sampleBuffer.put(byteOne);

                        } else {
                            sampleBuffer.compact();
                            log.debug("Compacting sampleBuffer ...");
                            sampleBuffer.put(byteOne);

                        }

                    }

                } // end getRecordDelimiters().length

                // shift the bytes in the FIFO window
                byteFour = byteThree;
                byteThree = byteTwo;
                byteTwo = byteOne;

            } //end while (more unread bytes)

            // prepare the buffer to read in more bytes from the stream
            buffer.compact();

        } // end while (more socket bytes to read)
        socket.close();

    } catch (IOException e) {
        // handle exceptions
        // In the event of an i/o exception, log the exception, and allow execute()
        // to return false, which will prompt a retry.
        failed = true;
        log.error("There was a communication error in sending the data sample. The message was: "
                + e.getMessage());
        if (log.isDebugEnabled()) {
            e.printStackTrace();
        }
        return !failed;

    } catch (SAPIException sapie) {
        // In the event of an RBNB communication  exception, log the exception, 
        // and allow execute() to return false, which will prompt a retry.
        failed = true;
        log.error("There was an RBNB error while sending the data sample. The message was: "
                + sapie.getMessage());
        if (log.isDebugEnabled()) {
            sapie.printStackTrace();
        }
        return !failed;
    }

    return !failed;

}