Example usage for io.netty.buffer ByteBuf getBytes

List of usage examples for io.netty.buffer ByteBuf getBytes

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf getBytes.

Prototype

public abstract int getBytes(int index, GatheringByteChannel out, int length) throws IOException;

Source Link

Document

Transfers this buffer's data to the specified channel starting at the specified absolute index .

Usage

From source file:com.ning.http.client.providers.netty_4.ResponseBodyPart.java

License:Apache License

@Override
public int writeTo(OutputStream outputStream) throws IOException {
    ByteBuf b = getChannelBuffer();
    int available = b.readableBytes();
    if (available > 0) {
        b.getBytes(b.readerIndex(), outputStream, available);
    }/*from w ww  .ja va2 s . c o m*/
    return available;
}

From source file:io.datty.msgpack.core.ValueMessageReader.java

License:Apache License

@Override
public ByteBuf skipValue(ByteBuf source, boolean copy) {

    if (!hasNext(source)) {
        return null;
    }/*from w  w  w. j  a  v  a  2 s .  co m*/

    int startIndex = source.readerIndex();
    skipValue(source);
    int endIndex = source.readerIndex();
    int length = endIndex - startIndex;

    if (copy) {
        ByteBuf dst = source.alloc().buffer(length);
        source.getBytes(startIndex, dst, length);
        return dst;
    } else {
        return source.slice(startIndex, length);
    }

}

From source file:net.tomp2p.storage.AlternativeCompositeByteBuf.java

License:Apache License

@Override
public AlternativeCompositeByteBuf getBytes(int index, OutputStream out, int length) throws IOException {
    checkIndex(index, length);/*from w  w w.  j  av a 2  s. c  om*/
    if (length == 0) {
        return this;
    }

    int i = findIndex(index);
    while (length > 0) {
        Component c = components.get(i);
        ByteBuf s = c.buf;
        int adjustment = c.offset;
        int localLength = Math.min(length, s.readableBytes() - (index - adjustment));
        s.getBytes(index - adjustment, out, localLength);
        index += localLength;
        length -= localLength;
        i++;
    }
    return this;
}

From source file:org.aotorrent.common.Piece.java

License:Apache License

private void writeSync(ByteBuf data, int offset) {
    if (isComplete()) {
        return;//from   w  w  w .j  ava2  s  .  c  o m
    }

    if ((data.readableBytes() + offset) > pieceLength) {
        LOGGER.error("Received block is out of bounds");
        return; //TODO exception
    }

    if (buffer == null) {
        buffer = Unpooled.buffer(pieceLength, pieceLength);
    }

    buffer.writerIndex(offset);
    data.getBytes(0, buffer, data.readableBytes());

    int dataBlocks = (int) Math.ceil((double) data.readableBytes() / (double) DEFAULT_BLOCK_LENGTH);
    int blockOffset = offset / DEFAULT_BLOCK_LENGTH;

    data.release();

    blockComplete.set(blockOffset, blockOffset + dataBlocks);

    if (isAllBlocksComplete()) {
        try {
            byte[] pieceHash = DigestUtils.sha1(buffer.array());

            if (Arrays.equals(pieceHash, hash)) {
                torrent.getFileStorage().store(index, buffer);

                complete = true;
                softBuffer = new SoftReference<>(buffer);
                torrentEngine.setPieceDone(Piece.this);
                torrentEngine.increaseDownloadedCounter(getPieceLength());
            } else {
                LOGGER.debug("Piece index: " + index + " hash invalid. Original:" + Hex.encodeHexString(hash)
                        + " actual: " + Hex.encodeHexString(pieceHash));
                blockComplete.clear();
            }
        } catch (IOException e) {
            LOGGER.error("Can't save piece", e);
        } finally {
            buffer = null;
        }
    }
}

From source file:org.aotorrent.common.storage.FileStorage.java

License:Apache License

public void store(int pieceIndex, ByteBuf byteBuffer) throws IOException {
    Collection<StorageFilesInfo> storageFiles = getAffectedFiles(pieceIndex);

    for (StorageFilesInfo storageFile : storageFiles) {

        ByteBuf buf = Unpooled.buffer((int) storageFile.getLength());
        byteBuffer.getBytes((int) storageFile.getPieceOffset(), buf, (int) storageFile.getLength());

        final File file = storageFile.getFile();

        if (file.getParentFile() != null) {
            //noinspection ResultOfMethodCallIgnored
            file.getParentFile().mkdirs();
        }/*from  ww w .ja v  a 2 s  .c  o m*/

        try (RandomAccessFile randomAccessFile = new RandomAccessFile(file.getCanonicalPath(), "rw")) {
            try (FileChannel fileChannel = randomAccessFile.getChannel()) {
                fileChannel.position(storageFile.getFileOffset());
                fileChannel.write(buf.nioBuffer());
            }
        }
    }
}

From source file:org.apache.hyracks.control.cc.web.ApplicationInstallationHandler.java

License:Apache License

protected void writeToFile(ByteBuf content, final String deploymentDir, final String fileName)
        throws Exception {
    class OutputStreamGetter extends SynchronizableWork {
        private OutputStream os;

        @Override/*from   w w w. ja va 2s  .  co m*/
        protected void doRun() throws Exception {
            FileUtils.forceMkdir(new File(deploymentDir));
            File jarFile = new File(deploymentDir, fileName);
            os = new FileOutputStream(jarFile);
        }
    }
    OutputStreamGetter r = new OutputStreamGetter();
    ccs.getWorkQueue().scheduleAndSync(r);
    try {
        content.getBytes(0, r.os, content.readableBytes());
    } finally {
        r.os.close();
    }
}

From source file:org.opendaylight.controller.netconf.nettyutil.handler.ssh.client.SshClientAdapter.java

License:Open Source License

private void writeImpl(ByteBuf message) throws IOException {
    message.getBytes(0, stdIn, message.readableBytes());
    stdIn.flush();
}

From source file:org.robotbrains.support.web.server.netty.NettyHttpFileUpload.java

License:Apache License

@Override
public boolean copyTo(OutputStream destination) {
    if (hasFile()) {
        try {//w  w  w .j a va  2s .com
            ByteBuf buffer = fileUpload.content();
            buffer.getBytes(0, destination, buffer.readableBytes());

            return true;
        } catch (Exception e) {
            throw SmartSpacesException.newFormattedException(e,
                    "Unable to save uploaded file to output stream");
        }
    } else {
        return false;
    }
}

From source file:se.sics.ktoolbox.croupier.util.CroupierContainerSerializerTest.java

License:Open Source License

@Test
public void testCroupierContainer() {
    Serializer serializer = Serializers.lookupSerializer(CroupierContainer.class);
    CroupierContainer original, copy;//  w w  w .  ja v a  2s  . co m
    ByteBuf serializedOriginal, serializedCopy;

    InetAddress localHost;
    try {
        localHost = InetAddress.getByName("localhost");
    } catch (UnknownHostException ex) {
        throw new RuntimeException(ex);
    }

    IdentifierFactory nodeIdFactory = IdentifierRegistry.lookup(BasicIdentifiers.Values.NODE.toString());
    NatAwareAddressImpl simpleAdr1 = NatAwareAddressImpl
            .open(new BasicAddress(localHost, 10000, nodeIdFactory.randomId()));
    original = new CroupierContainer(simpleAdr1, new TestHelper.TestContent1(1));
    serializedOriginal = Unpooled.buffer();
    serializer.toBinary(original, serializedOriginal);

    serializedCopy = Unpooled.buffer();
    serializedOriginal.getBytes(0, serializedCopy, serializedOriginal.readableBytes());
    copy = (CroupierContainer) serializer.fromBinary(serializedCopy, Optional.absent());

    Assert.assertEquals(original.age, copy.age);
    Assert.assertEquals(original.content, copy.content);
    Assert.assertEquals(original.src.getPrivateAdr(), copy.src.getPrivateAdr());
    Assert.assertEquals(original.src.getPublicAdr(), copy.src.getPublicAdr());
    Assert.assertEquals(original.src.getNatType(), copy.src.getNatType());
    Assert.assertTrue(Objects.equals(((NatAwareAddressImpl) original.src).getParents(),
            ((NatAwareAddressImpl) copy.src).getParents()));
    Assert.assertEquals(0, serializedCopy.readableBytes());
}

From source file:se.sics.ktoolbox.overlaymngr.util.ServiceViewSerializerTest.java

License:Open Source License

@Test
public void testRequest() {
    Serializer serializer = Serializers.lookupSerializer(ServiceView.class);
    ServiceView original, copy;//  w  w w .java 2  s .  co  m
    ByteBuf buf, copyBuf;

    original = new ServiceView();
    //serializer
    buf = Unpooled.buffer();
    serializer.toBinary(original, buf);

    copyBuf = Unpooled.buffer();
    buf.getBytes(0, copyBuf, buf.readableBytes());
    copy = (ServiceView) serializer.fromBinary(copyBuf, Optional.absent());

    Assert.assertEquals(original, copy);
    Assert.assertEquals(0, copyBuf.readableBytes());

    //generic
    buf = Unpooled.buffer();
    Serializers.toBinary(original, buf);

    copyBuf = Unpooled.buffer();
    buf.getBytes(0, copyBuf, buf.readableBytes());
    copy = (ServiceView) Serializers.fromBinary(copyBuf, Optional.absent());

    Assert.assertEquals(original, copy);
    Assert.assertEquals(0, copyBuf.readableBytes());
}