Example usage for io.netty.buffer ByteBuf nioBuffer

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

Introduction

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

Prototype

public abstract ByteBuffer nioBuffer(int index, int length);

Source Link

Document

Exposes this buffer's sub-region as an NIO ByteBuffer .

Usage

From source file:com.yahoo.pulsar.common.compression.CompressionCodecLZ4.java

License:Apache License

@Override
public ByteBuf encode(ByteBuf source) {
    int uncompressedLength = source.readableBytes();
    int maxLength = compressor.maxCompressedLength(uncompressedLength);

    ByteBuffer sourceNio = source.nioBuffer(source.readerIndex(), source.readableBytes());

    ByteBuf target = PooledByteBufAllocator.DEFAULT.buffer(maxLength, maxLength);
    ByteBuffer targetNio = target.nioBuffer(0, maxLength);

    int compressedLength = compressor.compress(sourceNio, 0, uncompressedLength, targetNio, 0, maxLength);
    target.writerIndex(compressedLength);
    return target;
}

From source file:com.yahoo.pulsar.common.compression.CompressionCodecLZ4.java

License:Apache License

@Override
public ByteBuf decode(ByteBuf encoded, int uncompressedLength) throws IOException {
    ByteBuf uncompressed = PooledByteBufAllocator.DEFAULT.buffer(uncompressedLength, uncompressedLength);
    ByteBuffer uncompressedNio = uncompressed.nioBuffer(0, uncompressedLength);

    ByteBuffer encodedNio = encoded.nioBuffer(encoded.readerIndex(), encoded.readableBytes());
    decompressor.decompress(encodedNio, encodedNio.position(), uncompressedNio, uncompressedNio.position(),
            uncompressedNio.remaining());

    uncompressed.writerIndex(uncompressedLength);
    return uncompressed;
}

From source file:com.yahoo.pulsar.common.util.XXHashChecksum.java

License:Apache License

public static long computeChecksum(ByteBuf payload) {
    if (payload.hasArray()) {
        return checksum.hash(payload.array(), payload.arrayOffset() + payload.readerIndex(),
                payload.readableBytes(), 0L);
    } else {//  w w  w. j  a va 2  s  .com
        ByteBuffer payloadNio = payload.nioBuffer(payload.readerIndex(), payload.readableBytes());
        return checksum.hash(payloadNio, 0, payload.readableBytes(), 0L);
    }
}

From source file:de.unipassau.isl.evs.ssh.core.network.handler.Decrypter.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> decoded) throws Exception {
    try {//w w  w . j  a  v a2s.  co m
        final int encryptedLength = in.readInt();
        final int decryptedLength = decryptCipher.getOutputSize(encryptedLength);

        final ByteBuf out = ctx.alloc().buffer(decryptedLength);
        //Log.v(TAG, "Decrypting " + encryptedLength + "b data to " + decryptedLength + "b of decrypted data");
        decryptCipher.doFinal(in.nioBuffer(in.readerIndex(), encryptedLength),
                out.nioBuffer(out.writerIndex(), decryptedLength));
        out.writerIndex(out.writerIndex() + decryptedLength);
        in.readerIndex(in.readerIndex() + encryptedLength);

        decoded.add(out);
    } catch (GeneralSecurityException | RuntimeException e) {
        ctx.close();
        throw e;
    }
}

From source file:de.unipassau.isl.evs.ssh.core.network.handler.Encrypter.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf in, ByteBuf out) throws Exception {
    final int decryptedLength = in.readableBytes();
    final int encryptedLength = encryptCipher.getOutputSize(decryptedLength);
    //Log.v(TAG, "Encrypting " + decryptedLength + "b data to " + encryptedLength + "b of encrypted data");
    out.writeInt(encryptedLength);/*from w  w  w .  ja  v  a 2  s  . c om*/

    out.ensureWritable(encryptedLength);
    final ByteBuffer inNio = in.nioBuffer(in.readerIndex(), decryptedLength);
    final ByteBuffer outNio = out.nioBuffer(out.writerIndex(), encryptedLength);
    encryptCipher.doFinal(inNio, outNio);
    if (inNio.hasRemaining()) {
        Log.wtf(TAG,
                "Crypto library did not read all bytes for encryption (" + inNio.remaining() + " remaining)");
    }
    if (outNio.hasRemaining()) {
        Log.wtf(TAG,
                "Crypto library did not write all bytes for encryption (" + outNio.remaining() + " remaining)");
    }
    out.writerIndex(out.writerIndex() + encryptedLength);
    in.readerIndex(in.readerIndex() + decryptedLength);
}

From source file:divconq.net.ssl.SslHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws SSLException {

    final int startOffset = in.readerIndex();
    final int endOffset = in.writerIndex();
    int offset = startOffset;
    int totalLength = 0;

    // If we calculated the length of the current SSL record before, use that information.
    if (packetLength > 0) {
        if (endOffset - startOffset < packetLength) {
            return;
        } else {//from  ww  w.j av  a2  s.com
            offset += packetLength;
            totalLength = packetLength;
            packetLength = 0;
        }
    }

    boolean nonSslRecord = false;

    while (totalLength < OpenSslEngine.MAX_ENCRYPTED_PACKET_LENGTH) {
        final int readableBytes = endOffset - offset;
        if (readableBytes < 5) {
            break;
        }

        final int packetLength = getEncryptedPacketLength(in, offset);
        if (packetLength == -1) {
            nonSslRecord = true;
            break;
        }

        assert packetLength > 0;

        if (packetLength > readableBytes) {
            // wait until the whole packet can be read
            this.packetLength = packetLength;
            break;
        }

        int newTotalLength = totalLength + packetLength;
        if (newTotalLength > OpenSslEngine.MAX_ENCRYPTED_PACKET_LENGTH) {
            // Don't read too much.
            break;
        }

        // We have a whole packet.
        // Increment the offset to handle the next packet.
        offset += packetLength;
        totalLength = newTotalLength;
    }

    if (totalLength > 0) {
        // The buffer contains one or more full SSL records.
        // Slice out the whole packet so unwrap will only be called with complete packets.
        // Also directly reset the packetLength. This is needed as unwrap(..) may trigger
        // decode(...) again via:
        // 1) unwrap(..) is called
        // 2) wrap(...) is called from within unwrap(...)
        // 3) wrap(...) calls unwrapLater(...)
        // 4) unwrapLater(...) calls decode(...)
        //
        // See https://github.com/netty/netty/issues/1534

        in.skipBytes(totalLength);
        final ByteBuffer inNetBuf = in.nioBuffer(startOffset, totalLength);
        unwrap(ctx, inNetBuf, totalLength);
        assert !inNetBuf.hasRemaining() || engine.isInboundDone();
    }

    if (nonSslRecord) {
        // Not an SSL/TLS packet
        NotSslRecordException e = new NotSslRecordException(
                "not an SSL/TLS record: " + ByteBufUtil.hexDump(in));
        in.skipBytes(in.readableBytes());
        ctx.fireExceptionCaught(e);
        setHandshakeFailure(e);
    }
}

From source file:divconq.net.ssl.SslHandler.java

License:Apache License

private static SSLEngineResult unwrap(SSLEngine engine, ByteBuffer in, ByteBuf out) throws SSLException {
    int overflows = 0;
    for (;;) {/*www  .j a va 2  s.co  m*/
        ByteBuffer out0 = out.nioBuffer(out.writerIndex(), out.writableBytes());
        SSLEngineResult result = engine.unwrap(in, out0);
        out.writerIndex(out.writerIndex() + result.bytesProduced());
        switch (result.getStatus()) {
        case BUFFER_OVERFLOW:
            int max = engine.getSession().getApplicationBufferSize();
            switch (overflows++) {
            case 0:
                out.ensureWritable(Math.min(max, in.remaining()));
                break;
            default:
                out.ensureWritable(max);
            }
            break;
        default:
            return result;
        }
    }
}

From source file:io.grpc.alts.internal.AltsChannelCrypter.java

License:Apache License

@Override
public void decrypt(ByteBuf out, ByteBuf ciphertextAndTag) throws GeneralSecurityException {
    int bytesRead = ciphertextAndTag.readableBytes();
    checkArgument(bytesRead == out.writableBytes());

    checkArgument(out.nioBufferCount() == 1);
    ByteBuffer outBuffer = out.internalNioBuffer(out.writerIndex(), out.writableBytes());

    checkArgument(ciphertextAndTag.nioBufferCount() == 1);
    ByteBuffer ciphertextAndTagBuffer = ciphertextAndTag.nioBuffer(ciphertextAndTag.readerIndex(), bytesRead);

    byte[] counter = incrementInCounter();
    int outPosition = outBuffer.position();
    aeadCrypter.decrypt(outBuffer, ciphertextAndTagBuffer, counter);
    int bytesWritten = outBuffer.position() - outPosition;
    out.writerIndex(out.writerIndex() + bytesWritten);
    ciphertextAndTag.readerIndex(out.readerIndex() + bytesRead);
    verify(out.writableBytes() == TAG_LENGTH);
}

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

License:Apache License

@Override
public ByteBuffer[] nioBuffers(int index, int length) {
    checkIndex(index, length);// w  w  w .j  a  v a 2 s .c  om
    if (length == 0) {
        return EmptyArrays.EMPTY_BYTE_BUFFERS;
    }

    List<ByteBuffer> buffers = new ArrayList<ByteBuffer>(components.size());
    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));
        switch (s.nioBufferCount()) {
        case 0:
            throw new UnsupportedOperationException();
        case 1:
            buffers.add(s.nioBuffer(index - adjustment, localLength));
            break;
        default:
            Collections.addAll(buffers, s.nioBuffers(index - adjustment, localLength));
        }

        index += localLength;
        length -= localLength;
        i++;
    }

    return buffers.toArray(new ByteBuffer[buffers.size()]);
}

From source file:org.apache.cassandra.transport.CBUtil.java

License:Apache License

private static String readString(ByteBuf cb, int length) {
    if (length == 0)
        return "";

    ByteBuffer buffer = cb.nioBuffer(cb.readerIndex(), length);
    try {/*from   w w w  .  ja va2 s.  c o  m*/
        String str = decodeString(buffer);
        cb.readerIndex(cb.readerIndex() + length);
        return str;
    } catch (IllegalStateException | CharacterCodingException e) {
        throw new ProtocolException(
                "Cannot decode string as UTF8: '" + ByteBufferUtil.bytesToHex(buffer) + "'; " + e);
    }
}