Example usage for java.nio ByteBuffer position

List of usage examples for java.nio ByteBuffer position

Introduction

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

Prototype

public final Buffer position(int newPosition) 

Source Link

Document

Sets the position of this buffer.

Usage

From source file:com.offbynull.portmapper.natpmp.NatPmpReceiver.java

/**
 * Start listening for NAT-PMP events. This method blocks until {@link #stop() } is called.
 * @param listener listener to notify of events
 * @throws IOException if socket error occurs
 * @throws NullPointerException if any argument is {@code null}
 *///from  w  ww.  j  a  v a2s .  c  o  m
public void start(NatPmpEventListener listener) throws IOException {
    Validate.notNull(listener);

    MulticastSocket socket = null;
    try {
        final InetAddress group = InetAddress.getByName("224.0.0.1"); // NOPMD
        final int port = 5350;
        final InetSocketAddress groupAddress = new InetSocketAddress(group, port);

        socket = new MulticastSocket(port);

        if (!currentSocket.compareAndSet(null, socket)) {
            IOUtils.closeQuietly(socket);
            return;
        }

        socket.setReuseAddress(true);

        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            Enumeration<InetAddress> addrs = networkInterface.getInetAddresses();
            while (addrs.hasMoreElements()) { // make sure atleast 1 ipv4 addr bound to interface
                InetAddress addr = addrs.nextElement();

                try {
                    if (addr instanceof Inet4Address) {
                        socket.joinGroup(groupAddress, networkInterface);
                    }
                } catch (IOException ioe) { // NOPMD
                    // occurs with certain interfaces
                    // do nothing
                }
            }
        }

        ByteBuffer buffer = ByteBuffer.allocate(12);
        DatagramPacket data = new DatagramPacket(buffer.array(), buffer.capacity());

        while (true) {
            buffer.clear();
            socket.receive(data);
            buffer.position(data.getLength());
            buffer.flip();

            if (!data.getAddress().equals(gatewayAddress)) { // data isn't from our gateway, ignore
                continue;
            }

            if (buffer.remaining() != 12) { // data isn't the expected size, ignore
                continue;
            }

            int version = buffer.get(0);
            if (version != 0) { // data doesn't have the correct version, ignore
                continue;
            }

            int opcode = buffer.get(1) & 0xFF;
            if (opcode != 128) { // data doesn't have the correct op, ignore
                continue;
            }

            int resultCode = buffer.getShort(2) & 0xFFFF;
            switch (resultCode) {
            case 0:
                break;
            default:
                continue; // data doesn't have a successful result, ignore
            }

            listener.publicAddressUpdated(new ExternalAddressNatPmpResponse(buffer));
        }

    } catch (IOException ioe) {
        if (currentSocket.get() == null) {
            return; // ioexception caused by interruption/stop, so just return without propogating error up
        }

        throw ioe;
    } finally {
        IOUtils.closeQuietly(socket);
        currentSocket.set(null);
    }
}

From source file:com.intel.chimera.stream.AbstractCryptoStreamTest.java

private void byteBufferReadCheck(InputStream in, ByteBuffer buf, int bufPos) throws Exception {
    buf.position(bufPos);
    int n = ((ReadableByteChannel) in).read(buf);
    Assert.assertEquals(bufPos + n, buf.position());
    byte[] readData = new byte[n];
    buf.rewind();//from ww w  .  j  a va  2  s.  c  o  m
    buf.position(bufPos);
    buf.get(readData);
    byte[] expectedData = new byte[n];
    System.arraycopy(data, 0, expectedData, 0, n);
    Assert.assertArrayEquals(readData, expectedData);
}

From source file:io.warp10.quasar.encoder.QuasarTokenEncoder.java

private ByteBuffer toByteBuffer(String strUUID) {
    ByteBuffer buffer = ByteBuffer.allocate(16);
    buffer.order(ByteOrder.BIG_ENDIAN);

    UUID uuid = UUID.fromString(strUUID);

    buffer.putLong(uuid.getMostSignificantBits());
    buffer.putLong(uuid.getLeastSignificantBits());

    buffer.position(0);
    return buffer;
}

From source file:io.github.dsheirer.record.wave.WaveWriter.java

/**
 * Writes the buffer contents to the file.  Assumes that the buffer is full
 * and the first byte of data is at position 0.
 *//*  w ww. ja  v a  2  s .  c  om*/
public void writeData(ByteBuffer buffer) throws IOException {
    buffer.position(0);

    openDataChunk();

    /* Write the full buffer if there is room, respecting the max file size */
    if (mFileChannel.size() + buffer.capacity() < mMaxSize) {
        while (buffer.hasRemaining()) {
            mDataChunkSize += mFileChannel.write(buffer);
        }

        updateTotalSize();
        updateDataChunkSize();
    } else {
        /* Split the buffer to finish filling the current file and then put
         * the leftover into a new file */
        int remaining = (int) (mMaxSize - mFileChannel.size());

        /* Ensure we write full frames to fill up the remaining size */
        remaining -= (int) (remaining % mAudioFormat.getFrameSize());

        byte[] bytes = buffer.array();

        ByteBuffer current = ByteBuffer.wrap(Arrays.copyOf(bytes, remaining));

        ByteBuffer next = ByteBuffer.wrap(Arrays.copyOfRange(bytes, remaining, bytes.length));

        while (current.hasRemaining()) {
            mDataChunkSize += mFileChannel.write(current);
        }

        updateTotalSize();
        updateDataChunkSize();

        rollover();

        openDataChunk();

        while (next.hasRemaining()) {
            mDataChunkSize += mFileChannel.write(next);
        }

        updateTotalSize();
        updateDataChunkSize();
    }
}

From source file:io.github.dsheirer.record.wave.WaveWriter.java

/**
 * Opens a new data chunk if a data chunk is not currently open.  This method can be invoked repeatedly as an
 * assurance that the data chunk header has been written.
 *
 * @throws IOException if there is an error writing the data chunk header.
 *//*from   w  w  w.  j  a  va  2s .c o m*/
private void openDataChunk() throws IOException {
    if (!mDataChunkOpen) {
        if (mFileChannel.size() + 32 >= mMaxSize) {
            rollover();
        }

        ByteBuffer formatChunk = getFormatChunk(mAudioFormat);
        formatChunk.position(0);

        while (formatChunk.hasRemaining()) {
            mFileChannel.write(formatChunk);
        }

        ByteBuffer dataHeader = getDataHeader();
        dataHeader.position(0);

        while (dataHeader.hasRemaining()) {
            mFileChannel.write(dataHeader);
        }

        mDataChunkSizeOffset = mFileChannel.size() - 4;
        mDataChunkSize = 0;
        mDataChunkOpen = true;

        updateTotalSize();
    }
}

From source file:au.org.ala.delta.io.BinFile.java

private void writeBytes(ByteBuffer buffer) {
    try {//from   w  w w  . ja v a2s . c  om
        buffer.position(0);
        _channel.write(buffer);
    } catch (IOException ioex) {
        throw new RuntimeException(ioex);
    }
}

From source file:pl.allegro.tech.hermes.consumers.consumer.sender.http.ByteBufferEntityTest.java

@Test
public void testWriteTo() throws Exception {
    final ByteBuffer bytes = ByteBuffer.wrap("Message content".getBytes(Consts.ASCII));
    final ByteBufferEntity httpentity = new ByteBufferEntity(bytes);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    httpentity.writeTo(out);// w ww  . j  a  v a 2s .  co  m
    byte[] bytes2 = out.toByteArray();
    Assert.assertNotNull(bytes2);
    Assert.assertEquals(bytes.capacity(), bytes2.length);
    bytes.position(0);
    for (int i = 0; i < bytes2.length; i++) {
        Assert.assertEquals(bytes.get(i), bytes2[i]);
    }

    out = new ByteArrayOutputStream();
    httpentity.writeTo(out);
    bytes2 = out.toByteArray();
    Assert.assertNotNull(bytes2);
    Assert.assertEquals(bytes.capacity(), bytes2.length);
    bytes.position(0);
    for (int i = 0; i < bytes.capacity(); i++) {
        Assert.assertEquals(bytes.get(i), bytes2[i]);
    }

    try {
        httpentity.writeTo(null);
        Assert.fail("IllegalArgumentException should have been thrown");
    } catch (final IllegalArgumentException ex) {
        // expected
    }
}

From source file:com.google.flatbuffers.Table.java

/**
 * Get a whole vector as a ByteBuffer./*from   w  ww . j a  va  2  s  .co m*/
 *
 * This is efficient, since it only allocates a new {@link ByteBuffer} object,
 * but does not actually copy the data, it still refers to the same bytes
 * as the original ByteBuffer. Also useful with nested FlatBuffers, etc.
 *
 * @param vector_offset The position of the vector in the byte buffer
 * @param elem_size The size of each element in the array
 * @return The {@link ByteBuffer} for the array
 */
protected ByteBuffer __vector_as_bytebuffer(int vector_offset, int elem_size) {
    int o = __offset(vector_offset);
    if (o == 0)
        return null;
    ByteBuffer bb = this.bb.duplicate().order(ByteOrder.LITTLE_ENDIAN);
    int vectorstart = __vector(o);
    bb.position(vectorstart);
    bb.limit(vectorstart + __vector_len(o) * elem_size);
    return bb;
}

From source file:com.google.flatbuffers.Table.java

/**
 * Create a Java `String` from UTF-8 data stored inside the FlatBuffer.
 *
 * This allocates a new string and converts to wide chars upon each access,
 * which is not very efficient. Instead, each FlatBuffer string also comes with an
 * accessor based on __vector_as_bytebuffer below, which is much more efficient,
 * assuming your Java program can handle UTF-8 data directly.
 *
 * @param offset An `int` index into the Table's ByteBuffer.
 * @return Returns a `String` from the data stored inside the FlatBuffer at `offset`.
 *//*www.j a  v  a2 s. co  m*/
protected String __string(int offset) {
    CharsetDecoder decoder = UTF8_DECODER.get();
    decoder.reset();

    offset += bb.getInt(offset);
    ByteBuffer src = bb.duplicate().order(ByteOrder.LITTLE_ENDIAN);
    int length = src.getInt(offset);
    src.position(offset + SIZEOF_INT);
    src.limit(offset + SIZEOF_INT + length);

    int required = (int) ((float) length * decoder.maxCharsPerByte());
    CharBuffer dst = CHAR_BUFFER.get();
    if (dst == null || dst.capacity() < required) {
        dst = CharBuffer.allocate(required);
        CHAR_BUFFER.set(dst);
    }

    dst.clear();

    try {
        CoderResult cr = decoder.decode(src, dst, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
    } catch (CharacterCodingException x) {
        throw new Error(x);
    }

    return dst.flip().toString();
}

From source file:com.weibo.api.motan.protocol.v2motan.MotanV2Codec.java

/**
 * decode data/*from  w w w. j a va 2  s  .  co m*/
 *
 * @return
 * @throws IOException
 */
@Override
public Object decode(Channel channel, String remoteIp, byte[] data) throws IOException {
    MotanV2Header header = MotanV2Header.buildHeader(data);
    Map<String, String> metaMap = new HashMap<String, String>();
    ByteBuffer buf = ByteBuffer.wrap(data);
    int metaSize = buf.getInt(HEADER_SIZE);
    int index = HEADER_SIZE + 4;
    if (metaSize > 0) {
        byte[] meta = new byte[metaSize];
        buf.position(index);
        buf.get(meta);
        metaMap = decodeMeta(meta);
        index += metaSize;
    }
    int bodySize = buf.getInt(index);
    index += 4;
    Object obj = null;
    if (bodySize > 0) {
        byte[] body = new byte[bodySize];
        buf.position(index);
        buf.get(body);
        if (header.isGzip()) {
            body = ByteUtil.unGzip(body);
        }
        //?
        Serialization serialization = getSerializaiontByNum(header.getSerialize());
        obj = new DeserializableObject(serialization, body);
    }
    if (header.isRequest()) {
        if (header.isHeartbeat()) {
            return DefaultRpcHeartbeatFactory.getDefaultHeartbeatRequest(header.getRequestId());
        } else {
            DefaultRequest request = new DefaultRequest();
            request.setRequestId(header.getRequestId());
            request.setInterfaceName(metaMap.remove(M2_PATH));
            request.setMethodName(metaMap.remove(M2_METHOD));
            request.setParamtersDesc(metaMap.remove(M2_METHOD_DESC));
            request.setAttachments(metaMap);
            if (obj != null) {
                request.setArguments(new Object[] { obj });
            }
            if (metaMap.get(M2_GROUP) != null) {
                request.setAttachment(URLParamType.group.getName(), metaMap.get(M2_GROUP));
            }

            if (StringUtils.isNotBlank(metaMap.get(M2_VERSION))) {
                request.setAttachment(URLParamType.version.getName(), metaMap.get(M2_VERSION));
            }

            return request;
        }

    } else {
        if (header.isHeartbeat()) {
            return DefaultRpcHeartbeatFactory.getDefaultHeartbeatResponse(header.getRequestId());
        }
        DefaultResponse response = new DefaultResponse();
        response.setRequestId(header.getRequestId());
        response.setProcessTime(MathUtil.parseLong(metaMap.remove(M2_PROCESS_TIME), 0));
        response.setAttachments(metaMap);
        if (header.getStatus() == MotanV2Header.MessageStatus.NORMAL.getStatus()) {//???
            response.setValue(obj);
        } else {
            String errmsg = metaMap.remove(M2_ERROR);
            Exception e = ExceptionUtil.fromMessage(errmsg);
            if (e == null) {
                e = (Exception) new MotanServiceException("default remote exception. remote errmsg:" + errmsg);
            }
            response.setException(e);
        }
        return response;
    }

}