Example usage for java.nio ByteBuffer allocate

List of usage examples for java.nio ByteBuffer allocate

Introduction

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

Prototype

public static ByteBuffer allocate(int capacity) 

Source Link

Document

Creates a byte buffer based on a newly allocated byte array.

Usage

From source file:ch.cyberduck.core.cryptomator.features.CryptoReadFeature.java

@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback)
        throws BackgroundException {
    try {/*from w w w  . j ava 2s . c  om*/
        final Path encrypted = vault.encrypt(session, file);
        // Header
        final Cryptor cryptor = vault.getCryptor();
        final TransferStatus headerStatus = new TransferStatus(status);
        headerStatus.setOffset(0);
        final InputStream in = proxy.read(encrypted,
                headerStatus.length(status.isAppend() ? cryptor.fileHeaderCryptor().headerSize()
                        : vault.toCiphertextSize(status.getLength())),
                callback);
        final ByteBuffer headerBuffer = ByteBuffer.allocate(cryptor.fileHeaderCryptor().headerSize());
        final int read = IOUtils.read(in, headerBuffer.array());
        final FileHeader header = cryptor.fileHeaderCryptor().decryptHeader(headerBuffer);
        if (status.isAppend()) {
            IOUtils.closeQuietly(in);
            final TransferStatus s = new TransferStatus(status).length(-1L);
            s.setOffset(this.align(status.getOffset()));
            final CryptoInputStream crypto = new CryptoInputStream(proxy.read(encrypted, s, callback), cryptor,
                    header, this.chunk(status.getOffset()));
            crypto.skip(this.position(status.getOffset()));
            return crypto;
        } else {
            return new CryptoInputStream(in, cryptor, header, vault.numberOfChunks(status.getOffset()));
        }
    } catch (IOException e) {
        throw new DefaultIOExceptionMappingService().map(e);
    }
}

From source file:com.liveramp.commons.util.BytesUtils.java

public static ByteBuffer byteBufferDeepCopy(ByteBuffer src) {
    ByteBuffer copy = ByteBuffer.allocate(src.remaining()).put(src.slice());
    copy.flip();//  w  w w  . j a v  a2  s .c o  m
    return copy;
}

From source file:byps.test.TestSerializePrimitiveTypes.java

public void internalTestBufferRealloc(ByteOrder border) throws BException {
    ByteBuffer buf = ByteBuffer.allocate(17);
    buf.order(border);//from ww  w.j av  a 2  s .  com
    BBuffer bbuf = BBuffer.create(TestUtils.protocol, buf);
    int count = 3;

    for (int i = 0; i < count; i++) {
        bbuf.putDouble(i);
    }
    bbuf.flip();

    TestUtils.printBuffer(log, bbuf);

    if (TestUtils.protocol == BProtocolJson.BINARY_MODEL) {
        BBufferJson jbuf = (BBufferJson) bbuf;
        for (int i = 0; i < count; i++) {
            if (i != 0)
                jbuf.nextExpectedJsonChar(',', true);
            double d = bbuf.getDouble();
            TestUtils.assertEquals(log, "double[" + i + "]", (double) i, d);
        }
    } else {
        for (int i = 0; i < count; i++) {
            double d = bbuf.getDouble();
            TestUtils.assertEquals(log, "double[" + i + "]", (double) i, d);
        }
    }
}

From source file:gridool.communication.transport.nio.GridNioServer.java

public GridNioServer(@Nonnull GridConfiguration config) {
    this.config = config;
    this.sharedReadBuf = ByteBuffer.allocate(8192);
    int nthreads = config.getMessageProcessorPoolSize();
    this.execPool = ExecutorFactory.newFixedThreadPool(nthreads, "NioMessageProcessor");
}

From source file:org.alfresco.contentstore.patch.PatchServiceImpl.java

@Override
public void getPatch(PatchDocument patchDocument, NodeChecksums nodeChecksums, ReadableByteChannel inChannel)
        throws IOException {
    ByteBuffer buffer = ByteBuffer.allocate(1024 * 100);
    inChannel.read(buffer);/*from w  w w.j  a  v a 2  s  . c o  m*/
    buffer.flip();

    updatePatchDocument(patchDocument, nodeChecksums, buffer);
}

From source file:com.hazelcast.simulator.probes.probes.impl.HdrLatencyDistributionResult.java

@Override
public void writeTo(XMLStreamWriter writer) {
    Histogram tmp = histogram.copy();//ww w. ja  v  a  2s .co  m
    int size = tmp.getNeededByteBufferCapacity();
    ByteBuffer byteBuffer = ByteBuffer.allocate(size);
    int bytesWritten = tmp.encodeIntoCompressedByteBuffer(byteBuffer);
    byteBuffer.rewind();
    byteBuffer.limit(bytesWritten);
    String encodedData = Base64.encodeBase64String(byteBuffer.array());
    try {
        writer.writeStartElement(ProbesResultXmlElements.HDR_LATENCY_DATA.getName());
        writer.writeCData(encodedData);
        writer.writeEndElement();
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.codeabovelab.dm.common.security.token.SignedTokenServiceBackend.java

private byte[] contentPack(long creationTime, byte[] random, byte[] serverSecret, byte[] payload) {
    ByteBuffer buffer = ByteBuffer
            .allocate(8 + 1 + random.length + 1 + serverSecret.length + 1 + payload.length);
    buffer.putLong(creationTime);/* w ww. j a va2  s.co m*/
    store(buffer, random);
    store(buffer, serverSecret);
    store(buffer, payload);
    return buffer.array();
}

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.  ja v  a 2  s  .  co 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:com.byteatebit.nbserver.task.TestWriteMessageTask.java

@Test
public void testWriteCompleteMessage() throws IOException {
    SocketChannel socket = mock(SocketChannel.class);
    ByteArrayOutputStream messageStream = new ByteArrayOutputStream();
    String message = "hi\n";
    when(socket.write(any(ByteBuffer.class))).then(new Answer<Integer>() {
        @Override//  w  w  w  .j a  v a 2s .  c om
        public Integer answer(InvocationOnMock invocationOnMock) throws Throwable {
            ByteBuffer buffer = (ByteBuffer) invocationOnMock.getArguments()[0];
            while (buffer.hasRemaining())
                messageStream.write(buffer.get());
            return buffer.position();
        }
    });
    INbContext nbContext = mock(INbContext.class);
    SelectionKey selectionKey = mock(SelectionKey.class);
    when(selectionKey.channel()).thenReturn(socket);
    when(selectionKey.isValid()).thenReturn(true);
    when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_WRITE);

    WriteMessageTask writeTask = WriteMessageTask.Builder.builder().withByteBuffer(ByteBuffer.allocate(100))
            .build();
    List<String> callbackInvoked = new ArrayList<>();
    Runnable callback = () -> callbackInvoked.add("");
    Consumer<Exception> exceptionHandler = e -> Assert.fail(e.getMessage());
    writeTask.writeMessage(message.getBytes(StandardCharsets.UTF_8), nbContext, socket, callback,
            exceptionHandler);
    verify(nbContext, times(1)).register(any(SocketChannel.class), eq(SelectionKey.OP_WRITE), any(), any());
    writeTask.write(selectionKey, callback, exceptionHandler);
    verify(selectionKey, times(1)).interestOps(0);

    Assert.assertEquals(message, messageStream.toString(StandardCharsets.UTF_8));
    Assert.assertEquals(1, callbackInvoked.size());
}

From source file:jsave.Utils.java

public static long read_uint32(final RandomAccessFile raf) throws IOException {
    byte[] data = new byte[4];
    raf.read(data);// w w w  . ja  va2 s  .c  o  m
    ByteBuffer bb = ByteBuffer.allocate(data.length);
    bb.put(data);
    return getUnsignedInt(bb);
}