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();

Source Link

Document

Exposes this buffer's readable bytes as an NIO ByteBuffer .

Usage

From source file:com.linecorp.armeria.internal.grpc.GrpcMessageMarshaller.java

License:Apache License

private Message deserializeProto(ByteBuf buf, Message prototype) throws IOException {
    if (GrpcSerializationFormats.isProto(serializationFormat)) {
        final CodedInputStream stream;
        if (unsafeWrapDeserializedBuffer) {
            stream = UnsafeByteOperations.unsafeWrap(buf.nioBuffer()).newCodedInput();
            stream.enableAliasing(true);
        } else {/*from  w  w w. j  av  a2  s.  co m*/
            stream = CodedInputStream.newInstance(buf.nioBuffer());
        }
        try {
            final Message msg = prototype.getParserForType().parseFrom(stream);
            try {
                stream.checkLastTagWas(0);
            } catch (InvalidProtocolBufferException e) {
                e.setUnfinishedMessage(msg);
                throw e;
            }
            return msg;
        } catch (InvalidProtocolBufferException e) {
            throw Status.INTERNAL.withDescription("Invalid protobuf byte sequence").withCause(e)
                    .asRuntimeException();
        }
    }

    if (GrpcSerializationFormats.isJson(serializationFormat)) {
        final Message.Builder builder = prototype.newBuilderForType();
        try (ByteBufInputStream is = new ByteBufInputStream(buf, /* releaseOnClose */ false)) {
            jsonMarshaller.mergeValue(is, builder);
        }
        return builder.build();
    }
    throw new IllegalStateException("Unknown serialization format: " + serializationFormat);
}

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

License:Apache License

/**
 * Return the response body's part bytes received.
 *
 * @return the response body's part bytes received.
 *//*from ww w.jav  a 2  s  . co  m*/
@Override
public byte[] getBodyPartBytes() {
    byte[] bp = bytes.get();
    if (bp != null) {
        return bp;
    }

    ByteBuf b = getChannelBuffer();
    byte[] rb = b.nioBuffer().array();
    bytes.set(rb);
    return rb;
}

From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.PublishDecoder.java

License:Open Source License

@Override
void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception {
    LOG.info("decode invoked with buffer {}", in);
    in.resetReaderIndex();//from   w w w .  ja  v a  2  s  . co m
    int startPos = in.readerIndex();

    //Common decoding part
    PublishMessage message = new PublishMessage();
    if (!decodeCommonHeader(message, in)) {
        LOG.info("decode ask for more data after {}", in);
        in.resetReaderIndex();
        return;
    }

    if (Utils.isMQTT3_1_1(ctx)) {
        if (message.getQos() == AbstractMessage.QOSType.MOST_ONE && message.isDupFlag()) {
            //bad protocol, if QoS=0 => DUP = 0
            throw new CorruptedFrameException("Received a PUBLISH with QoS=0 & DUP = 1, MQTT 3.1.1 violation");
        }

        if (message.getQos() == AbstractMessage.QOSType.RESERVED) {
            throw new CorruptedFrameException(
                    "Received a PUBLISH with QoS flags setted 10 b11, MQTT 3.1.1 violation");
        }
    }

    int remainingLength = message.getRemainingLength();

    //Topic name
    String topic = Utils.decodeString(in);
    if (topic == null) {
        in.resetReaderIndex();
        return;
    }
    if (topic.contains("+") || topic.contains("#")) {
        throw new CorruptedFrameException(
                "Received a PUBLISH with topic containting wild card chars, topic: " + topic);
    }

    message.setTopicName(topic);

    if (message.getQos() == AbstractMessage.QOSType.LEAST_ONE
            || message.getQos() == AbstractMessage.QOSType.EXACTLY_ONCE) {
        message.setMessageID(in.readUnsignedShort());
    }
    int stopPos = in.readerIndex();

    //read the payload
    int payloadSize = remainingLength - (stopPos - startPos - 2)
            + (Utils.numBytesToEncode(remainingLength) - 1);
    if (in.readableBytes() < payloadSize) {
        in.resetReaderIndex();
        return;
    }
    //        byte[] b = new byte[payloadSize];
    ByteBuf bb = Unpooled.buffer(payloadSize);
    in.readBytes(bb);
    message.setPayload(bb.nioBuffer());

    out.add(message);
}

From source file:com.scurrilous.circe.checksum.Crc32cIntChecksum.java

License:Apache License

/**
 * Computes crc32c checksum: if it is able to load crc32c native library then it computes using that native library
 * which is faster as it computes using hardware machine instruction else it computes using crc32c algo.
 *
 * @param payload/*from  w w  w.  j  a  va 2 s .  c o  m*/
 * @return
 */
public static int computeChecksum(ByteBuf payload) {
    if (payload.hasMemoryAddress() && (CRC32C_HASH instanceof Sse42Crc32C)) {
        return CRC32C_HASH.calculate(payload.memoryAddress() + payload.readerIndex(), payload.readableBytes());
    } else if (payload.hasArray()) {
        return CRC32C_HASH.calculate(payload.array(), payload.arrayOffset() + payload.readerIndex(),
                payload.readableBytes());
    } else {
        return CRC32C_HASH.calculate(payload.nioBuffer());
    }
}

From source file:com.scurrilous.circe.checksum.Crc32cIntChecksum.java

License:Apache License

/**
 * Computes incremental checksum with input previousChecksum and input payload
 *
 * @param previousChecksum : previously computed checksum
 * @param payload//from  w  ww.  j av  a  2 s . c  om
 * @return
 */
public static int resumeChecksum(int previousChecksum, ByteBuf payload) {
    if (payload.hasMemoryAddress() && (CRC32C_HASH instanceof Sse42Crc32C)) {
        return CRC32C_HASH.resume(previousChecksum, payload.memoryAddress() + payload.readerIndex(),
                payload.readableBytes());
    } else if (payload.hasArray()) {
        return CRC32C_HASH.resume(previousChecksum, payload.array(),
                payload.arrayOffset() + payload.readerIndex(), payload.readableBytes());
    } else {
        return CRC32C_HASH.resume(previousChecksum, payload.nioBuffer());
    }
}

From source file:com.scurrilous.circe.checksum.Crc32cLongChecksum.java

License:Apache License

/**
 * Computes crc32c checksum: if it is able to load crc32c native library then it computes using that native library
 * which is faster as it computes using hardware machine instruction else it computes using crc32c algo.
 *
 * @param payload//from   w w w .  j  a v a  2s  . c o  m
 * @return
 */
public static long computeChecksum(ByteBuf payload) {
    int crc;
    if (payload.hasMemoryAddress() && (CRC32C_HASH instanceof Sse42Crc32C)) {
        crc = CRC32C_HASH.calculate(payload.memoryAddress() + payload.readerIndex(), payload.readableBytes());
    } else if (payload.hasArray()) {
        crc = CRC32C_HASH.calculate(payload.array(), payload.arrayOffset() + payload.readerIndex(),
                payload.readableBytes());
    } else {
        crc = CRC32C_HASH.calculate(payload.nioBuffer());
    }
    return crc & 0xffffffffL;
}

From source file:com.scurrilous.circe.checksum.Crc32cLongChecksum.java

License:Apache License

/**
 * Computes incremental checksum with input previousChecksum and input payload
 *
 * @param previousChecksum : previously computed checksum
 * @param payload//from   w  w w .  j  av  a  2s  .  c o m
 * @return
 */
public static long resumeChecksum(long previousChecksum, ByteBuf payload) {
    int crc = (int) previousChecksum;
    if (payload.hasMemoryAddress() && (CRC32C_HASH instanceof Sse42Crc32C)) {
        crc = CRC32C_HASH.resume(crc, payload.memoryAddress() + payload.readerIndex(), payload.readableBytes());
    } else if (payload.hasArray()) {
        crc = CRC32C_HASH.resume(crc, payload.array(), payload.arrayOffset() + payload.readerIndex(),
                payload.readableBytes());
    } else {
        crc = CRC32C_HASH.resume(crc, payload.nioBuffer());
    }
    return crc & 0xffffffffL;
}

From source file:com.tesora.dve.db.mysql.portal.MSPCommandHandler.java

License:Open Source License

static boolean isLoadDataStmt(MSPComQueryRequestMessage message) {
    ByteBuf rawStatement = message.getQueryNative();//returns a slice()
    try {/*from   w  w w  . j  a va  2  s  .  c  om*/
        //previous code made two copies of the query data before we even get to the parser, direct buf ==> byte[] ==> String
        //the parser requires a byte[] array, so (for now) we *must* do direct buf ==> byte[]
        //TODO: this code does direct buf ==> CharSequence, but a custom CharSequence could peek into the byte[], avoiding most of one full copy. -sgossard
        CharsetDecoder decoder = PECharsetUtils.latin1.newDecoder();
        CharBuffer charBuf = decoder.decode(rawStatement.nioBuffer());
        return MSPComQueryRequest.IS_LOAD_DATA_STATEMENT.matcher(charBuf).matches();
    } catch (CharacterCodingException e) {
        throw new IllegalArgumentException("query statement does not appear to be latin1");
    }
}

From source file:com.tongbanjie.tarzan.rpc.protocol.NettyDecoder.java

License:Apache License

@Override
public Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    ByteBuf frame = null;
    try {//from  www  .j  a v  a 2  s  .c  o  m
        frame = (ByteBuf) super.decode(ctx, in);
        if (null == frame) {
            return null;
        }
        return RpcCommand.decode(frame.nioBuffer());
    } catch (Exception e) {
        LOGGER.error("decode exception, " + RpcHelper.parseChannelRemoteAddr(ctx.channel()), e);
        RpcHelper.closeChannel(ctx.channel());
    } finally {
        if (null != frame) {
            frame.release();
        }
    }

    return null;
}

From source file:com.vethrfolnir.game.network.mu.crypt.MuDecoder.java

License:Open Source License

private static int DecodeBlock(ByteBuf buff, ByteBuf outBuff, int offset, int size) {
    // decripted size
    int index = 0;

    if ((size % 11) != 0) {
        log.warn("Cannot decrypt packet, it's already decrypted!: Size " + size + " = " + ((size % 11)));
        log.warn(PrintData.printData(buff.nioBuffer()));
        return -1;
    }//from ww w .  j a  va 2  s.  com

    ByteBuf encrypted = alloc.heapBuffer(11, 11).order(ByteOrder.LITTLE_ENDIAN);
    short[] uByteArray = new short[encrypted.capacity()];

    ByteBuf decrypted = alloc.heapBuffer(8, 8).order(ByteOrder.LITTLE_ENDIAN);
    ByteBuf converter = alloc.heapBuffer(4).order(ByteOrder.LITTLE_ENDIAN);

    for (int i = 0; i < size; i += 11) {
        buff.readBytes(encrypted);

        //System.out.println("ENC: "+PrintData.printData(encrypted.nioBuffer()));
        int Result = BlockDecode(decrypted, getAsUByteArray(encrypted, uByteArray), converter,
                MuKeyFactory.getClientToServerPacketDecKeys());
        if (Result != -1) {
            //Buffer.BlockCopy(Decrypted, 0, m_DecryptResult, (OffSet - 1) + DecSize, Result);

            outBuff.writerIndex((offset - 1) + index);
            outBuff.writeBytes(decrypted);

            //outBuff.writeBytes(decrypted);

            decrypted.clear();
            encrypted.clear();
            converter.clear();
            //System.arraycopy(Decrypted, 0, m_DecryptResult, (OffSet - 1) + DecSize, Result);

            index += Result;
        }
    }

    return index;
}