Example usage for io.netty.buffer ByteBuf setByte

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

Introduction

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

Prototype

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

Source Link

Document

Sets the specified byte at the specified absolute index in this buffer.

Usage

From source file:org.apache.tajo.util.BytesUtils.java

License:Apache License

/**
 * this is an implementation copied from ByteBufUtil in netty4
 *///from w w w .  j a  v a  2s .c o  m
public static int writeUtf8(ByteBuf buffer, char[] chars, boolean ignoreSurrogate) {
    int oldWriterIndex = buffer.writerIndex();
    int writerIndex = oldWriterIndex;

    // We can use the _set methods as these not need to do any index checks and reference checks.
    // This is possible as we called ensureWritable(...) before.
    for (int i = 0; i < chars.length; i++) {
        char c = chars[i];
        if (c < 0x80) {
            buffer.setByte(writerIndex++, (byte) c);
        } else if (c < 0x800) {
            buffer.setByte(writerIndex++, (byte) (0xc0 | (c >> 6)));
            buffer.setByte(writerIndex++, (byte) (0x80 | (c & 0x3f)));
        } else if (!ignoreSurrogate && isSurrogate(c)) {
            if (!Character.isHighSurrogate(c)) {
                throw new IllegalArgumentException("Invalid encoding. "
                        + "Expected high (leading) surrogate at index " + i + " but got " + c);
            }
            final char c2;
            try {
                // Surrogate Pair consumes 2 characters. Optimistically try to get the next character to avoid
                // duplicate bounds checking with charAt. If an IndexOutOfBoundsException is thrown we will
                // re-throw a more informative exception describing the problem.
                c2 = chars[++i];
            } catch (IndexOutOfBoundsException e) {
                throw new IllegalArgumentException("Underflow. " + "Expected low (trailing) surrogate at index "
                        + i + " but no more characters found.", e);
            }
            if (!Character.isLowSurrogate(c2)) {
                throw new IllegalArgumentException("Invalid encoding. "
                        + "Expected low (trailing) surrogate at index " + i + " but got " + c2);
            }
            int codePoint = Character.toCodePoint(c, c2);
            // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G2630.
            buffer.setByte(writerIndex++, (byte) (0xf0 | (codePoint >> 18)));
            buffer.setByte(writerIndex++, (byte) (0x80 | ((codePoint >> 12) & 0x3f)));
            buffer.setByte(writerIndex++, (byte) (0x80 | ((codePoint >> 6) & 0x3f)));
            buffer.setByte(writerIndex++, (byte) (0x80 | (codePoint & 0x3f)));
        } else {
            buffer.setByte(writerIndex++, (byte) (0xe0 | (c >> 12)));
            buffer.setByte(writerIndex++, (byte) (0x80 | ((c >> 6) & 0x3f)));
            buffer.setByte(writerIndex++, (byte) (0x80 | (c & 0x3f)));
        }
    }
    // update the writerIndex without any extra checks for performance reasons
    buffer.writerIndex(writerIndex);
    return writerIndex - oldWriterIndex;
}

From source file:org.bgp4j.netty.protocol.open.OpenPacket.java

License:Apache License

@Override
protected void encodePayload(ByteBuf buffer) {
    buffer.writeByte(getProtocolVersion());
    buffer.writeShort(getAutonomousSystem());
    buffer.writeShort(getHoldTime());//from w w  w. j  av  a2  s .c o m
    buffer.writeInt((int) getBgpIdentifier());

    if (!capabilities.isEmpty()) {
        int capabilityLengthIndex = buffer.writerIndex();

        buffer.writeByte(0); // placeholder for capability length
        buffer.writeByte(BGPv4Constants.BGP_OPEN_PARAMETER_TYPE_CAPABILITY); // type byte

        int parameterLengthIndex = buffer.writerIndex();

        buffer.writeByte(0); // placeholder for parameter length
        CapabilityCodec.encodeCapabilities(buffer, getCapabilities());

        buffer.setByte(capabilityLengthIndex, buffer.writerIndex() - capabilityLengthIndex - 1);
        buffer.setByte(parameterLengthIndex, buffer.writerIndex() - parameterLengthIndex - 1);
    } else {
        buffer.writeByte(0); // no capabilites encoded --> optional parameter length equals 0
    }
}

From source file:org.elasticsearch.http.nio.HttpReadWriteHandlerTests.java

License:Apache License

public void testDecodeHttpRequestError() throws IOException {
    String uri = "localhost:9090/" + randomAlphaOfLength(8);
    io.netty.handler.codec.http.HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
            HttpMethod.GET, uri);/*from w w w  .ja  va2 s.c o m*/

    ByteBuf buf = requestEncoder.encode(httpRequest);
    try {
        buf.setByte(0, ' ');
        buf.setByte(1, ' ');
        buf.setByte(2, ' ');

        handler.consumeReads(toChannelBuffer(buf));

        ArgumentCaptor<Exception> exceptionCaptor = ArgumentCaptor.forClass(Exception.class);
        verify(transport).incomingRequestError(any(HttpRequest.class), any(NioHttpChannel.class),
                exceptionCaptor.capture());

        assertTrue(exceptionCaptor.getValue() instanceof IllegalArgumentException);
    } finally {
        buf.release();
    }
}

From source file:org.onosproject.lisp.msg.types.lcaf.LispLcafAddress.java

License:Apache License

/**
 * Updates the header length field value based on the size of LISP header.
 *
 * @param lcafIndex the index of LCAF address, because LCAF address is
 *                  contained inside LISP control message, so to correctly
 *                  find the right LCAF length index, we need to know the
 *                  absolute lcaf index inside LISP control message byte buf
 * @param byteBuf   netty byte buffer//from  w w  w  .  j a  va 2  s.  c om
 */
public static void updateLength(int lcafIndex, ByteBuf byteBuf) {
    byteBuf.setByte(lcafIndex + LENGTH_FIELD_INDEX, byteBuf.writerIndex() - COMMON_HEADER_SIZE - lcafIndex);
}

From source file:org.starnub.starbounddata.packets.Packet.java

License:Open Source License

/**
 * Recommended: For internal use with StarNub packet decoding
 * <p>//from w w  w.ja va2  s .  c  o m
 * Uses: This will write a s{@link org.starnub.starbounddata.types.variants.VLQ} to a {@link io.netty.buffer.ByteBuf}
 * <p>
 * Notes: This will not create a VLQ object and should be used
 * <p>
 *
 * @param out   ByteBuf in which is to be read
 * @param value long representing the VLQ value to be written out
 */
protected static void writeSVLQPacketEncoder(ByteBuf out, long value) {
    if (value < 0) {
        value = ((-(value + 1)) << 1) | 1;
    } else {
        value = value << 1;
    }
    int numRelevantBits = 64 - Long.numberOfLeadingZeros(value);
    int numBytes = (numRelevantBits + 6) / 7;
    if (numBytes == 0) {
        numBytes = 1;
    }
    out.writerIndex(numBytes + 1); /* Sets the write index at the number of bytes + 1 byte for packet id */
    for (int i = numBytes - 1; i >= 0; i--) {
        int curByte = (int) (value & 0x7F);
        if (i != (numBytes - 1)) {
            curByte |= 0x80;
        }
        out.setByte(i + 1, curByte); /* Sets the byte at index + 1 byte for packet id */
        value >>>= 7;
    }
}

From source file:org.traccar.protocol.M2mProtocolDecoder.java

License:Apache License

@Override
protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    ByteBuf buf = (ByteBuf) msg;

    // Remove offset
    for (int i = 0; i < buf.readableBytes(); i++) {
        int b = buf.getByte(i);
        if (b != 0x0b) {
            buf.setByte(i, b - 0x20);
        }/*from  w  w w  . java2 s .  c  o m*/
    }

    if (firstPacket) {

        firstPacket = false;

        StringBuilder imei = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            int b = buf.readByte();
            if (i != 0) {
                imei.append(b / 10);
            }
            imei.append(b % 10);
        }

        getDeviceSession(channel, remoteAddress, imei.toString());

    } else {

        DeviceSession deviceSession = getDeviceSession(channel, remoteAddress);
        if (deviceSession == null) {
            return null;
        }

        Position position = new Position(getProtocolName());
        position.setDeviceId(deviceSession.getDeviceId());

        DateBuilder dateBuilder = new DateBuilder().setDay(buf.readUnsignedByte() & 0x3f)
                .setMonth(buf.readUnsignedByte() & 0x3f).setYear(buf.readUnsignedByte())
                .setHour(buf.readUnsignedByte() & 0x3f).setMinute(buf.readUnsignedByte() & 0x7f)
                .setSecond(buf.readUnsignedByte() & 0x7f);
        position.setTime(dateBuilder.getDate());

        int degrees = buf.readUnsignedByte();
        double latitude = buf.readUnsignedByte();
        latitude += buf.readUnsignedByte() / 100.0;
        latitude += buf.readUnsignedByte() / 10000.0;
        latitude /= 60;
        latitude += degrees;

        int b = buf.readUnsignedByte();

        degrees = (b & 0x7f) * 100 + buf.readUnsignedByte();
        double longitude = buf.readUnsignedByte();
        longitude += buf.readUnsignedByte() / 100.0;
        longitude += buf.readUnsignedByte() / 10000.0;
        longitude /= 60;
        longitude += degrees;

        if ((b & 0x80) != 0) {
            longitude = -longitude;
        }
        if ((b & 0x40) != 0) {
            latitude = -latitude;
        }

        position.setValid(true);
        position.setLatitude(latitude);
        position.setLongitude(longitude);
        position.setSpeed(buf.readUnsignedByte());

        int satellites = buf.readUnsignedByte();
        if (satellites == 0) {
            return null; // cell information
        }
        position.set(Position.KEY_SATELLITES, satellites);

        // decode other data

        return position;

    }

    return null;
}

From source file:ru.jts_dev.gameserver.util.Encoder.java

License:Open Source License

@Transformer
public ByteBuf decrypt(ByteBuf data, @Header(CONNECTION_ID) String connectionId) {
    GameSession gameSession = sessionService.getSessionBy(connectionId);

    assert gameSession != null : "GameSession for " + connectionId + " does not exist";

    ByteBuf key = gameSession.getDecryptKey();

    int temp = 0;
    for (int i = 0; i < data.readableBytes(); i++) {
        final int temp2 = data.getUnsignedByte(i);
        data.setByte(i, (byte) (temp2 ^ key.getByte(i & 15) ^ temp));
        temp = temp2;/*from w  w  w  . ja v  a 2 s . c om*/
    }

    int old = key.getInt(8);
    old += data.readableBytes();

    key.setInt(8, old);

    return data;
}

From source file:ru.jts_dev.gameserver.util.Encoder.java

License:Open Source License

@Transformer
public ByteBuf encrypt(ByteBuf data, @Header(CONNECTION_ID) String connectionId) {
    GameSession gameSession = sessionService.getSessionBy(connectionId);

    assert gameSession != null : "GameSession for " + connectionId + " does not exist";

    ByteBuf key = gameSession.getEncryptKey();

    int temp = 0;
    for (int i = 0; i < data.readableBytes(); i++) {
        int temp2 = data.getUnsignedByte(data.readerIndex() + i);
        temp = temp2 ^ key.getByte(i & 15) ^ temp;
        data.setByte(data.readerIndex() + i, (byte) temp);
    }//from  w  w  w .j  a v  a2s  .co m

    int old = key.getInt(8);
    old += data.readableBytes();

    key.setInt(8, old);

    return data;
}

From source file:se.sics.caracaldb.global.MaintenanceSerializer.java

License:Open Source License

@Override
public void toBinary(Object o, ByteBuf buf) {
    if (o instanceof MaintenanceMsg) {
        MaintenanceMsg msg = (MaintenanceMsg) o;
        int flagPos = buf.writerIndex();
        buf.writeByte(0); // reserve for flags
        BitBuffer flags = BitBuffer.create(MSG); // 0
        SpecialSerializers.MessageSerializationUtil.msgToBinary(msg, buf, false, false);
        toBinaryOp(msg.op, buf, flags);/*from  w  w  w.j a v  a2  s .  co  m*/
        byte[] flagsB = flags.finalise();
        buf.setByte(flagPos, flagsB[0]);
        return;
    }
    if (o instanceof Maintenance) {
        int flagPos = buf.writerIndex();
        buf.writeByte(0); // reserve for flags
        BitBuffer flags = BitBuffer.create(OP); // 0
        toBinaryOp((Maintenance) o, buf, flags);
        byte[] flagsB = flags.finalise();
        buf.setByte(flagPos, flagsB[0]);
        return;
    }
    LOG.warn("Couldn't serialize {}: {}", o, o.getClass());
}

From source file:se.sics.caracaldb.operations.ConditionSerializer.java

License:Open Source License

@Override
public void toBinary(Object o, ByteBuf buf) {
    if (o instanceof Condition) {
        Condition c = (Condition) o;
        int flagPos = buf.writerIndex();
        buf.writeByte(0); // reserve for flags
        BitBuffer flags = BitBuffer.create(false); // reserve 0
        toBinaryCondition(c, buf, flags);
        byte[] flagsB = flags.finalise();
        buf.setByte(flagPos, flagsB[0]);
        return;/* w ww .  j  a  va  2  s .  c  o m*/
    }
    LOG.warn("Couldn't serialize {}: {}", o, o.getClass());
}