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.antsdb.saltedfish.server.mysql.ReplicationPacketDecoder.java

License:Open Source License

@SuppressWarnings("unused")
private ReplicationPacket readPacket(ByteBuf in, int size) {
    // packet sequence number for multiple packets

    // byte packetSequence = in.readByte();
    byte seqId = in.readByte();

    // handshake//w ww.ja va 2  s .c  o  m

    ReplicationPacket packet = null;

    // using state to decide how to handle connecting messages.
    if (state == StateIndicator.INITIAL_STATE) {
        packet = new StateIndicator(StateIndicator.INITIAL_STATE);
        packet.packetLength = size;
        packet.packetId = seqId;
        packet.read(this.handler, in);
        state = StateIndicator.RESPONSED_STATE;
    } else if (state == StateIndicator.RESPONSED_STATE) {
        byte header = in.readByte();

        if (header == 0) {
            packet = new StateIndicator(StateIndicator.HANDSHAKEN_STATE);
            state = StateIndicator.HANDSHAKEN_STATE;
        } else {
            packet = new StateIndicator(StateIndicator.HANDSHAKE_FAIL_STATE);
            state = StateIndicator.HANDSHAKE_FAIL_STATE;
        }
        char[] bytes = new char[size];
        for (int i = 0; i < size; i++) {
            int ch = in.getByte(i);
            bytes[i] = (char) ch;
        }
        packet.packetId = seqId;
        packet.packetLength = size;
        packet.read(this.handler, in);
    } else if (state == StateIndicator.HANDSHAKEN_STATE) {
        // expecting response for registered slave
        byte header = in.readByte();

        if (header == 0) {
            packet = new StateIndicator(StateIndicator.REGISTERED_STATE);
            state = StateIndicator.REGISTERED_STATE;
        } else {
            packet = new StateIndicator(StateIndicator.REGISTER_FAIL_STATE);
            state = StateIndicator.REGISTER_FAIL_STATE;
        }
        packet.packetId = seqId;
        packet.packetLength = size;
        packet.read(this.handler, in);
    } else {

        // binlog stream started with 00 ok-byte
        byte okByte = in.readByte();

        if (okByte == 0) {
            // read event header

            // timestamp 4 bytes
            int timeStamp = in.readInt();
            // event type
            byte eventType = in.readByte();
            // server id, 4 bytes
            int serverId = (int) BufferUtils.readLong(in);
            // event length, 4 bytes
            long eventLength = BufferUtils.readLong(in);
            // next position, 4 bytes
            long nextPosition = BufferUtils.readLong(in);
            // flags
            int flags = in.readShort();

            // events

            switch (eventType) {
            case ReplicationPacket.ROTATE_EVENT:
                packet = new RotatePacket(eventType, eventLength, nextPosition);
                break;
            case ReplicationPacket.TABLE_MAP_EVENT:
                packet = new TableMapPacket(eventType, eventLength, nextPosition);
                break;
            case ReplicationPacket.WRITE_ROWS_EVENT:
            case ReplicationPacket.UPDATE_ROWS_EVENT:
            case ReplicationPacket.DELETE_ROWS_EVENT:
                packet = new RowsEventV2Packet(eventType, eventLength, nextPosition);
                break;
            case ReplicationPacket.STOP_EVENT:
                packet = new StopPacket(eventType, eventLength, nextPosition);
                break;
            case ReplicationPacket.XID_EVENT:
                packet = new XIDPacket(eventType, eventLength, nextPosition);
                break;
            case ReplicationPacket.QUERY_EVENT:
            case ReplicationPacket.FORMAT_DESCRIPTION_EVENT:
            case ReplicationPacket.START_EVENT_V3:
                // use GenericPacket to ignore unsupported events for now
                packet = new GenericPacket(eventType, eventLength, nextPosition);
                break;
            default:
                _log.error("unknown event: " + eventType);
                throw new CodingError("unknown event: " + eventType);
            }

            if (packet != null) {
                packet.packetId = seqId;
                packet.packetLength = size;
                packet.read(this.handler, in);
            }
        } else {
            ByteBuf pkt = (ByteBuf) in;
            ByteBuffer bbuf = pkt.nioBuffer();

            int i = bbuf.remaining();

            byte[] bytes = new byte[i];
            pkt.readBytes(bytes);
            String dump = '\n' + UberUtil.hexDump(bytes);
            _log.error("unknown packet: " + dump);
            throw new CodingError("unknown packet");
        }
    }
    return packet;
}

From source file:com.antsdb.saltedfish.server.mysql.util.BufferUtils.java

License:Open Source License

/**
 * decoding string from mysql is not easy. literals is encoded in utf8. chances are some lierals are encoded in 
 * binary. we need this pretty logic to convert mysql binary to string
 * @param buf/*from   www. j av  a 2 s.c o m*/
 * @return
 */
public static CharBuffer readStringCrazy(Decoder decoder, ByteBuf buf) {
    CharBuffer cbuf = MysqlString.decode(decoder, buf.nioBuffer());
    cbuf.flip();
    return cbuf;
}

From source file:com.dempe.chat.common.mqtt.codec.PublishDecoder.java

License:Open Source License

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

    //Common decoding part
    PublishMessage message = new PublishMessage();
    if (!decodeCommonHeader(message, in)) {
        LOG.debug("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;
    }
    //[MQTT-3.3.2-2] The Topic Name in the PUBLISH Packet MUST NOT contain wildcard characters.
    if (topic.contains("+") || topic.contains("#")) {
        throw new CorruptedFrameException(
                "Received a PUBLISH with topic containing wild card chars, topic: " + topic);
    }
    //check topic is at least one char [MQTT-4.7.3-1]
    if (topic.length() == 0) {
        throw new CorruptedFrameException("Received a PUBLISH with topic without any character");
    }

    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;
    }
    ByteBuf bb = Unpooled.buffer(payloadSize);
    in.readBytes(bb);
    message.setPayload(bb.nioBuffer());

    out.add(message);
}

From source file:com.digitalpetri.opcua.sdk.client.api.identity.UsernameProvider.java

License:Open Source License

@Override
public Tuple2<UserIdentityToken, SignatureData> getIdentityToken(EndpointDescription endpoint,
        ByteString serverNonce) throws Exception {

    UserTokenPolicy tokenPolicy = Arrays.stream(endpoint.getUserIdentityTokens())
            .filter(t -> t.getTokenType() == UserTokenType.UserName).findFirst()
            .orElseThrow(() -> new Exception("no username token policy found"));

    String policyId = tokenPolicy.getPolicyId();

    SecurityPolicy securityPolicy = SecurityPolicy.None;

    String securityPolicyUri = tokenPolicy.getSecurityPolicyUri();
    try {/*from   w  w w  .  j a  v a  2 s.c  o  m*/
        if (securityPolicyUri != null && !securityPolicyUri.isEmpty()) {
            securityPolicy = SecurityPolicy.fromUri(securityPolicyUri);
        } else {
            securityPolicyUri = endpoint.getSecurityPolicyUri();
            securityPolicy = SecurityPolicy.fromUri(securityPolicyUri);
        }
    } catch (Throwable t) {
        logger.warn("Error parsing SecurityPolicy for uri={}, falling back to no security.", securityPolicyUri);
    }

    byte[] passwordBytes = password.getBytes("UTF-8");
    byte[] nonceBytes = Optional.ofNullable(serverNonce.bytes()).orElse(new byte[0]);

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

    if (securityPolicy == SecurityPolicy.None) {
        buffer.writeBytes(passwordBytes);
    } else {
        buffer.writeInt(passwordBytes.length + nonceBytes.length);
        buffer.writeBytes(passwordBytes);
        buffer.writeBytes(nonceBytes);

        ByteString bs = endpoint.getServerCertificate();
        X509Certificate certificate = CertificateUtil.decodeCertificate(bs.bytes());

        int plainTextBlockSize = getPlainTextBlockSize(certificate, securityPolicy);
        int blockCount = (buffer.readableBytes() + plainTextBlockSize - 1) / plainTextBlockSize;
        Cipher cipher = getAndInitializeCipher(certificate, securityPolicy);

        ByteBuffer plainTextNioBuffer = buffer.nioBuffer();
        ByteBuffer cipherTextNioBuffer = Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN).nioBuffer();

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

            cipher.doFinal(plainTextNioBuffer, cipherTextNioBuffer);
        }

        cipherTextNioBuffer.flip();
        buffer = Unpooled.wrappedBuffer(cipherTextNioBuffer);
    }

    byte[] bs = new byte[buffer.readableBytes()];
    buffer.readBytes(bs);

    UserNameIdentityToken token = new UserNameIdentityToken(policyId, username, ByteString.of(bs),
            securityPolicy.getAsymmetricEncryptionAlgorithm().getUri());

    return new Tuple2<>(token, new SignatureData());
}

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

License:Apache License

private void decryptChunk(Delegate delegate, SecureChannel channel, ByteBuf chunkBuffer) throws UaException {
    int cipherTextBlockSize = delegate.getCipherTextBlockSize(channel);
    int blockCount = chunkBuffer.readableBytes() / cipherTextBlockSize;

    int plainTextBufferSize = cipherTextBlockSize * blockCount;

    ByteBuf plainTextBuffer = BufferUtil.buffer(plainTextBufferSize);

    ByteBuffer plainTextNioBuffer = plainTextBuffer.writerIndex(plainTextBufferSize).nioBuffer();

    ByteBuffer chunkNioBuffer = chunkBuffer.nioBuffer();

    try {/*from w w w .  j a v  a2  s  . co  m*/
        Cipher cipher = delegate.getCipher(channel);

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

        if (delegate instanceof AsymmetricDelegate) {
            for (int blockNumber = 0; blockNumber < blockCount; blockNumber++) {
                chunkNioBuffer.limit(chunkNioBuffer.position() + cipherTextBlockSize);

                cipher.doFinal(chunkNioBuffer, plainTextNioBuffer);
            }
        } else {
            cipher.doFinal(chunkNioBuffer, plainTextNioBuffer);
        }
    } catch (GeneralSecurityException e) {
        throw new UaException(StatusCodes.Bad_SecurityChecksFailed, e);
    }

    /* Write plainTextBuffer back into the chunk buffer we decrypted from. */
    plainTextNioBuffer.flip(); // limit = pos, pos = 0

    chunkBuffer.writerIndex(chunkBuffer.readerIndex());
    chunkBuffer.writeBytes(plainTextNioBuffer);

    plainTextBuffer.release();
}

From source file:com.diwayou.hybrid.remoting.netty.NettyDecoder.java

License:Apache License

@Override
public Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    ByteBuf frame = null;
    try {//from   ww w  . j  a  v  a 2s . c o  m
        frame = (ByteBuf) super.decode(ctx, in);
        if (null == frame) {
            return null;
        }

        ByteBuffer byteBuffer = frame.nioBuffer();

        return RemotingCommand.decode(byteBuffer);
    } catch (Exception e) {
        log.error("decode exception, " + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), e);
        // ? pipelineclose???
        RemotingUtil.closeChannel(ctx.channel());
    } finally {
        if (null != frame) {
            frame.release();
        }
    }

    return null;
}

From source file:com.easy.remoting.netty.handler.EasyDecoder.java

License:Apache License

@Override
public Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    ByteBuf frame = null;
    try {//  ww  w .jav a  2  s. co m
        frame = (ByteBuf) super.decode(ctx, in);
        if (null == frame) {
            return null;
        }

        ByteBuffer byteBuffer = frame.nioBuffer();

        return Cmd.decode(byteBuffer);
    } catch (Exception e) {
        log.error("decode exception:{}", e);

        ctx.channel().close().addListener(ChannelFutureListener.CLOSE);

    } finally {
        if (null != frame) {
            frame.release();
        }
    }

    return null;
}

From source file:com.github.pgasync.impl.netty.ByteBufMessageDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (in.readableBytes() == 0) {
        return;/*from   w  ww. ja  v  a2  s .c  o m*/
    }

    byte id = in.readByte();
    int length = in.readInt();

    Decoder<?> decoder = DECODERS.get(id);
    try {
        if (decoder != null) {
            ByteBuffer buffer = in.nioBuffer();
            out.add(decoder.read(buffer));
            in.skipBytes(buffer.position());
        } else {
            in.skipBytes(length - 4);
        }
    } catch (Throwable t) {
        // broad catch as otherwise the exception is silently dropped
        ctx.fireExceptionCaught(t);
    }
}

From source file:com.github.sparkfy.network.protocol.MessageWithHeader.java

License:Apache License

private int copyByteBuf(ByteBuf buf, WritableByteChannel target) throws IOException {
    int written = target.write(buf.nioBuffer());
    buf.skipBytes(written);//from w w  w . jav a  2 s . com
    return written;
}

From source file:com.github.sylvek.wsmqttfwd.decoder.PublishDecoder.java

License:Open Source License

@Override
public PublishMessage decode(AttributeMap ctx, ByteBuf in) throws Exception {
    LOG.debug("decode invoked with buffer {}", in);
    in.resetReaderIndex();/*from   w  w w  .  j a  v a2s  .  co m*/
    int startPos = in.readerIndex();

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

    int remainingLength = message.getRemainingLength();

    //Topic name
    String topic = Utils.decodeString(in);
    if (topic == null) {
        in.resetReaderIndex();
        return null;
    }
    //[MQTT-3.3.2-2] The Topic Name in the PUBLISH Packet MUST NOT contain wildcard characters.
    if (topic.contains("+") || topic.contains("#")) {
        throw new CorruptedFrameException(
                "Received a PUBLISH with topic containing wild card chars, topic: " + topic);
    }
    //check topic is at least one char [MQTT-4.7.3-1]
    if (topic.length() == 0) {
        throw new CorruptedFrameException("Received a PUBLISH with topic without any character");
    }

    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 null;
    }
    ByteBuf bb = Unpooled.buffer(payloadSize);
    in.readBytes(bb);
    message.setPayload(bb.nioBuffer());

    return message;
}