Example usage for io.netty.buffer ByteBuf writeInt

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

Introduction

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

Prototype

public abstract ByteBuf writeInt(int value);

Source Link

Document

Sets the specified 32-bit integer at the current writerIndex and increases the writerIndex by 4 in this buffer.

Usage

From source file:com.datastax.driver.core.LZ4Compressor.java

License:Apache License

private ByteBuf compressDirect(ByteBuf input) throws IOException {
    int maxCompressedLength = compressor.maxCompressedLength(input.readableBytes());
    // If the input is direct we will allocate a direct output buffer as well as this will allow us to use
    // LZ4Compressor.compress and so eliminate memory copies.
    ByteBuf output = input.alloc().directBuffer(INTEGER_BYTES + maxCompressedLength);
    try {//ww w  .j  av  a2 s .  c o  m
        ByteBuffer in = inputNioBuffer(input);
        // Increase reader index.
        input.readerIndex(input.writerIndex());

        output.writeInt(in.remaining());

        ByteBuffer out = outputNioBuffer(output);
        int written = compressor.compress(in, in.position(), in.remaining(), out, out.position(),
                out.remaining());
        // Set the writer index so the amount of written bytes is reflected
        output.writerIndex(output.writerIndex() + written);
    } catch (Exception e) {
        // release output buffer so we not leak and rethrow exception.
        output.release();
        throw new IOException(e);
    }
    return output;
}

From source file:com.datastax.driver.core.LZ4Compressor.java

License:Apache License

private ByteBuf compressHeap(ByteBuf input) throws IOException {
    int maxCompressedLength = compressor.maxCompressedLength(input.readableBytes());

    // Not a direct buffer so use byte arrays...
    int inOffset = input.arrayOffset() + input.readerIndex();
    byte[] in = input.array();
    int len = input.readableBytes();
    // Increase reader index.
    input.readerIndex(input.writerIndex());

    // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so
    // can eliminate the overhead of allocate a new byte[].
    ByteBuf output = input.alloc().heapBuffer(INTEGER_BYTES + maxCompressedLength);
    try {//  w w w  .j a  v a2  s.c o m
        output.writeInt(len);
        // calculate the correct offset.
        int offset = output.arrayOffset() + output.writerIndex();
        byte[] out = output.array();
        int written = compressor.compress(in, inOffset, len, out, offset);

        // Set the writer index so the amount of written bytes is reflected
        output.writerIndex(output.writerIndex() + written);
    } catch (Exception e) {
        // release output buffer so we not leak and rethrow exception.
        output.release();
        throw new IOException(e);
    }
    return output;
}

From source file:com.Da_Technomancer.crossroads.API.packets.Message.java

License:Creative Commons License

private static void writeInt(int i, ByteBuf buf) {
    buf.writeInt(i);
}

From source file:com.Da_Technomancer.crossroads.API.packets.Message.java

License:Creative Commons License

private static void writeByte2DArray(byte[][] bytes, ByteBuf buf) {
    buf.writeInt(bytes.length);
    buf.writeInt(bytes[0].length);// ww w . j av  a2s  .  c  o m
    for (byte[] inner : bytes) {
        buf.writeBytes(inner);
    }
}

From source file:com.Da_Technomancer.crossroads.API.packets.Message.java

License:Creative Commons License

private static void writeIntArray(int[] ints, ByteBuf buf) {
    buf.writeInt(ints.length);
    for (int inner : ints) {
        buf.writeInt(inner);/*from w w  w .j  av a  2  s.  c om*/
    }
}

From source file:com.Da_Technomancer.crossroads.API.packets.Message.java

License:Creative Commons License

private static void writeDoubleArray(double[] doubles, ByteBuf buf) {
    buf.writeInt(doubles.length);
    for (double inner : doubles) {
        buf.writeDouble(inner);//from w ww.jav a2  s  .  c o  m
    }
}

From source file:com.dc.gameserver.ServerCore.Controller.AbstractController.AbstractController.java

License:Apache License

/**
 * Encoder buffer            </br>
 * 2            </br>// w w  w  .j av a 2s.  c  o m
 *
 * @param ID          ??
 * @param messageLite byte[]
 * @return
 */
public static ByteBuf wrappedBufferShort(int ID, MessageLite messageLite) {
    byte[] src = messageLite.toByteArray();
    int length = 6 + src.length;
    ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(length, length);
    buffer.setIndex(0, 0x2);//writeIndex?     2
    buffer.writeInt(ID); //?                4
    buffer.writeBytes(src);
    buffer.setShort(0, buffer.writerIndex() - 0x2); //  short
    messageLite = null; //set null ,collection by GC
    return buffer;
}

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 w  w .  j a  va2 s .c om*/
    out.writeInt(msg.getData().length);
    out.writeBytes(msg.getData());
}

From source file:com.dianping.cat.message.spi.codec.NativeMessageCodec.java

License:Open Source License

@Override
public ByteBuf encode(MessageTree tree) {
    ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(4 * 1024);

    try {//from ww  w  . ja  v  a2s.  co m
        Context ctx = new Context(tree);

        buf.writeInt(0); // place-holder

        Codec.HEADER.encode(ctx, buf, null);

        Message msg = tree.getMessage();

        if (msg != null) {
            encodeMessage(ctx, buf, msg);
        }
        int readableBytes = buf.readableBytes();

        buf.setInt(0, readableBytes - 4); // reset the message size

        return buf;
    } catch (RuntimeException e) {
        buf.release();

        throw e;
    }
}

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