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 ByteBuf writeBytes(ByteBuffer src);

Source Link

Document

Transfers the specified source buffer's data to this buffer starting at the current writerIndex until the source buffer's position reaches its limit, and increases the writerIndex by the number of the transferred bytes.

Usage

From source file:com.dempe.chat.common.netty.PublishEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, PublishMessage message, ByteBuf out) {
    if (message.getQos() == AbstractMessage.QOSType.RESERVED) {
        throw new IllegalArgumentException("Found a message with RESERVED Qos");
    }// www . j  a va2 s .  com
    if (message.getTopicName() == null || message.getTopicName().isEmpty()) {
        throw new IllegalArgumentException("Found a message with empty or null topic name");
    }

    ByteBuf variableHeaderBuff = ctx.alloc().buffer(2);
    ByteBuf buff = null;
    try {
        variableHeaderBuff.writeBytes(Utils.encodeString(message.getTopicName()));
        if (message.getQos() == AbstractMessage.QOSType.LEAST_ONE
                || message.getQos() == AbstractMessage.QOSType.EXACTLY_ONCE) {
            if (message.getMessageID() == null) {
                throw new IllegalArgumentException("Found a message with QOS 1 or 2 and not MessageID setted");
            }
            variableHeaderBuff.writeShort(message.getMessageID());
        }
        variableHeaderBuff.writeBytes(message.getPayload());
        int variableHeaderSize = variableHeaderBuff.readableBytes();

        byte flags = Utils.encodeFlags(message);

        buff = ctx.alloc().buffer(2 + variableHeaderSize);
        buff.writeByte(AbstractMessage.PUBLISH << 4 | flags);
        buff.writeBytes(Utils.encodeRemainingLength(variableHeaderSize));
        buff.writeBytes(variableHeaderBuff);
        out.writeBytes(buff);
    } finally {
        variableHeaderBuff.release();
        if (buff != null) {
            buff.release();
        }
    }
}

From source file:com.dianping.cat.hadoop.hdfs.bucket.AbstractHdfsMessageBucket.java

License:Open Source License

@Override
public MessageTree findById(String messageId) throws IOException {
    int index = MessageId.parse(messageId).getIndex();

    try {//from w w  w  .j a v  a2s  .  c  o m
        byte[] data = m_reader.readMessage(index);

        if (data != null) {
            ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(data.length);

            buf.writeBytes(data);

            MessageTree tree = CodecHandler.decode(buf);

            m_lastAccessTime = System.currentTimeMillis();
            return tree;
        } else {
            return null;
        }
    } catch (EOFException e) {
        return null;
    } finally {
        CodecHandler.reset();
    }
}

From source file:com.dianping.cat.message.io.ClientMessageEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, ClientMessage msg, ByteBuf out) {
    out.writeInt(ClientMessage.PROTOCOL_ID);
    out.writeInt(msg.getVersion());/*from   w  ww .j  a va 2  s .c  o  m*/
    out.writeInt(msg.getData().length);
    out.writeBytes(msg.getData());
}

From source file:com.digisky.outerproxy.testclient.HttpSnoopClient.java

License:Apache License

public static void testWithEncode(Channel ch, String uri, String sjson) {
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
    request.headers().set(HttpHeaders.Names.HOST, "127.0.0.1");
    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

    request.setMethod(HttpMethod.POST);//from w  ww.  j  av a 2  s.  c o  m
    request.setUri("/" + uri);
    HttpPostRequestEncoder bodyRequestEncoder = null;
    try {
        bodyRequestEncoder = new HttpPostRequestEncoder(request, false);
    } catch (ErrorDataEncoderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } // false => not multipart
      //***********************************************************************
    ByteBuf b = Unpooled.buffer();
    b.writeBytes("{}".getBytes());
    try {
        bodyRequestEncoder.addBodyAttribute("val", sjson);
    } catch (ErrorDataEncoderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //***********************************************************************
    try {
        request = bodyRequestEncoder.finalizeRequest();
    } catch (ErrorDataEncoderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ch.writeAndFlush(request);
    try {
        ch.closeFuture().sync();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

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

License:Apache License

private ByteBuf encodeReadCoils(ReadCoilsResponse response, ByteBuf buffer) {
    buffer.writeByte(response.getFunctionCode().getCode());
    buffer.writeByte(response.getCoilStatus().readableBytes());
    buffer.writeBytes(response.getCoilStatus());

    return buffer;
}

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

License:Apache License

private ByteBuf encodeReadDiscreteInputs(ReadDiscreteInputsResponse response, ByteBuf buffer) {
    buffer.writeByte(response.getFunctionCode().getCode());
    buffer.writeByte(response.getInputStatus().readableBytes());
    buffer.writeBytes(response.getInputStatus());

    return buffer;
}

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

License:Apache License

private ByteBuf encodeReadHoldingRegisters(ReadHoldingRegistersResponse response, ByteBuf buffer) {
    buffer.writeByte(response.getFunctionCode().getCode());
    buffer.writeByte(response.getRegisters().readableBytes());
    buffer.writeBytes(response.getRegisters());

    return buffer;
}

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

License:Apache License

private ByteBuf encodeReadInputRegisters(ReadInputRegistersResponse response, ByteBuf buffer) {
    buffer.writeByte(response.getFunctionCode().getCode());
    buffer.writeByte(response.getRegisters().readableBytes());
    buffer.writeBytes(response.getRegisters());

    return buffer;
}

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 ww w  .j a va2s.  co  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 {/* w w w .ja v  a  2s  .c om*/
        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();
}