Example usage for io.netty.buffer ByteBuf setInt

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

Introduction

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

Prototype

public abstract ByteBuf setInt(int index, int value);

Source Link

Document

Sets the specified 32-bit integer at the specified absolute index in this buffer.

Usage

From source file:org.apache.giraph.comm.netty.handler.RequestEncoder.java

License:Apache License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (!(msg instanceof WritableRequest)) {
        throw new IllegalArgumentException("encode: Got a message of type " + msg.getClass());
    }//from   ww  w.  ja v  a 2 s  .c  o m

    // Encode the request
    if (LOG.isDebugEnabled()) {
        startEncodingNanoseconds = TIME.getNanoseconds();
    }

    ByteBuf buf;
    WritableRequest request = (WritableRequest) msg;
    int requestSize = request.getSerializedSize();
    if (requestSize == WritableRequest.UNKNOWN_SIZE) {
        buf = ctx.alloc().buffer(bufferStartingSize);
    } else {
        requestSize += SIZE_OF_INT + SIZE_OF_BYTE;
        buf = ctx.alloc().buffer(requestSize);
    }
    ByteBufOutputStream output = new ByteBufOutputStream(buf);

    // This will later be filled with the correct size of serialized request
    output.writeInt(0);
    output.writeByte(request.getType().ordinal());
    try {
        request.write(output);
    } catch (IndexOutOfBoundsException e) {
        LOG.error("write: Most likely the size of request was not properly "
                + "specified (this buffer is too small) - see getSerializedSize() " + "in "
                + request.getType().getRequestClass());
        throw new IllegalStateException(e);
    }
    output.flush();
    output.close();

    // Set the correct size at the end
    buf.setInt(0, buf.writerIndex() - SIZE_OF_INT);
    if (LOG.isDebugEnabled()) {
        LOG.debug("write: Client " + request.getClientId() + ", " + "requestId " + request.getRequestId()
                + ", size = " + buf.readableBytes() + ", " + request.getType() + " took "
                + Times.getNanosSince(TIME, startEncodingNanoseconds) + " ns");
    }
    ctx.write(buf, promise);
}

From source file:org.apache.giraph.comm.netty.handler.ResponseEncoder.java

License:Apache License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("write(" + ctx + "," + msg);
    }/*from  w ww .j  a v a 2  s . com*/

    if (!(msg instanceof WritableRequest)) {
        throw new IllegalArgumentException("encode: cannot encode message of type " + msg.getClass()
                + " since it is not an instance of an implementation of " + " WritableRequest.");
    }
    @SuppressWarnings("unchecked")
    WritableRequest writableRequest = (WritableRequest) msg;

    ByteBuf buf = ctx.alloc().buffer(10);
    ByteBufOutputStream output = new ByteBufOutputStream(buf);

    if (LOG.isDebugEnabled()) {
        LOG.debug("encode: Encoding a message of type " + msg.getClass());
    }

    // Space is reserved now to be filled later by the serialize request size
    output.writeInt(0);
    // write type of object.
    output.writeByte(writableRequest.getType().ordinal());
    // write the object itself.
    writableRequest.write(output);

    output.flush();
    output.close();

    // Set the correct size at the end.
    buf.setInt(0, buf.writerIndex() - SIZE_OF_INT);

    if (LOG.isDebugEnabled()) {
        LOG.debug("encode: Encoding a message of type " + msg.getClass());
    }
    ctx.write(buf, promise);
    /*if[HADOOP_NON_SECURE]
    else[HADOOP_NON_SECURE]*/
    if (writableRequest.getType() == RequestType.SASL_COMPLETE_REQUEST) {
        // We are sending to the client a SASL_COMPLETE response (created by
        // the SaslServer handler). The SaslServer handler has removed itself
        // from the pipeline after creating this response, and now it's time for
        // the ResponseEncoder to remove itself also.
        if (LOG.isDebugEnabled()) {
            LOG.debug("encode: Removing RequestEncoder handler: no longer needed," + " since client: "
                    + ctx.channel().remoteAddress() + " has " + "completed authenticating.");
        }
        ctx.pipeline().remove(this);
    }
    /*end[HADOOP_NON_SECURE]*/
    ctx.write(buf, promise);
}

From source file:org.dcache.xrootd.security.NestedBucketBuffer.java

License:Open Source License

@Override
/**//  w w w . ja  v  a2  s. co  m
 * Serialize all the buckets in that buffer to an outputstream.
 *
 * @param out The ByteBuf to which this buffer will be serialized
 */
public void serialize(ByteBuf out) {

    super.serialize(out);

    //
    // The nesting is a bit tricky. First, we skip 4 bytes (here we store later the
    // size of the nested serialized bucket buffer, which we don't know yet). Then, we
    // serialize the nested bucket buffer and store it in the bytebuffer. Then we jump
    // back to the previously marked position and store the size of the nested bucket buffer.
    //
    int start = out.writerIndex();
    out.writeInt(0); // placeholder value

    /* the protocol is be 0-padded to 4 bytes */
    byte[] protocol = _protocol.getBytes(US_ASCII);
    out.writeBytes(protocol);
    out.writeZero(4 - protocol.length);

    out.writeInt(_step);

    for (XrootdBucket bucket : _nestedBuckets.values()) {
        bucket.serialize(out);
    }

    out.writeInt(BucketType.kXRS_none.getCode());

    out.setInt(start, out.writerIndex() - start - 4);
}

From source file:org.jfxvnc.net.rfb.codec.decoder.rect.CursorRectDecoder.java

License:Apache License

@Override
protected void sendRect(List<Object> out) {
    int i = 0;/*  w  ww .j  a  va  2 s  .c  o m*/
    ByteBuf pixels = aloc.buffer(capacity - bitMaskLength);
    while (pixels.isWritable(4)) {
        pixels.writeInt(framebuffer.getUnsignedByte(i * 4 + redPos) << pixelFormat.getRedShift()
                | framebuffer.getUnsignedByte(i * 4 + 1) << pixelFormat.getGreenShift()
                | framebuffer.getUnsignedByte(i * 4 + bluePos) << pixelFormat.getBlueShift() | 0xff000000);
        i++;
    }

    if (bitMaskLength > 0) {
        ByteBuf bitmask = aloc.buffer(bitMaskLength);
        framebuffer.getBytes(capacity - bitMaskLength, bitmask);
        // remove transparent pixels
        int maskBytesPerRow = Math.floorDiv((rect.getWidth() + 7), 8);
        IntStream.range(0, rect.getHeight())
                .forEach(y -> IntStream.range(0, rect.getWidth())
                        .filter(x -> (bitmask.getByte((y * maskBytesPerRow) + Math.floorDiv(x, 8))
                                & (1 << 7 - Math.floorMod(x, 8))) < 1)
                        .forEach(x -> pixels.setInt((y * rect.getWidth() + x) * 4, 0)));
        bitmask.release();
    }
    out.add(new CursorImageRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight(), pixels));
}

From source file:org.l2junity.loginserver.network.client.crypt.Crypt.java

License:Open Source License

@Override
public void encrypt(ByteBuf buf) {
    // Ensure that byte order is little endian because we set new packet size in first 2 bytes
    if (buf.order() != ByteOrder.LITTLE_ENDIAN) {
        buf = buf.order(ByteOrder.LITTLE_ENDIAN);
    }/*from  w  ww  . j  a  v  a  2 s  .c o m*/

    // Checksum & XOR Key or Checksum only
    buf.writeZero(_static ? 8 : 4);

    // Padding
    buf.writeZero(8 - (buf.readableBytes() % 8));

    if (_static) {
        _static = false;

        int key = Rnd.nextInt();
        buf.skipBytes(4); // The first 4 bytes are ignored
        while (buf.readerIndex() < (buf.writerIndex() - 8)) {
            int data = buf.readInt();
            key += data;
            data ^= key;
            buf.setInt(buf.readerIndex() - 4, data);
        }
        buf.setInt(buf.readerIndex(), key);

        buf.resetReaderIndex();

        final byte[] block = new byte[8];
        while (buf.isReadable(8)) {
            buf.readBytes(block);
            STATIC_BLOWFISH_ENGINE.encryptBlock(block, 0);
            buf.setBytes(buf.readerIndex() - block.length, block);
        }
    } else {
        int checksum = 0;
        while (buf.isReadable(8)) {
            checksum ^= buf.readInt();
        }
        buf.setInt(buf.readerIndex(), checksum);

        buf.resetReaderIndex();

        final byte[] block = new byte[8];
        while (buf.isReadable(8)) {
            buf.readBytes(block);
            _blowfishEngine.encryptBlock(block, 0);
            buf.setBytes(buf.readerIndex() - block.length, block);
        }
    }
}

From source file:org.opendaylight.netide.openflowjava.protocol.impl.serialization.factories.MultipartReplyMessageFactory.java

License:Open Source License

private void serializeMeterBody(MultipartReplyBody body, ByteBuf outBuffer) {
    MultipartReplyMeterCase meterCase = (MultipartReplyMeterCase) body;
    MultipartReplyMeter meter = meterCase.getMultipartReplyMeter();
    for (MeterStats meterStats : meter.getMeterStats()) {
        ByteBuf meterStatsBuff = UnpooledByteBufAllocator.DEFAULT.buffer();
        meterStatsBuff.writeInt(meterStats.getMeterId().getValue().intValue());
        meterStatsBuff.writeInt(EncodeConstants.EMPTY_LENGTH);
        meterStatsBuff.writeZero(METER_PADDING);
        meterStatsBuff.writeInt(meterStats.getFlowCount().intValue());
        meterStatsBuff.writeLong(meterStats.getPacketInCount().longValue());
        meterStatsBuff.writeLong(meterStats.getByteInCount().longValue());
        meterStatsBuff.writeInt(meterStats.getDurationSec().intValue());
        meterStatsBuff.writeInt(meterStats.getDurationNsec().intValue());
        for (MeterBandStats meterBandStats : meterStats.getMeterBandStats()) {
            meterStatsBuff.writeLong(meterBandStats.getPacketBandCount().longValue());
            meterStatsBuff.writeLong(meterBandStats.getByteBandCount().longValue());
        }//w w  w . j  a v a  2  s.  co m
        meterStatsBuff.setInt(METER_LENGTH_INDEX, meterStatsBuff.readableBytes());
        outBuffer.writeBytes(meterStatsBuff);
    }
}

From source file:org.opendaylight.openflowjava.protocol.impl.serialization.factories.MultipartReplyMessageFactory.java

License:Open Source License

private void serializeMeterBody(final MultipartReplyBody body, final ByteBuf outBuffer) {
    MultipartReplyMeterCase meterCase = (MultipartReplyMeterCase) body;
    MultipartReplyMeter meter = meterCase.getMultipartReplyMeter();
    for (MeterStats meterStats : meter.getMeterStats()) {
        ByteBuf meterStatsBuff = UnpooledByteBufAllocator.DEFAULT.buffer();
        meterStatsBuff.writeInt(meterStats.getMeterId().getValue().intValue());
        meterStatsBuff.writeInt(EncodeConstants.EMPTY_LENGTH);
        meterStatsBuff.writeZero(METER_PADDING);
        meterStatsBuff.writeInt(meterStats.getFlowCount().intValue());
        meterStatsBuff.writeLong(meterStats.getPacketInCount().longValue());
        meterStatsBuff.writeLong(meterStats.getByteInCount().longValue());
        meterStatsBuff.writeInt(meterStats.getDurationSec().intValue());
        meterStatsBuff.writeInt(meterStats.getDurationNsec().intValue());
        for (MeterBandStats meterBandStats : meterStats.getMeterBandStats()) {
            meterStatsBuff.writeLong(meterBandStats.getPacketBandCount().longValue());
            meterStatsBuff.writeLong(meterBandStats.getByteBandCount().longValue());
        }// w  w w . ja v  a  2s. co  m
        meterStatsBuff.setInt(METER_LENGTH_INDEX, meterStatsBuff.readableBytes());
        outBuffer.writeBytes(meterStatsBuff);
    }
}

From source file:org.teiid.transport.ObjectEncoder.java

License:Apache License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    ByteBuf out = allocateBuffer(ctx, this.estimatedLength, this.preferDirect);
    int startIdx = out.writerIndex();
    ByteBufOutputStream bout = new ByteBufOutputStream(out);
    bout.write(LENGTH_PLACEHOLDER);//  w  w  w .ja  v a  2 s. c o m
    final CompactObjectOutputStream oout = new CompactObjectOutputStream(bout);
    try {
        oout.writeObject(msg);
        ExternalizeUtil.writeCollection(oout, oout.getReferences());
        oout.flush();
        oout.close();

        int endIdx = out.writerIndex();
        out.setInt(startIdx, endIdx - startIdx - 4);

        if (out.isReadable()) {
            ctx.write(out, promise);
            for (InputStream is : oout.getStreams()) {
                ctx.write(new AnonymousChunkedStream(new BufferedInputStream(is, CHUNK_SIZE)), promise);
            }
        } else {
            out.release();
            ctx.write(Unpooled.EMPTY_BUFFER, promise);
        }
        ctx.flush();
        out = null;
    } catch (Throwable t) {
        throw new FailedWriteException(msg, t);
    } finally {
        if (out != null) {
            out.release();
        }
    }
}

From source file:org.tiger.netty.rpc.all.codec.MarshallingEncoder.java

License:Apache License

protected void encode(Object msg, ByteBuf out) throws Exception {
    try {/*from  ww w  .  j a v a  2s . com*/
        int lengthPos = out.writerIndex();
        out.writeBytes(LENGTH_PLACEHOLDER);//??
        ChannelBufferByteOutput output = new ChannelBufferByteOutput(out);
        marshaller.start(output);
        marshaller.writeObject(msg);
        marshaller.finish();
        //ByteBufsetInt(int index, int value):indexvalueint
        //?ByteBufwriteIntsetInt??readerIndexwriterIndex
        //??4??
        out.setInt(lengthPos, out.writerIndex() - lengthPos - 4);
    } finally {
        marshaller.close();
    }
}

From source file:org.tiger.netty.rpc.all.codec.NettyMessageEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, NettyMessage msg, ByteBuf sendBuf) throws Exception {
    System.out.println("NettyMessageEncoder encode ..." + System.currentTimeMillis());
    if (msg == null || msg.getHeader() == null)
        throw new Exception("The encode message is null");

    sendBuf.writeInt((msg.getHeader().getCrcCode()));
    //print(sendBuf);
    sendBuf.writeInt((msg.getHeader().getLength()));
    //print(sendBuf);
    sendBuf.writeLong((msg.getHeader().getSessionID()));
    //print(sendBuf);
    sendBuf.writeByte((msg.getHeader().getType()));
    //print(sendBuf);
    sendBuf.writeByte((msg.getHeader().getPriority()));
    //print(sendBuf);
    sendBuf.writeInt((msg.getHeader().getAttachment().size()));
    //print(sendBuf);
    String key = null;/*from  ww w.j  av  a  2 s .  c  o m*/
    byte[] keyArray = null;
    Object value = null;
    for (Map.Entry<String, Object> param : msg.getHeader().getAttachment().entrySet()) {
        key = param.getKey();
        keyArray = key.getBytes("UTF-8");
        sendBuf.writeInt(keyArray.length);
        sendBuf.writeBytes(keyArray);
        value = param.getValue();
        marshallingEncoder.encode(value, sendBuf);
    }
    key = null;
    keyArray = null;
    value = null;
    if (msg.getBody() != null) {
        marshallingEncoder.encode(msg.getBody(), sendBuf);
    } else {
        sendBuf.writeInt(0);
        //print(sendBuf);
    }

    System.out.println(sendBuf.readableBytes());
    //???4 int? 8?4?int??4intlengthlengthlength????8
    sendBuf.setInt(4, sendBuf.readableBytes() - 8);
    //print(sendBuf);
    //sendBuf.writeInt(0);
}