Example usage for java.nio ByteBuffer put

List of usage examples for java.nio ByteBuffer put

Introduction

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

Prototype

public ByteBuffer put(ByteBuffer src) 

Source Link

Document

Writes all the remaining bytes of the src byte buffer to this buffer's current position, and increases both buffers' position by the number of bytes copied.

Usage

From source file:io.undertow.server.WriteTimeoutTestCase.java

@Test
public void testWriteTimeout() throws IOException, InterruptedException {
    DefaultServer.setRootHandler(new HttpHandler() {
        @Override// ww w  .  j ava  2  s  .  com
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            final StreamSinkChannel response = exchange.getResponseChannel();
            try {
                response.setOption(Options.WRITE_TIMEOUT, 10);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            final int capacity = 1 * 1024 * 1024; //1mb

            final ByteBuffer originalBuffer = ByteBuffer.allocateDirect(capacity);
            for (int i = 0; i < capacity; ++i) {
                originalBuffer.put((byte) '*');
            }
            originalBuffer.flip();
            response.getWriteSetter().set(new ChannelListener<Channel>() {

                private ByteBuffer buffer = originalBuffer.duplicate();
                int count = 0;

                @Override
                public void handleEvent(final Channel channel) {
                    do {
                        try {
                            int res = response.write(buffer);
                            if (res == 0) {
                                return;
                            }
                        } catch (IOException e) {
                            exception = e;
                            errorLatch.countDown();
                        }
                        if (!buffer.hasRemaining()) {
                            count++;
                            buffer = originalBuffer.duplicate();
                        }
                    } while (count < 1000);
                    exchange.endExchange();
                }
            });
            response.wakeupWrites();
        }
    });

    final TestHttpClient client = new TestHttpClient();
    try {
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL());
        try {
            HttpResponse result = client.execute(get);
            InputStream content = result.getEntity().getContent();
            byte[] buffer = new byte[512];
            int r = 0;
            while ((r = content.read(buffer)) > 0) {
                Thread.sleep(200);
                if (exception != null) {
                    Assert.assertEquals(WriteTimeoutException.class, exception.getClass());
                    return;
                }
            }
            Assert.fail("Write did not time out");
        } catch (IOException e) {
            if (errorLatch.await(5, TimeUnit.SECONDS)) {
                Assert.assertEquals(WriteTimeoutException.class, exception.getClass());
            } else {
                Assert.fail("Write did not time out");
            }
        }
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:client.MultiplexingClient.java

/**
 * Creates a new packet with a size chosen randomly between
 * MIN_SIZE and MAX_SIZE. /*from   ww w.j  a v  a2  s. co m*/
 */
private ByteBuffer generateNextPacket() {
    // Generate a random size between 
    int size = MIN_SIZE + r.nextInt(maxPcktSize - MIN_SIZE);
    ByteBuffer buffer = ByteBuffer.allocate(size);
    buffer.put(SimpleProtocolDecoder.STX);
    for (int i = 0; i < size - 2; i++) {
        buffer.put((byte) ('0' + (i % 10)));
    }
    buffer.put(SimpleProtocolDecoder.ETX);
    buffer.limit(buffer.position());
    buffer.flip();
    return buffer;
}

From source file:com.offbynull.portmapper.pcp.PcpRequest.java

/**
 * Dump this PCP request in to a byte buffer.
 * @param dst byte buffer to dump to/*from   w w w . j a  v  a  2s.  co  m*/
 * @param selfAddress IP address of this machine on the interface used to access the PCP server
 * @throws NullPointerException if any argument is {@code null}
 * @throws BufferOverflowException if {@code dst} doesn't have enough space to write this option
 * @throws ReadOnlyBufferException if {@code dst} is read-only
 */
public final void dump(ByteBuffer dst, InetAddress selfAddress) {
    Validate.notNull(dst);
    Validate.notNull(selfAddress);

    dst.put((byte) 2);
    dst.put((byte) op); // topmost bit should be 0, because op is between 0 to 127, which means r-flag = 0
    dst.putShort((short) 0);
    dst.putInt((int) lifetime);

    byte[] selfAddressArr = selfAddress.getAddress();
    switch (selfAddressArr.length) {
    case 4: {
        // convert ipv4 address to ipv4-mapped ipv6 address
        for (int i = 0; i < 10; i++) {
            dst.put((byte) 0);
        }

        for (int i = 0; i < 2; i++) {
            dst.put((byte) 0xff);
        }

        dst.put(selfAddressArr);
        break;
    }
    case 16: {
        dst.put(selfAddressArr);
        break;
    }
    default:
        throw new IllegalArgumentException(); // should never happen
    }

    dumpOpCodeSpecificInformation(dst);

    for (PcpOption option : options) {
        option.dump(dst);
    }
}

From source file:com.tera.common.network.nio.MMOConnection.java

final void movePendingWriteBufferTo(ByteBuffer dest) {
    primaryWriteBuffer.flip();/*from w  ww  .j  av a  2 s .  co  m*/
    dest.put(primaryWriteBuffer);
    getReadWriteThread().recycleBuffer(primaryWriteBuffer);
    primaryWriteBuffer = secondaryWriteBuffer;
    secondaryWriteBuffer = null;
}

From source file:Base64Encoder.java

/**
 * Encodes one or more characters into one or more bytes.
 *
 * <p> This method encapsulates the basic encoding loop, encoding as many
 * characters as possible until it either runs out of input, runs out of room
 * in the output buffer, or encounters an encoding error.  This method is
 * invoked by the {@link #encode encode} method, which handles result
 * interpretation and error recovery.//from   w w w .  j av a 2  s. c  om
 *
 * <p> The buffers are read from, and written to, starting at their current
 * positions.  At most {@link Buffer#remaining in.remaining()} characters
 * will be read, and at most {@link Buffer#remaining out.remaining()}
 * bytes will be written.  The buffers' positions will be advanced to
 * reflect the characters read and the bytes written, but their marks and
 * limits will not be modified.
 *
 * <p> This method returns a {@link CoderResult} object to describe its
 * reason for termination, in the same manner as the {@link #encode encode}
 * method.  Most implementations of this method will handle encoding errors
 * by returning an appropriate result object for interpretation by the
 * {@link #encode encode} method.  An optimized implementation may instead
 * examine the relevant error action and implement that action itself.
 *
 * <p> An implementation of this method may perform arbitrary lookahead by
 * returning {@link CoderResult#UNDERFLOW} until it receives sufficient
 * input.  </p>
 *
 * @param  in
 *         The input character buffer
 *
 * @param  out
 *         The output byte buffer
 *
 * @return  A coder-result object describing the reason for termination
 */
public java.nio.charset.CoderResult encodeLoop(java.nio.CharBuffer in, java.nio.ByteBuffer out) {
    if (excessByte != null) {
        if (out.remaining() > 0) {
            out.put(excessByte.byteValue());
            excessByte = null;
        } else
            return CoderResult.OVERFLOW;

    }
    while (in.remaining() > 0) {
        char inch = in.get();
        int code = (int) inch >= encTable.length ? CHARCODE_INVALID : encTable[(int) inch];
        if (encState < 4) {
            switch (code) {
            case CHARCODE_INVALID:
                throw new IllegalArgumentException("Invalid base-64 character'" + inch + "'");
            case CHARCODE_WHITESPACE:
                break;
            case CHARCODE_PADDER:
                if (encState == 1)
                    throw new IllegalArgumentException("Mal-formed base-64 (= after one character");
                encState = 4;
                break;
            default:
                switch (encState) {
                case 0:
                    bits = code << 2;
                    encState = 1;
                    break;
                case 1:
                    encState = 2;
                    int v = bits | ((code >> 4) & 3);
                    bits = (code << 4) & 0xF0;
                    if (!out(out, v))
                        return CoderResult.OVERFLOW;
                    break;
                case 2:
                    encState = 3;
                    v = bits | (code >> 2) & 0x0f;
                    bits = (code << 6) & 0xC0;
                    if (!out(out, v))
                        return CoderResult.OVERFLOW;
                    break;
                case 3:
                    encState = 0;
                    bits |= (code & 0x3f);
                    if (!out(out, bits))
                        return CoderResult.OVERFLOW;
                    break;
                }

                break;
            }

        }
    }
    return CoderResult.UNDERFLOW;
}

From source file:com.buaa.cfs.common.oncrpc.XDR.java

private void ensureFreeSpace(int size) {
    Preconditions.checkState(state == State.WRITING);
    if (buf.remaining() < size) {
        int newCapacity = buf.capacity() * 2;
        int newRemaining = buf.capacity() + buf.remaining();

        while (newRemaining < size) {
            newRemaining += newCapacity;
            newCapacity *= 2;//w  w  w.j  ava 2s. com
        }

        ByteBuffer newbuf = ByteBuffer.allocate(newCapacity);
        buf.flip();
        newbuf.put(buf);
        buf = newbuf;
    }
}

From source file:io.druid.query.search.FragmentSearchQuerySpec.java

@Override
public byte[] getCacheKey() {
    if (values == null) {
        return ByteBuffer.allocate(2).put(CACHE_TYPE_ID).put(caseSensitive ? (byte) 1 : 0).array();
    }//w  ww .j av  a2  s . c o  m

    final byte[][] valuesBytes = new byte[values.size()][];
    int valuesBytesSize = 0;
    int index = 0;
    for (String value : values) {
        valuesBytes[index] = StringUtils.toUtf8(value);
        valuesBytesSize += valuesBytes[index].length;
        ++index;
    }

    final ByteBuffer queryCacheKey = ByteBuffer.allocate(2 + valuesBytesSize).put(CACHE_TYPE_ID)
            .put(caseSensitive ? (byte) 1 : 0);

    for (byte[] bytes : valuesBytes) {
        queryCacheKey.put(bytes);
    }

    return queryCacheKey.array();
}

From source file:com.robonobo.eon.DEONConnection.java

void receivePacket(EONPacket eonPacket) {
    DEONPacket packet = (DEONPacket) eonPacket;
    ByteBuffer buf = ByteBuffer.allocate(packet.getPayload().limit());
    buf.put(packet.getPayload());
    buf.flip();// www  . j  a v  a2  s .  co m
    EonSocketAddress addr = packet.getSourceSocketAddress();
    receiveLock.lock();
    try {
        incomingDataBufs.add(buf);
        incomingDataAddrs.add(addr);
        if (dataReceiver == null)
            canReceive.signal();
        else {
            // Async read
            if (dataReceiverRunning) // This will be picked up by the already-running receiver
                return;
            else
                fireAsyncReceiver();
        }
    } finally {
        receiveLock.unlock();
    }
}

From source file:com.unister.semweb.drums.api.DRUMSTest.java

/**
 * This method is for testing the binary search in DRUMS.findElementInReadBuffer()
 * //from  ww w. jav a2s  . co  m
 * @throws IOException
 * @throws ClassNotFoundException
 */
@Test
public void findElementInReadBufferTest() throws IOException, ClassNotFoundException {
    log.info("Test Binary search. findElementInReadBufferTest()");
    DRUMS<DummyKVStorable> table = DRUMSInstantiator.createOrOpenTable(hashFunction, TestUtils.gp);
    // create data
    DummyKVStorable d1 = DummyKVStorable.getInstance();
    d1.setKey(new byte[] { 0, 0, 0, 0, 0, 0, 0, 1 });
    DummyKVStorable d2 = DummyKVStorable.getInstance();
    d2.setKey(new byte[] { 0, 0, 0, 0, 0, 0, 0, 2 });
    DummyKVStorable d3 = DummyKVStorable.getInstance();
    d3.setKey(new byte[] { 0, 0, 0, 0, 0, 0, 0, 3 });
    ByteBuffer bb = ByteBuffer.allocate(3 * TestUtils.gp.getElementSize());
    bb.put(d1.toByteBuffer().array());
    bb.put(d2.toByteBuffer().array());
    bb.put(d3.toByteBuffer().array());

    Assert.assertEquals(-1, table.findElementInReadBuffer(bb, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }, 0));
    Assert.assertEquals(0, table.findElementInReadBuffer(bb, new byte[] { 0, 0, 0, 0, 0, 0, 0, 1 }, 0));
    Assert.assertEquals(1 * TestUtils.gp.getElementSize(),
            table.findElementInReadBuffer(bb, new byte[] { 0, 0, 0, 0, 0, 0, 0, 2 }, 0));
    Assert.assertEquals(2 * TestUtils.gp.getElementSize(),
            table.findElementInReadBuffer(bb, new byte[] { 0, 0, 0, 0, 0, 0, 0, 3 }, 0));
    Assert.assertEquals(2 * TestUtils.gp.getElementSize(), table.findElementInReadBuffer(bb,
            new byte[] { 0, 0, 0, 0, 0, 0, 0, 3 }, 1 * TestUtils.gp.getElementSize()));
    Assert.assertEquals(2 * TestUtils.gp.getElementSize(), table.findElementInReadBuffer(bb,
            new byte[] { 0, 0, 0, 0, 0, 0, 0, 3 }, 2 * TestUtils.gp.getElementSize()));
    Assert.assertEquals(-1, table.findElementInReadBuffer(bb, new byte[] { 0, 0, 0, 0, 0, 0, 0, 3 },
            3 * TestUtils.gp.getElementSize()));
}

From source file:com.tera.common.network.nio.MMOConnection.java

final void createWriteBuffer(ByteBuffer buf) {
    if (primaryWriteBuffer == null) {
        // APPENDING FOR NULL

        primaryWriteBuffer = getReadWriteThread().getPooledBuffer();
        primaryWriteBuffer.put(buf);//from w  ww.  java2 s .  c om
    } else {
        // PREPENDING ON EXISTING

        ByteBuffer temp = getReadWriteThread().getPooledBuffer();
        temp.put(buf);

        int remaining = temp.remaining();
        primaryWriteBuffer.flip();
        int limit = primaryWriteBuffer.limit();

        if (remaining >= primaryWriteBuffer.remaining()) {
            temp.put(primaryWriteBuffer);
            getReadWriteThread().recycleBuffer(primaryWriteBuffer);
            primaryWriteBuffer = temp;
        } else {
            primaryWriteBuffer.limit(remaining);
            temp.put(primaryWriteBuffer);
            primaryWriteBuffer.limit(limit);
            primaryWriteBuffer.compact();
            secondaryWriteBuffer = primaryWriteBuffer;
            primaryWriteBuffer = temp;
        }
    }
}