Example usage for java.nio ByteBuffer duplicate

List of usage examples for java.nio ByteBuffer duplicate

Introduction

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

Prototype

public abstract ByteBuffer duplicate();

Source Link

Document

Returns a duplicated buffer that shares its content with this buffer.

Usage

From source file:com.glaf.core.util.ByteBufferUtils.java

/**
 * @return a new copy of the data in @param buffer USUALLY YOU SHOULD USE
 *         ByteBuffer.duplicate() INSTEAD, which creates a new Buffer (so
 *         you can mutate its position without affecting the original)
 *         without copying the underlying array.
 */// w w  w . j a  va 2s.  c  o m
public static ByteBuffer clone(ByteBuffer buffer) {
    assert buffer != null;

    if (buffer.remaining() == 0)
        return EMPTY_BYTE_BUFFER;

    ByteBuffer clone = ByteBuffer.allocate(buffer.remaining());

    if (buffer.hasArray()) {
        System.arraycopy(buffer.array(), buffer.arrayOffset() + buffer.position(), clone.array(), 0,
                buffer.remaining());
    } else {
        clone.put(buffer.duplicate());
        clone.flip();
    }

    return clone;
}

From source file:com.glaf.core.util.ByteBufferUtils.java

/**
 * You should almost never use this. Instead, use the write* methods to
 * avoid copies.//from  ww w .  j a  va2s .  c o m
 */
public static byte[] getArray(ByteBuffer buffer) {
    int length = buffer.remaining();

    if (buffer.hasArray()) {
        int boff = buffer.arrayOffset() + buffer.position();
        if (boff == 0 && length == buffer.array().length)
            return buffer.array();
        else
            return Arrays.copyOfRange(buffer.array(), boff, boff + length);
    }
    // else, DirectByteBuffer.get() is the fastest route
    byte[] bytes = new byte[length];
    buffer.duplicate().get(bytes);

    return bytes;
}

From source file:com.jordanwilliams.heftydb.test.generator.KeyValueGenerator.java

public synchronized ByteBuffer testKey(int size, int reuseWeight) {
    int next = rand.nextInt(100);

    if (next <= reuseWeight && reuseWeight != 0 && testKeys.size() > 0) {
        ByteBuffer existing = testKeys.get(rand.nextInt(testKeys.size()));
        ByteBuffer reusedKey = existing.duplicate();
        reusedKey.rewind();/*from   w  w  w  .j ava 2s .  com*/
        return reusedKey;
    } else {
        ByteBuffer random = randomKey(size);

        if (testKeys.size() < MAX_CACHED_KEYS) {
            testKeys.add(random);
        }

        return random.duplicate();
    }
}

From source file:com.stratagis.geoevent.adapter.nmeaplus.NmeaPlusInboundAdapter.java

@Override
public void receive(ByteBuffer buffer, String channelId) {
    ByteBuffer buffer2 = buffer.duplicate();
    new Thread(new GeoEventProducer(channelId, index(buffer), deviceNameFind(buffer2))).start();
}

From source file:com.easemob.dataexport.utils.ConversionUtils.java

public static Object object(Class<?> type, ByteBuffer bytes) {

    try {//ww  w.ja v  a  2  s .com
        if (Long.class.isAssignableFrom(type)) {
            return bytes.slice().getLong();
        } else if (UUID.class.isAssignableFrom(type)) {
            return uuid(bytes);
        } else if (String.class.isAssignableFrom(type)) {
            return string(bytes);
        } else if (Boolean.class.isAssignableFrom(type)) {
            return bytes.slice().get() != 0;
        } else if (Integer.class.isAssignableFrom(type)) {
            return bytes.slice().getInt();
        } else if (Double.class.isAssignableFrom(type)) {
            return bytes.slice().getDouble();
        } else if (Float.class.isAssignableFrom(type)) {
            return bytes.slice().getFloat();
        } else if (ByteBuffer.class.isAssignableFrom(type)) {
            return bytes.duplicate();
        } else if (byte[].class.isAssignableFrom(type)) {
            byte[] b = new byte[bytes.remaining()];
            bytes.slice().get(b);
            return b;
        }
    } catch (Exception e) {
        logger.error("Unable to get object from bytes for type " + type.getName(), e);
    }
    return null;
}

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

@Test
public void testWriteTimeout() throws IOException, InterruptedException {
    DefaultServer.setRootHandler(new HttpHandler() {
        @Override/*from w w w  .  ja va2s .co  m*/
        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:org.eclipse.jgit.lfs.server.fs.LfsServerTest.java

private void checkResponseStatus(HttpResponse response) {
    StatusLine statusLine = response.getStatusLine();
    int status = statusLine.getStatusCode();
    if (statusLine.getStatusCode() >= 400) {
        String error;/*ww w  . j a  va2 s .c o  m*/
        try {
            ByteBuffer buf = IO.readWholeStream(new BufferedInputStream(response.getEntity().getContent()),
                    1024);
            if (buf.hasArray()) {
                error = new String(buf.array(), buf.arrayOffset() + buf.position(), buf.remaining(), UTF_8);
            } else {
                final byte[] b = new byte[buf.remaining()];
                buf.duplicate().get(b);
                error = new String(b, UTF_8);
            }
        } catch (IOException e) {
            error = statusLine.getReasonPhrase();
        }
        throw new RuntimeException("Status: " + status + " " + error);
    }
    assertEquals(200, status);
}

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

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

    ByteBuffer buffer = ByteBuffer.allocate(HyperLogLogCollector.getLatestNumBytesForDenseStorage());
    HyperLogLogCollector collector = HyperLogLogCollector.makeCollector(buffer.duplicate());

    // make sure the original buffer gets modified
    collector.fold(biggerOffset);/* w  ww.  ja  v  a 2 s .  c  o m*/
    Assert.assertEquals(collector, HyperLogLogCollector.makeCollector(buffer.duplicate()));

    // make sure the original buffer gets modified
    collector.fold(smallerOffset);
    Assert.assertEquals(collector, HyperLogLogCollector.makeCollector(buffer.duplicate()));
}

From source file:com.ery.ertc.estorm.util.Bytes.java

/**
 * Returns a new byte array, copied from the given {@code buf}, from the
 * position (inclusive) to the limit (exclusive). The position and the other
 * index parameters are not changed./* w w w.  jav a 2s  . com*/
 * 
 * @param buf
 *            a byte buffer
 * @return the byte array
 * @see #toBytes(ByteBuffer)
 */
public static byte[] getBytes(ByteBuffer buf) {
    return readBytes(buf.duplicate());
}