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:com.allanbank.mongodb.netty.ByteToMessageDecoderTest.java

License:Apache License

/**
 * Test method for/* w  ww  .jav a  2  s  .c o  m*/
 * {@link ByteToMessageDecoder#decode(ChannelHandlerContext, ByteBuf)}.
 *
 * @throws Exception
 *             On a test failure.
 */
@Test
public void testDecodeBadOpCode() throws Exception {
    final Random rand = new Random(System.currentTimeMillis());
    final Message msg = new KillCursors(new long[] { rand.nextLong() }, ReadPreference.PRIMARY);
    final int msgId = rand.nextInt() & 0xFFFFFF;

    final ByteBuf buffer = ourAllocator.buffer();

    final ByteBufOutputStream out = new ByteBufOutputStream(buffer);
    final BsonOutputStream bout = new BsonOutputStream(out);

    msg.write(msgId, bout);

    // OpCode is bytes 12-16.
    buffer.setByte(12, (byte) 0xAA);
    buffer.setByte(13, (byte) 0xBB);
    buffer.setByte(14, (byte) 0xCC);
    buffer.setByte(15, (byte) 0xDD);

    final ChannelHandlerContext mockContext = createMock(ChannelHandlerContext.class);

    replay(mockContext);

    final ByteToMessageDecoder decoder = new ByteToMessageDecoder(new StringDecoderCache());

    try {
        decoder.decode(mockContext, out.buffer());
        fail("Should have thrown a MongoDBException.");
    } catch (final MongoDbException good) {
        assertThat(good.getMessage(), is("Unexpected operation read '" + 0xDDCCBBAA + "'."));
    }

    verify(mockContext);
}

From source file:com.allanbank.mongodb.netty.ByteToMessageDecoderTest.java

License:Apache License

/**
 * Test method for//from w w w  .  ja v a 2s . c  o  m
 * {@link ByteToMessageDecoder#extractFrame(ChannelHandlerContext, ByteBuf, int, int)}
 * .
 */
@Test
public void testExtractFrameChannelHandlerContextByteBufIntInt() {
    final ByteBuf buffer = ourAllocator.buffer();

    buffer.writeBytes(new byte[1000]);

    final ChannelHandlerContext mockContext = createMock(ChannelHandlerContext.class);

    replay(mockContext);

    final ByteToMessageDecoder decoder = new ByteToMessageDecoder(new StringDecoderCache());

    final ByteBuf result = decoder.extractFrame(mockContext, buffer, 100, 200);
    assertThat(result, instanceOf(SlicedByteBuf.class));

    assertThat(buffer.getByte(100), is((byte) 0));
    result.setByte(0, 1);
    assertThat(buffer.getByte(100), is((byte) 1));

    verify(mockContext);
}

From source file:com.comphenix.protocol.compat.netty.independent.NettyByteBufAdapter.java

License:Open Source License

@Override
public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) {
    try {/*from w w  w . j  a  va 2  s . c o m*/
        for (int i = 0; i < length; i++) {
            dst.setByte(dstIndex + i, input.read());
        }
    } catch (IOException e) {
        throw new RuntimeException("Cannot read input.", e);
    }
    return this;
}

From source file:com.couchbase.client.core.endpoint.view.ViewHandler.java

License:Apache License

/**
 * Parse out the info portion from the header part of the query response.
 *
 * This includes the total rows, but also debug info if attached.
 *//*from  w w  w  .  j  a  va  2 s. com*/
private void parseViewInfo() {
    int rowsStart = -1;
    for (int i = responseContent.readerIndex(); i < responseContent.writerIndex() - 2; i++) {
        byte curr = responseContent.getByte(i);
        byte f1 = responseContent.getByte(i + 1);
        byte f2 = responseContent.getByte(i + 2);

        if (curr == '"' && f1 == 'r' && f2 == 'o') {
            rowsStart = i;
            break;
        }
    }

    if (rowsStart == -1) {
        return;
    }

    ByteBuf info = responseContent.readBytes(rowsStart - responseContent.readerIndex());
    int closingPointer = info.forEachByteDesc(new ByteBufProcessor() {
        @Override
        public boolean process(byte value) throws Exception {
            return value != ',';
        }
    });

    if (closingPointer > 0) {
        info.setByte(closingPointer, '}');
        viewInfoObservable.onNext(info);
    } else {
        viewInfoObservable.onNext(Unpooled.EMPTY_BUFFER);
    }
    viewInfoObservable.onCompleted();
    viewParsingState = QUERY_STATE_ROWS;
}

From source file:com.l2jmobius.gameserver.network.client.Crypt.java

License:Open Source License

@Override
public void encrypt(ByteBuf buf) {
    if (!_isEnabled) {
        _isEnabled = true;// w  w w.  j  a  va  2s  .co m
        onPacketSent(buf);
        return;
    }

    onPacketSent(buf);

    int a = 0;
    while (buf.isReadable()) {
        final int b = buf.readByte() & 0xFF;
        a = b ^ _outKey[(buf.readerIndex() - 1) & 15] ^ a;
        buf.setByte(buf.readerIndex() - 1, a);
    }

    shiftKey(_outKey, buf.writerIndex());
}

From source file:com.l2jmobius.gameserver.network.client.Crypt.java

License:Open Source License

@Override
public void decrypt(ByteBuf buf) {
    if (!_isEnabled) {
        onPacketReceive(buf);// w  ww .  ja  v  a2  s.c  o m
        return;
    }

    int a = 0;
    while (buf.isReadable()) {
        final int b = buf.readByte() & 0xFF;
        buf.setByte(buf.readerIndex() - 1, b ^ _inKey[(buf.readerIndex() - 1) & 15] ^ a);
        a = b;
    }

    shiftKey(_inKey, buf.writerIndex());

    onPacketReceive(buf);
}

From source file:com.linecorp.armeria.server.grpc.ArmeriaServerCall.java

License:Apache License

private static void encodeHeader(CharSequence name, CharSequence value, ByteBuf buf) {
    final int nameLen = name.length();
    final int valueLen = value.length();
    final int entryLen = nameLen + valueLen + 4;
    buf.ensureWritable(entryLen);//from   ww  w .j a v  a2s. c  om
    int offset = buf.writerIndex();
    writeAscii(buf, offset, name, nameLen);
    offset += nameLen;
    buf.setByte(offset++, ':');
    buf.setByte(offset++, ' ');
    writeAscii(buf, offset, value, valueLen);
    offset += valueLen;
    buf.setByte(offset++, '\r');
    buf.setByte(offset++, '\n');
    buf.writerIndex(offset);
}

From source file:com.linecorp.armeria.server.grpc.ArmeriaServerCall.java

License:Apache License

private static void writeCharSequence(ByteBuf buf, int offset, CharSequence value, int valueLen) {
    for (int i = 0; i < valueLen; ++i) {
        buf.setByte(offset++, c2b(value.charAt(i)));
    }//  w w  w . ja va  2s.co  m
}

From source file:com.mobius.software.android.iotbroker.mqtt.parser.MQParser.java

License:Open Source License

public static ByteBuf encode(MQMessage header) throws UnsupportedEncodingException, MalformedMessageException {
    int length = header.getLength();
    ByteBuf buf = getBuffer(length);
    MessageType type = header.getType();

    switch (type) {
    case CONNECT:
        Connect connect = (Connect) header;
        if (connect.isWillFlag() && !connect.getWill().isValid())
            throw new MalformedMessageException("invalid will encoding");

        buf.setByte(0, (byte) (type.getNum() << 4));
        buf.writeShort(4);/*from   w  w w.  ja v  a  2s .  c  o m*/
        buf.writeBytes(connect.getName().getBytes());
        buf.writeByte(connect.getProtocolLevel());
        byte contentFlags = 0;
        contentFlags |= 0;
        contentFlags |= connect.isClean() ? 0x02 : 0;
        contentFlags |= connect.isWillFlag() ? 0x04 : 0;
        contentFlags |= connect.isWillFlag() ? connect.getWill().getTopic().getQos().getValue() << 3 : 0;
        contentFlags |= connect.isWillFlag() ? connect.getWill().getRetain() ? 0x20 : 0 : 0;
        contentFlags |= connect.isUsernameFlag() ? 0x40 : 0;
        contentFlags |= connect.isPasswordFlag() ? 0x80 : 0;
        buf.writeByte(contentFlags);
        buf.writeShort(connect.getKeepAlive());
        buf.writeShort(connect.getClientID().length());
        buf.writeBytes(connect.getClientID().getBytes("UTF-8"));

        if (connect.isWillFlag()) {
            Text willTopic = connect.getWill().getTopic().getName();
            if (willTopic != null) {
                buf.writeShort(willTopic.length());
                buf.writeBytes(willTopic.toString().getBytes("UTF-8"));
            }

            byte[] willMessage = connect.getWill().getContent();
            if (willMessage != null) {
                buf.writeShort(willMessage.length);
                buf.writeBytes(willMessage);
            }
        }

        String username = connect.getUserName();
        if (username != null) {
            buf.writeShort(username.length());
            buf.writeBytes(username.getBytes("UTF-8"));
        }

        String password = connect.getPassword();
        if (password != null) {
            buf.writeShort(password.length());
            buf.writeBytes(password.getBytes("UTF-8"));
        }
        break;

    case CONNACK:
        Connack connack = (Connack) header;
        buf.setByte(0, (byte) (type.getNum() << 4));
        buf.writeBoolean(connack.isSessionPresent());
        buf.writeByte(connack.getReturnCode().getNum());
        break;

    case PUBLISH:
        Publish publish = (Publish) header;
        byte firstByte = (byte) (type.getNum() << 4);
        firstByte |= publish.isDup() ? 8 : 0;
        firstByte |= (publish.getTopic().getQos().getValue() << 1);
        firstByte |= publish.isRetain() ? 1 : 0;
        buf.setByte(0, firstByte);
        buf.writeShort(publish.getTopic().length());
        buf.writeBytes(publish.getTopic().getName().toString().getBytes("UTF-8"));
        if (publish.getPacketID() != null)
            buf.writeShort(publish.getPacketID());
        buf.writeBytes(publish.getContent());
        break;

    case PUBACK:
        Puback puback = (Puback) header;
        buf.setByte(0, (byte) (type.getNum() << 4));
        buf.writeShort(puback.getPacketID());
        break;

    case PUBREC:
        Pubrec pubrec = (Pubrec) header;
        buf.setByte(0, (byte) (type.getNum() << 4));
        buf.writeShort(pubrec.getPacketID());
        break;

    case PUBREL:
        Pubrel pubrel = (Pubrel) header;
        buf.setByte(0, (byte) ((type.getNum() << 4) | 0x2));
        buf.writeShort(pubrel.getPacketID());
        break;

    case PUBCOMP:
        Pubcomp pubcomp = (Pubcomp) header;
        buf.setByte(0, (byte) (type.getNum() << 4));
        buf.writeShort(pubcomp.getPacketID());
        break;

    case SUBSCRIBE:
        Subscribe sub = (Subscribe) header;
        buf.setByte(0, (byte) ((type.getNum() << 4) | 0x2));
        if (sub.getPacketID() != null)
            buf.writeShort(sub.getPacketID());
        for (Topic subscription : sub.getTopics()) {
            buf.writeShort(subscription.getName().length());
            buf.writeBytes(subscription.getName().toString().getBytes("UTF-8"));
            buf.writeByte(subscription.getQos().getValue());
        }
        break;

    case SUBACK:
        Suback suback = (Suback) header;
        buf.setByte(0, (byte) (type.getNum() << 4));
        buf.writeShort(suback.getPacketID());
        for (SubackCode code : suback.getReturnCodes())
            buf.writeByte(code.getNum());
        break;

    case UNSUBSCRIBE:
        Unsubscribe unsub = (Unsubscribe) header;
        buf.setByte(0, (byte) ((type.getNum() << 4) | 0x2));
        buf.writeShort(unsub.getPacketID());
        for (Topic topic : unsub.getTopics()) {
            buf.writeShort(topic.getName().length());
            buf.writeBytes(topic.getName().toString().getBytes("UTF-8"));
        }
        break;

    case UNSUBACK:
        Unsuback unsuback = (Unsuback) header;
        buf.setByte(0, (byte) (type.getNum() << 4));
        buf.writeShort(unsuback.getPacketID());
        break;

    case DISCONNECT:
    case PINGREQ:
    case PINGRESP:
        buf.setByte(0, (byte) (type.getNum() << 4));
        break;

    default:
        throw new MalformedMessageException("Invalid header type: " + type);
    }

    return buf;
}

From source file:com.mobius.software.mqtt.parser.MQParser.java

License:Open Source License

public static ByteBuf encode(MQMessage header) throws MalformedMessageException {
    int length = header.getLength();
    ByteBuf buf = getBuffer(length);
    MessageType type = header.getType();
    try {/*  ww  w  . java2  s.  c  o m*/
        switch (type) {
        case CONNECT:
            Connect connect = (Connect) header;
            if (connect.isWillFlag() && !connect.getWill().isValid())
                throw new MalformedMessageException("invalid will encoding");

            buf.setByte(0, (byte) (type.getNum() << 4));
            buf.writeShort(4);
            buf.writeBytes(connect.getName().getBytes());
            buf.writeByte(connect.getProtocolLevel());

            byte contentFlags = 0;
            if (connect.isCleanSession())
                contentFlags += 2;
            if (connect.isWillFlag()) {
                contentFlags += 4;
                contentFlags += connect.getWill().getTopic().getQos().getValue() << 3;
                if (connect.getWill().isRetain())
                    contentFlags += 0x20;
            }
            if (connect.isPasswordFlag())
                contentFlags += 0x40;
            if (connect.isUsernameFlag())
                contentFlags += 0x80;
            buf.writeByte(contentFlags);

            buf.writeShort(connect.getKeepalive());
            buf.writeShort(connect.getClientID().length());
            buf.writeBytes(connect.getClientID().getBytes("UTF-8"));

            if (connect.isWillFlag()) {
                Text willTopic = connect.getWill().getTopic().getName();
                if (willTopic != null) {
                    buf.writeShort(willTopic.length());
                    buf.writeBytes(willTopic.toString().getBytes("UTF-8"));
                }

                byte[] willMessage = connect.getWill().getContent();
                if (willMessage != null) {
                    buf.writeShort(willMessage.length);
                    buf.writeBytes(willMessage);
                }
            }

            String username = connect.getUsername();
            if (username != null) {
                buf.writeShort(username.length());
                buf.writeBytes(username.getBytes("UTF-8"));
            }

            String password = connect.getPassword();
            if (password != null) {
                buf.writeShort(password.length());
                buf.writeBytes(password.getBytes("UTF-8"));
            }
            break;

        case CONNACK:
            Connack connack = (Connack) header;
            buf.setByte(0, (byte) (type.getNum() << 4));
            buf.writeBoolean(connack.isSessionPresent());
            buf.writeByte(connack.getReturnCode().getNum());
            break;

        case PUBLISH:
            Publish publish = (Publish) header;
            byte firstByte = (byte) (type.getNum() << 4);
            firstByte |= publish.isDup() ? 8 : 0;
            firstByte |= (publish.getTopic().getQos().getValue() << 1);
            firstByte |= publish.isRetain() ? 1 : 0;
            buf.setByte(0, firstByte);
            buf.writeShort(publish.getTopic().length());
            buf.writeBytes(publish.getTopic().getName().toString().getBytes("UTF-8"));
            switch (publish.getTopic().getQos()) {
            case AT_MOST_ONCE:
                if (publish.getPacketID() != null)
                    throw new MalformedMessageException("publish qos-0 must not contain packetID");
                break;
            case AT_LEAST_ONCE:
            case EXACTLY_ONCE:
                if (publish.getPacketID() == null)
                    throw new MalformedMessageException("publish qos-1,2 must contain packetID");
                buf.writeShort(publish.getPacketID());
                break;
            }
            buf.writeBytes(publish.getContent());
            break;

        case PUBACK:
            Puback puback = (Puback) header;
            buf.setByte(0, (byte) (type.getNum() << 4));
            if (puback.getPacketID() == null)
                throw new MalformedMessageException("puback must contain packetID");
            buf.writeShort(puback.getPacketID());
            break;

        case PUBREC:
            Pubrec pubrec = (Pubrec) header;
            buf.setByte(0, (byte) (type.getNum() << 4));
            if (pubrec.getPacketID() == null)
                throw new MalformedMessageException("pubrec must contain packetID");
            buf.writeShort(pubrec.getPacketID());
            break;

        case PUBREL:
            Pubrel pubrel = (Pubrel) header;
            buf.setByte(0, (byte) ((type.getNum() << 4) | 0x2));
            if (pubrel.getPacketID() == null)
                throw new MalformedMessageException("pubrel must contain packetID");
            buf.writeShort(pubrel.getPacketID());
            break;

        case PUBCOMP:
            Pubcomp pubcomp = (Pubcomp) header;
            buf.setByte(0, (byte) (type.getNum() << 4));
            if (pubcomp.getPacketID() == null)
                throw new MalformedMessageException("pubcomp must contain packetID");
            buf.writeShort(pubcomp.getPacketID());
            break;

        case SUBSCRIBE:
            Subscribe sub = (Subscribe) header;
            buf.setByte(0, (byte) ((type.getNum() << 4) | 0x2));
            if (sub.getPacketID() == null)
                throw new MalformedMessageException("subscribe must contain packetID");
            buf.writeShort(sub.getPacketID());
            for (Topic subscription : sub.getTopics()) {
                buf.writeShort(subscription.getName().length());
                buf.writeBytes(subscription.getName().toString().getBytes("UTF-8"));
                buf.writeByte(subscription.getQos().getValue());
            }
            break;

        case SUBACK:
            Suback suback = (Suback) header;
            buf.setByte(0, (byte) (type.getNum() << 4));
            if (suback.getPacketID() == null)
                throw new MalformedMessageException("suback must contain packetID");
            buf.writeShort(suback.getPacketID());
            for (SubackCode code : suback.getReturnCodes())
                buf.writeByte(code.getNum());
            break;

        case UNSUBSCRIBE:
            Unsubscribe unsub = (Unsubscribe) header;
            buf.setByte(0, (byte) ((type.getNum() << 4) | 0x2));
            if (unsub.getPacketID() == null)
                throw new MalformedMessageException("subscribe must contain packetID");
            buf.writeShort(unsub.getPacketID());
            for (Text topic : unsub.getTopics()) {
                buf.writeShort(topic.length());
                buf.writeBytes(topic.toString().getBytes("UTF-8"));
            }
            break;

        case UNSUBACK:
            Unsuback unsuback = (Unsuback) header;
            buf.setByte(0, (byte) (type.getNum() << 4));
            if (unsuback.getPacketID() == null)
                throw new MalformedMessageException("unsuback must contain packetID");
            buf.writeShort(unsuback.getPacketID());
            break;

        case DISCONNECT:
        case PINGREQ:
        case PINGRESP:
            buf.setByte(0, (byte) (type.getNum() << 4));
            break;

        default:
            throw new MalformedMessageException("Invalid header type: " + type);
        }

        return buf;
    } catch (UnsupportedEncodingException e) {
        throw new MalformedMessageException("unsupported string encoding:" + e.getMessage());
    }
}