Example usage for java.nio ByteBuffer flip

List of usage examples for java.nio ByteBuffer flip

Introduction

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

Prototype

public final Buffer flip() 

Source Link

Document

Flips this buffer.

Usage

From source file:org.apache.hadoop.oncrpc.TestFrameDecoder.java

@Test
public void testMultipleFrames() {
    RpcFrameDecoder decoder = new RpcFrameDecoder();

    // Test multiple frames
    byte[] fragment1 = new byte[4 + 10];
    fragment1[0] = 0; // not final fragment
    fragment1[1] = 0;/*w  w w.  ja v  a2  s  . c  om*/
    fragment1[2] = 0;
    fragment1[3] = (byte) 10; // fragment size = 10 bytes
    assertFalse(XDR.isLastFragment(fragment1));
    assertTrue(XDR.fragmentSize(fragment1) == 10);

    // decoder should wait for the final fragment
    ByteBuffer buffer = ByteBuffer.allocate(4 + 10);
    buffer.put(fragment1);
    buffer.flip();
    ChannelBuffer buf = new ByteBufferBackedChannelBuffer(buffer);
    ChannelBuffer channelBuffer = (ChannelBuffer) decoder.decode(Mockito.mock(ChannelHandlerContext.class),
            Mockito.mock(Channel.class), buf);
    assertTrue(channelBuffer == null);

    byte[] fragment2 = new byte[4 + 10];
    fragment2[0] = (byte) (1 << 7); // final fragment
    fragment2[1] = 0;
    fragment2[2] = 0;
    fragment2[3] = (byte) 10; // fragment size = 10 bytes
    assertTrue(XDR.isLastFragment(fragment2));
    assertTrue(XDR.fragmentSize(fragment2) == 10);

    buffer = ByteBuffer.allocate(4 + 10);
    buffer.put(fragment2);
    buffer.flip();
    buf = new ByteBufferBackedChannelBuffer(buffer);
    channelBuffer = (ChannelBuffer) decoder.decode(Mockito.mock(ChannelHandlerContext.class),
            Mockito.mock(Channel.class), buf);
    assertTrue(channelBuffer != null);
    // Complete frame should have to total size 10+10=20
    assertEquals(20, channelBuffer.readableBytes());
}

From source file:org.apache.nifi.avro.AvroTypeUtil.java

public static ByteBuffer convertByteArray(final Object[] bytes) {
    final ByteBuffer bb = ByteBuffer.allocate(bytes.length);
    for (final Object o : bytes) {
        if (o instanceof Byte) {
            bb.put(((Byte) o).byteValue());
        } else {/*  w  w w.j  ava 2s. com*/
            throw new IllegalTypeConversionException(
                    "Cannot convert value " + bytes + " of type " + bytes.getClass() + " to ByteBuffer");
        }
    }
    bb.flip();
    return bb;
}

From source file:edu.hawaii.soest.kilonalu.adcp.EnsembleHeader.java

/**
 *  Constructor.  This method populates the Header fields from the given
 *  ByteBuffer of data passed in as an argument.
 *
 * @param ensembleBuffer the ByteBuffer that contains the binary ensemble data
 *//*ww w .j  a  va2s . c o m*/
public EnsembleHeader(ByteBuffer ensembleBuffer, Ensemble ensemble) {

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

    // define the temporary arrays for passing bytes
    byte[] oneByte = new byte[1];
    byte[] twoBytes = new byte[2];

    // set each of the Ensemble Header fields n the order that they are 
    // read from the byte stream
    ensembleBuffer.get(twoBytes);
    setHeaderID(twoBytes);
    headerID.flip();
    ensemble.addToByteSum(twoBytes);

    ensembleBuffer.get(twoBytes);
    setNumberOfBytesInEnsemble(twoBytes);
    numberOfBytesInEnsemble.flip();
    ensemble.addToByteSum(twoBytes);

    ensembleBuffer.get(oneByte);
    setHeaderSpare(oneByte);
    headerSpare.flip();
    ensemble.addToByteSum(oneByte);

    ensembleBuffer.get(oneByte);
    setNumberOfDataTypes(oneByte);
    numberOfDataTypes.flip();
    ensemble.addToByteSum(oneByte);

    // set the dataTypeOffsets ByteBuffer size
    dataTypeOffsets = ByteBuffer.allocate(((int) getNumberOfDataTypes().get()) * 2);
    numberOfDataTypes.flip();
    byte[] offsetBytes = new byte[(getNumberOfDataTypes().get() * 2)];
    numberOfDataTypes.flip();
    ensembleBuffer.get(offsetBytes);
    setDataTypeOffsets(offsetBytes);
    dataTypeOffsets.flip();
    ensemble.addToByteSum(offsetBytes);

}

From source file:eu.scape_project.arc2warc.PayloadContent.java

public InputStream getPayloadContentAsInputStream() throws IOException {
    if (length >= buffer.length) {
        File tempDir = org.apache.commons.io.FileUtils.getTempDirectory();
        final File tmp = File.createTempFile(RandomStringUtils.randomAlphabetic(10), "tmp", tempDir);
        tmp.deleteOnExit();//from  w  w  w  .j  a  va  2  s.c o  m
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(tmp);
            copyAndCheck(outputStream);
        } finally {
            IOUtils.closeQuietly(outputStream);
        }
        return new FileInputStream(tmp);
    } else {
        final ByteBuffer wrap = ByteBuffer.wrap(buffer);
        wrap.clear();
        OutputStream outStream = StreamUtils.newOutputStream(wrap);
        copyAndCheck(outStream);
        wrap.flip();
        return StreamUtils.newInputStream(wrap);
    }
}

From source file:com.unister.semweb.drums.file.RepairIndexTest.java

/** Converts the given array of {@link TestStorable} to a consecutive {@link ByteBuffer}. */
private ByteBuffer convert(TestStorable[] toConvert) {
    ByteBuffer converter = ByteBuffer.allocate(toConvert.length * globalParameters.getElementSize());
    for (TestStorable oneTestStorable : toConvert) {
        converter.put(oneTestStorable.toByteBuffer());
    }//from   w  w  w.j a va  2  s. c om
    converter.flip();
    return converter;
}

From source file:ch.cyberduck.core.sds.triplecrypt.CryptoInputStream.java

private int readNextChunk() throws IOException {
    final ByteBuffer ciphertextBuf = ByteBuffer.allocate(SDSSession.DEFAULT_CHUNKSIZE);
    final int read = IOUtils.read(proxy, ciphertextBuf.array());
    if (lastread == 0) {
        return IOUtils.EOF;
    }/*from   w w w. j  a v  a2s  . c  o m*/
    ciphertextBuf.position(read);
    ciphertextBuf.flip();
    try {
        final PlainDataContainer pDataContainer;
        if (read == 0) {
            final PlainDataContainer c1 = cipher
                    .processBytes(createEncryptedDataContainer(ciphertextBuf.array(), read, null));
            final PlainDataContainer c2 = cipher.doFinal(new EncryptedDataContainer(null, tag));
            pDataContainer = new PlainDataContainer(ArrayUtils.addAll(c1.getContent(), c2.getContent()));
        } else {
            pDataContainer = cipher
                    .processBytes(createEncryptedDataContainer(ciphertextBuf.array(), read, null));
        }
        final byte[] content = pDataContainer.getContent();
        buffer = ByteBuffer.allocate(content.length);
        buffer.put(content);
        buffer.flip();
        lastread = read;
        return content.length;
    } catch (CryptoException e) {
        throw new IOException(e);
    }
}

From source file:cn.ac.ncic.mastiff.io.coding.RunLengthEncodingIntReader.java

public byte[] CompressensureDecompressed() throws IOException {
    FlexibleEncoding.ORC.DynamicByteArray dynamicBuffer = new FlexibleEncoding.ORC.DynamicByteArray();
    dynamicBuffer.add(inBuf.getData(), 0, inBuf.getLength());
    ByteBuffer byteBuf = ByteBuffer.allocate(dynamicBuffer.size());
    dynamicBuffer.setByteBuffer(byteBuf, 0, dynamicBuffer.size());
    byteBuf.flip();
    FlexibleEncoding.ORC.InStream instream = FlexibleEncoding.ORC.InStream.create("test", byteBuf, null,
            dynamicBuffer.size());//from w ww.  j a  va2 s . c  o  m
    RunLengthIntegerReader rlein = new RunLengthIntegerReader(instream, true);
    DataOutputBuffer decoding = new DataOutputBuffer();
    //  decompressedSize = bb.getInt();
    decoding.writeInt(decompressedSize);
    decoding.writeInt(numPairs);
    decoding.writeInt(startPos);
    for (int i = 0; i < numPairs; i++) {
        int tmp = (int) rlein.next();
        decoding.writeInt(tmp);
    }
    byteBuf.clear();
    inBuf.close();
    return decoding.getData();
}

From source file:cn.ac.ncic.mastiff.io.coding.RunLengthEncodingIntReader.java

@Override
public byte[] ensureDecompressed() throws IOException {
    FlexibleEncoding.ORC.DynamicByteArray dynamicBuffer = new FlexibleEncoding.ORC.DynamicByteArray();
    dynamicBuffer.add(inBuf.getData(), 12, inBuf.getLength() - 12);
    ByteBuffer byteBuf = ByteBuffer.allocate(dynamicBuffer.size());
    dynamicBuffer.setByteBuffer(byteBuf, 0, dynamicBuffer.size());
    byteBuf.flip();
    FlexibleEncoding.ORC.InStream instream = FlexibleEncoding.ORC.InStream.create("test", byteBuf, null,
            dynamicBuffer.size());//from w ww.  jav  a 2s .  c o  m
    RunLengthIntegerReader rlein = new RunLengthIntegerReader(instream, true);
    DataOutputBuffer decoding = new DataOutputBuffer();
    decoding.writeInt(decompressedSize);
    decoding.writeInt(numPairs);
    decoding.writeInt(startPos);
    for (int i = 0; i < numPairs; i++) {
        int tmp = (int) rlein.next();
        decoding.writeInt(tmp);
    }
    byteBuf.clear();
    inBuf.close();
    return decoding.getData();

}

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

@Test
public void testWriteTimeout() throws IOException, InterruptedException {
    DefaultServer.setRootHandler(new HttpHandler() {
        @Override/*from   w w w .  j a  v a2 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:cn.ac.ncic.mastiff.io.coding.DeltaBinaryBitPackingZigZarIntReader.java

public byte[] CompressensureDecompressed() throws IOException {
    FlexibleEncoding.ORC.DynamicByteArray dynamicBuffer = new FlexibleEncoding.ORC.DynamicByteArray();
    dynamicBuffer.add(inBuf.getData(), 0, inBuf.getLength());
    FlexibleEncoding.Parquet.DeltaBinaryPackingValuesReader reader = new FlexibleEncoding.Parquet.DeltaBinaryPackingValuesReader();
    ByteBuffer byteBuf = ByteBuffer.allocate(dynamicBuffer.size());
    dynamicBuffer.setByteBuffer(byteBuf, 0, dynamicBuffer.size());
    byteBuf.flip();
    reader.initFromPage(numPairs, byteBuf.array(), 0);
    DataOutputBuffer decoding = new DataOutputBuffer();
    decoding.writeInt(decompressedSize);
    decoding.writeInt(numPairs);/*  w  w w .ja  v a  2s  . c om*/
    decoding.writeInt(startPos);
    for (int i = 0; i < numPairs; i++) {

        int tmp = reader.readInteger();
        decoding.writeInt(tmp);
    }
    byteBuf.clear();
    inBuf.close();
    return decoding.getData();
}