Example usage for io.netty.buffer ByteBuf writeBytes

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

Introduction

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

Prototype

public abstract int writeBytes(ScatteringByteChannel in, int length) throws IOException;

Source Link

Document

Transfers the content of the specified channel to this buffer starting at the current writerIndex and increases the writerIndex by the number of the transferred bytes.

Usage

From source file:com.digitalpetri.modbus.codec.ModbusRequestEncoder.java

License:Apache License

public ByteBuf encodeWriteMultipleRegisters(WriteMultipleRegistersRequest request, ByteBuf buffer) {
    buffer.writeByte(request.getFunctionCode().getCode());
    buffer.writeShort(request.getAddress());
    buffer.writeShort(request.getQuantity());

    int byteCount = request.getQuantity() * 2;
    buffer.writeByte(byteCount);/*from w w  w  . j  a v a 2 s  . c om*/

    buffer.writeBytes(request.getValues(), byteCount);

    return buffer;
}

From source file:com.digitalpetri.opcua.stack.core.channel.ChunkEncoder.java

License:Apache License

private List<ByteBuf> encode(Delegate delegate, SecureChannel channel, MessageType messageType,
        ByteBuf messageBuffer, long requestId) throws UaException {

    List<ByteBuf> chunks = new ArrayList<>();

    boolean encrypted = delegate.isEncryptionEnabled(channel);

    int securityHeaderSize = delegate.getSecurityHeaderSize(channel);
    int cipherTextBlockSize = delegate.getCipherTextBlockSize(channel);
    int plainTextBlockSize = delegate.getPlainTextBlockSize(channel);
    int signatureSize = delegate.getSignatureSize(channel);

    int maxChunkSize = parameters.getLocalSendBufferSize();
    int headerSizes = SecureMessageHeader.SECURE_MESSAGE_HEADER_SIZE + securityHeaderSize;
    int paddingOverhead = encrypted ? (cipherTextBlockSize > 256 ? 2 : 1) : 0;

    int maxBlockCount = (maxChunkSize - headerSizes - signatureSize - paddingOverhead) / cipherTextBlockSize;
    int maxBodySize = (plainTextBlockSize * maxBlockCount - SequenceHeader.SEQUENCE_HEADER_SIZE);

    while (messageBuffer.readableBytes() > 0) {
        int bodySize = Math.min(messageBuffer.readableBytes(), maxBodySize);

        int paddingSize = encrypted
                ? plainTextBlockSize/*from  ww  w.  j  a va2  s.c  o  m*/
                        - (SequenceHeader.SEQUENCE_HEADER_SIZE + bodySize + signatureSize + paddingOverhead)
                                % plainTextBlockSize
                : 0;

        int plainTextContentSize = SequenceHeader.SEQUENCE_HEADER_SIZE + bodySize + signatureSize + paddingSize
                + paddingOverhead;

        assert (plainTextContentSize % plainTextBlockSize == 0);

        int chunkSize = SecureMessageHeader.SECURE_MESSAGE_HEADER_SIZE + securityHeaderSize
                + (plainTextContentSize / plainTextBlockSize) * cipherTextBlockSize;

        ByteBuf chunkBuffer = BufferUtil.buffer(chunkSize);

        /* Message Header */
        SecureMessageHeader messageHeader = new SecureMessageHeader(messageType,
                messageBuffer.readableBytes() > bodySize ? 'C' : 'F', chunkSize, channel.getChannelId());

        SecureMessageHeader.encode(messageHeader, chunkBuffer);

        /* Security Header */
        delegate.encodeSecurityHeader(channel, chunkBuffer);

        /* Sequence Header */
        SequenceHeader sequenceHeader = new SequenceHeader(sequenceNumber.getAndIncrement(), requestId);

        SequenceHeader.encode(sequenceHeader, chunkBuffer);

        /* Message Body */
        chunkBuffer.writeBytes(messageBuffer, bodySize);

        /* Padding and Signature */
        if (encrypted) {
            writePadding(cipherTextBlockSize, paddingSize, chunkBuffer);
        }

        if (delegate.isSigningEnabled(channel)) {
            ByteBuffer chunkNioBuffer = chunkBuffer.nioBuffer(0, chunkBuffer.writerIndex());

            byte[] signature = delegate.signChunk(channel, chunkNioBuffer);

            chunkBuffer.writeBytes(signature);
        }

        /* Encryption */
        if (encrypted) {
            chunkBuffer.readerIndex(SecureMessageHeader.SECURE_MESSAGE_HEADER_SIZE + securityHeaderSize);

            assert (chunkBuffer.readableBytes() % plainTextBlockSize == 0);

            try {
                int blockCount = chunkBuffer.readableBytes() / plainTextBlockSize;

                ByteBuffer chunkNioBuffer = chunkBuffer.nioBuffer(chunkBuffer.readerIndex(),
                        blockCount * cipherTextBlockSize);
                ByteBuf copyBuffer = chunkBuffer.copy();
                ByteBuffer plainTextNioBuffer = copyBuffer.nioBuffer();

                Cipher cipher = delegate.getAndInitializeCipher(channel);

                if (delegate instanceof AsymmetricDelegate) {
                    for (int blockNumber = 0; blockNumber < blockCount; blockNumber++) {
                        int position = blockNumber * plainTextBlockSize;
                        int limit = (blockNumber + 1) * plainTextBlockSize;
                        plainTextNioBuffer.position(position).limit(limit);

                        int bytesWritten = cipher.doFinal(plainTextNioBuffer, chunkNioBuffer);

                        assert (bytesWritten == cipherTextBlockSize);
                    }
                } else {
                    cipher.doFinal(plainTextNioBuffer, chunkNioBuffer);
                }

                copyBuffer.release();
            } catch (GeneralSecurityException e) {
                throw new UaException(StatusCodes.Bad_SecurityChecksFailed, e);
            }
        }

        chunkBuffer.readerIndex(0).writerIndex(chunkSize);

        chunks.add(chunkBuffer);
    }

    lastRequestId = requestId;

    return chunks;
}

From source file:com.flysoloing.learning.network.netty.http2.Http2ExampleUtil.java

License:Apache License

/**
 * Reads an InputStream into a byte array.
 * @param input the InputStream.// w ww. j  a  v  a 2s .  c  om
 * @return a byte array representation of the InputStream.
 * @throws IOException if an I/O exception of some sort happens while reading the InputStream.
 */
public static ByteBuf toByteBuf(InputStream input) throws IOException {
    ByteBuf buf = Unpooled.buffer();
    int n = 0;
    do {
        n = buf.writeBytes(input, BLOCK_SIZE);
    } while (n > 0);
    return buf;
}

From source file:com.heliosapm.streams.metrichub.tsdbplugin.MetricsAPIHttpPlugin.java

License:Apache License

/**
 * Unloads the UI content from a jar/*w  w w.  ja  v  a  2s.  c om*/
 * @param file The jar file
 */
protected void unloadFromJar(final File file) {
    log.info("Loading MetricsAPI UI Content from JAR: [{}]", file);
    final long startTime = System.currentTimeMillis();
    int filesLoaded = 0;
    int fileFailures = 0;
    int fileNewer = 0;
    long bytesLoaded = 0;

    JarFile jar = null;
    final ByteBuf contentBuffer = BufferManager.getInstance().directBuffer(30000);
    try {
        jar = new JarFile(file);
        final Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            final String name = entry.getName();
            if (name.startsWith(CONTENT_BASE + "/")) {
                final int contentSize = (int) entry.getSize();
                final long contentTime = entry.getTime();
                if (entry.isDirectory()) {
                    new File(metricUiContentDir, name).mkdirs();
                    continue;
                }
                File contentFile = new File(metricUiContentDir, name.replace(CONTENT_BASE + "/", ""));
                if (!contentFile.getParentFile().exists()) {
                    contentFile.getParentFile().mkdirs();
                }
                if (contentFile.exists()) {
                    if (contentFile.lastModified() >= contentTime) {
                        log.debug("File in directory was newer [{}]", name);
                        fileNewer++;
                        continue;
                    }
                    contentFile.delete();
                }
                log.debug("Writing content file [{}]", contentFile);
                contentFile.createNewFile();
                if (!contentFile.canWrite()) {
                    log.warn("Content file [{}] not writable", contentFile);
                    fileFailures++;
                    continue;
                }
                FileOutputStream fos = null;
                InputStream jis = null;
                try {
                    fos = new FileOutputStream(contentFile);
                    jis = jar.getInputStream(entry);
                    contentBuffer.writeBytes(jis, contentSize);
                    contentBuffer.readBytes(fos, contentSize);
                    fos.flush();
                    jis.close();
                    jis = null;
                    fos.close();
                    fos = null;
                    filesLoaded++;
                    bytesLoaded += contentSize;
                    log.debug("Wrote content file [{}] + with size [{}]", contentFile, contentSize);
                } finally {
                    if (jis != null)
                        try {
                            jis.close();
                        } catch (Exception ex) {
                        }
                    if (fos != null)
                        try {
                            fos.close();
                        } catch (Exception ex) {
                        }
                    contentBuffer.clear();
                }
            } // not content
        } // end of while loop
        final long elapsed = System.currentTimeMillis() - startTime;
        StringBuilder b = new StringBuilder(
                "\n\n\t===================================================\n\tMetricsAPI Content Directory:[")
                        .append(metricUiContentDir).append("]");
        b.append("\n\tTotal Files Written:").append(filesLoaded);
        b.append("\n\tTotal Bytes Written:").append(bytesLoaded);
        b.append("\n\tFile Write Failures:").append(fileFailures);
        b.append("\n\tExisting File Newer Than Content:").append(fileNewer);
        b.append("\n\tElapsed (ms):").append(elapsed);
        b.append("\n\t===================================================\n");
        log.info(b.toString());
    } catch (Exception ex) {
        log.error("Failed to export MetricsAPI content", ex);
    } finally {
        if (jar != null)
            try {
                jar.close();
            } catch (Exception x) {
                /* No Op */}
        try {
            contentBuffer.release();
        } catch (Exception x) {
            /* No Op */}
    }
}

From source file:com.heliosapm.tsdblite.handlers.http.HttpStaticFileServerHandler.java

License:Open Source License

/**
 * Loads the Static UI content files from the classpath JAR to the configured static root directory
 * @param the name of the content directory to write the content to
 *//*from   w w w  .  ja v  a  2 s .com*/
private void loadContent(String contentDirectory) {
    File gpDir = new File(contentDirectory);
    final long startTime = System.currentTimeMillis();
    int filesLoaded = 0;
    int fileFailures = 0;
    int fileNewer = 0;
    long bytesLoaded = 0;
    String codeSourcePath = HttpStaticFileServerHandler.class.getProtectionDomain().getCodeSource()
            .getLocation().getPath();
    File file = new File(codeSourcePath);
    if (codeSourcePath.endsWith(".jar") && file.exists() && file.canRead()) {
        JarFile jar = null;
        ByteBuf contentBuffer = Unpooled.directBuffer(300000);
        try {
            jar = new JarFile(file);
            final Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                final String name = entry.getName();
                if (name.startsWith(CONTENT_PREFIX + "/")) {
                    final int contentSize = (int) entry.getSize();
                    final long contentTime = entry.getTime();
                    if (entry.isDirectory()) {
                        new File(gpDir, name).mkdirs();
                        continue;
                    }
                    File contentFile = new File(gpDir, name.replace(CONTENT_PREFIX + "/", ""));
                    if (!contentFile.getParentFile().exists()) {
                        contentFile.getParentFile().mkdirs();
                    }
                    if (contentFile.exists()) {
                        if (contentFile.lastModified() >= contentTime) {
                            log.debug("File in directory was newer [{}]", name);
                            fileNewer++;
                            continue;
                        }
                        contentFile.delete();
                    }
                    log.debug("Writing content file [{}]", contentFile);
                    contentFile.createNewFile();
                    if (!contentFile.canWrite()) {
                        log.warn("Content file [{}] not writable", contentFile);
                        fileFailures++;
                        continue;
                    }
                    FileOutputStream fos = null;
                    InputStream jis = null;
                    try {
                        fos = new FileOutputStream(contentFile);
                        jis = jar.getInputStream(entry);
                        contentBuffer.writeBytes(jis, contentSize);
                        contentBuffer.readBytes(fos, contentSize);
                        fos.flush();
                        jis.close();
                        jis = null;
                        fos.close();
                        fos = null;
                        filesLoaded++;
                        bytesLoaded += contentSize;
                        log.debug("Wrote content file [{}] + with size [{}]", contentFile, contentSize);
                    } finally {
                        if (jis != null)
                            try {
                                jis.close();
                            } catch (Exception ex) {
                            }
                        if (fos != null)
                            try {
                                fos.close();
                            } catch (Exception ex) {
                            }
                    }
                } // not content
            } // end of while loop
            final long elapsed = System.currentTimeMillis() - startTime;
            StringBuilder b = new StringBuilder(
                    "\n\n\t===================================================\n\tStatic Root Directory:[")
                            .append(contentDirectory).append("]");
            b.append("\n\tTotal Files Written:").append(filesLoaded);
            b.append("\n\tTotal Bytes Written:").append(bytesLoaded);
            b.append("\n\tFile Write Failures:").append(fileFailures);
            b.append("\n\tExisting File Newer Than Content:").append(fileNewer);
            b.append("\n\tElapsed (ms):").append(elapsed);
            b.append("\n\t===================================================\n");
            log.info(b.toString());
        } catch (Exception ex) {
            log.error("Failed to export ui content", ex);
        } finally {
            if (jar != null)
                try {
                    jar.close();
                } catch (Exception x) {
                    /* No Op */}
        }
    } else { // end of was-not-a-jar
        log.warn(
                "\n\tThe TSDBLite classpath is not a jar file, so there is no content to unload.\n\tBuild the OpenTSDB jar and run 'java -jar <jar> --d <target>'.");
    }
}

From source file:com.larskroll.common.RAFileRef.java

License:Open Source License

void copyTo(io.netty.buffer.ByteBuf buffer, long start, int length) {
    try {/*from   w  w  w  .  jav  a  2s .  c  om*/
        int written = -1;
        int startx = buffer.writerIndex();
        /* Note: there's a weird bug here, causing the buffer to sometimes
        * read nothing, although there's enough to read.
        * As a workaround: Keep trying until we get the desired amount of data
        */
        while (written < length) {
            raf.seek(start);
            buffer.writerIndex(startx);
            FileChannel source = raf.getChannel();
            written = buffer.writeBytes(source, length);
            //            if (written != length) {
            //                System.err.println("Read from " + raf + " of size " + raf.length() 
            //                        + " starting at " + start + " leaving " + (raf.length()-start) 
            //                        + " to read " + length);
            //                throw new RuntimeException("Buffer didn't write required bytes!");
            //            }
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.liferay.sync.engine.lan.server.file.SyncChunkedFile.java

License:Open Source License

@Override
public ByteBuf readChunk(ByteBufAllocator byteBufAllocator) throws Exception {

    long offset = _offset;

    if (offset >= _endOffset) {
        return null;
    }//from   www .j  a  v a2  s. c o m

    int chunkSize = (int) Math.min((long) _chunkSize, _endOffset - offset);

    ByteBuf byteBuf = byteBufAllocator.buffer(chunkSize);

    boolean release = true;

    try {
        FileTime currentFileTime = Files.getLastModifiedTime(_path, LinkOption.NOFOLLOW_LINKS);

        long currentTime = currentFileTime.toMillis();

        if (currentTime != _modifiedTime) {
            throw new Exception("File modified during transfer: " + _path);
        }

        int bytesRead = 0;

        if (_closeAggressively || (_fileChannel == null)) {
            _fileChannel = FileChannel.open(_path);

            _fileChannel.position(_offset);
        }

        while (true) {
            int localBytesRead = byteBuf.writeBytes(_fileChannel, chunkSize - bytesRead);

            if (localBytesRead >= 0) {
                bytesRead += localBytesRead;

                if (bytesRead != chunkSize) {
                    continue;
                }
            }

            _offset += bytesRead;

            release = false;

            return byteBuf;
        }
    } finally {
        if (_closeAggressively && (_fileChannel != null)) {
            _fileChannel.close();
        }

        if (release) {
            byteBuf.release();
        }
    }
}

From source file:com.mastfrog.acteur.io.FileWriter.java

License:Open Source License

@Override
public void operationComplete(ChannelFuture f) throws Exception {
    if (!f.channel().isOpen()) {
        return;/*  w ww .  ja  va  2  s. co  m*/
    }
    ByteBuf buf = f.channel().alloc().buffer(bufferSize);
    int bytes = buf.writeBytes(stream, bufferSize);
    if (bytes == -1) {
        stream.close();
        f.channel().writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT).addListener(CLOSE);
        return;
    }
    f = f.channel().writeAndFlush(new DefaultHttpContent(buf));
    f.addListener(this);
}

From source file:com.uber.tchannel.codecs.CodecUtils.java

License:Open Source License

public static ByteBuf writeArgCopy(ByteBufAllocator allocator, ByteBuf payload, ByteBuf arg,
        int writableBytes) {
    if (writableBytes <= TFrame.FRAME_SIZE_LENGTH) {
        throw new UnsupportedOperationException(
                "writableBytes must be larger than " + TFrame.FRAME_SIZE_LENGTH);
    }//w  w w  .j a  va 2s.c o m

    int readableBytes = arg.readableBytes();
    int headerSize = TFrame.FRAME_SIZE_LENGTH;
    int chunkLength = Math.min(readableBytes + headerSize, writableBytes);

    // Write the size of the `arg`
    payload.writeShort(chunkLength - headerSize);
    if (readableBytes == 0) {
        return payload;
    } else {
        return payload.writeBytes(arg, chunkLength - headerSize);
    }
}

From source file:com.vethrfolnir.encdec.ReadDataFiles.java

License:Open Source License

public static long[] readFile(URL url) {

    ByteBuf buff = Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN);

    try (DataInputStream is = new DataInputStream(url.openStream())) {
        buff.writeBytes(is, is.available());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }/*from w  ww  . j  a  v a 2  s . c  o m*/

    int bits2 = buff.readUnsignedShort();

    System.out.println("First two bits: " + bits2 + " hex: 0x" + PrintData.fillHex(bits2, 2));

    long[] out_dat = new long[12];

    buff.readerIndex(6);
    int pointer = 0;
    for (int i = 0; i < 3; i++) {
        long[] buf = new long[4];

        for (int j = 0; j < 4; j++) {
            buf[j] = buff.readUnsignedInt();
        }

        out_dat[pointer++] = buf[0] ^ (xor_tab_datfile[0]);
        out_dat[pointer++] = buf[1] ^ (xor_tab_datfile[1] & 0xFFFFFFFFL);
        out_dat[pointer++] = buf[2] ^ (xor_tab_datfile[2] & 0xFFFFFFFFL);
        out_dat[pointer++] = buf[3] ^ (xor_tab_datfile[3]);
    }

    for (int i = 0; i < out_dat.length; i++) {
        System.out.print(" " + (out_dat[i]));
    }

    System.out.println();
    return null;
}