Example usage for io.netty.buffer ByteBuf getByte

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

Introduction

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

Prototype

public abstract byte getByte(int index);

Source Link

Document

Gets a byte at the specified absolute index in this buffer.

Usage

From source file:io.codis.nedis.handler.RedisResponseDecoder.java

License:Apache License

private boolean decode(ByteBuf in, List<Object> out, Object nullValue) throws Exception {
    if (in.readableBytes() < 2) {
        return false;
    }// w  ww .j a  v  a  2 s .c  om
    byte b = in.readByte();
    switch (b) {
    case '+': {
        String reply = decodeString(in);
        if (reply == null) {
            return false;
        }
        out.add(reply);
        return true;
    }
    case '-': {
        String reply = decodeString(in);
        if (reply == null) {
            return false;
        }
        out.add(new RedisResponseException(reply));
        return true;
    }
    case ':': {
        Long reply = decodeLong(in);
        if (reply == null) {
            return false;
        }
        out.add(reply);
        return true;
    }
    case '$': {
        Long numBytes = decodeLong(in);
        if (numBytes == null) {
            return false;
        }
        if (numBytes.intValue() == -1) {
            out.add(nullValue);
            return true;
        }
        if (in.readableBytes() < numBytes.intValue() + 2) {
            return false;
        }
        if (in.getByte(in.readerIndex() + numBytes.intValue()) != '\r'
                || in.getByte(in.readerIndex() + numBytes.intValue() + 1) != '\n') {
            throw new ProtocolException("Response is not ended by CRLF");
        }
        byte[] reply = new byte[numBytes.intValue()];
        in.readBytes(reply);
        // skip CRLF
        in.skipBytes(2);
        out.add(reply);
        return true;
    }
    case '*': {
        Long numReplies = decodeLong(in);
        if (numReplies == null) {
            return false;
        }
        if (numReplies.intValue() == -1) {
            out.add(nullValue);
            return true;
        }
        List<Object> replies = new ArrayList<>();
        for (int i = 0; i < numReplies.intValue(); i++) {
            if (!decode(in, replies, null)) {
                return false;
            }
        }
        out.add(replies);
        return true;
    }
    default:
        throw new ProtocolException("Unknown leading char: " + (char) b);
    }
}

From source file:io.datty.msgpack.core.AbstractMessageReader.java

License:Apache License

public MessageFormat getNextFormat(ByteBuf buffer) {
    return MessageFormat.valueOf(buffer.getByte(buffer.readerIndex()));
}

From source file:io.datty.msgpack.core.AbstractMessageReader.java

License:Apache License

public byte getNextCode(ByteBuf buffer) {
    return buffer.getByte(buffer.readerIndex());
}

From source file:io.grapebaba.vineyard.grape.codec.GrapeCodec.java

License:Apache License

@Override
public GrapeMessage decode(ByteBuf byteBuf) {
    final int messageTypePosition = 0;
    MessageType messageType = valueOf(byteBuf.getByte(messageTypePosition));
    switch (messageType) {
    case REQUEST:
        return new RequestMessageCodec().decode(byteBuf);
    case RESPONSE:
        return new ResponseMessageCodec().decode(byteBuf);
    case HEARTBEAT_REQUEST:
        return new HeartbeatRequestMessage();
    case HEARTBEAT_RESPONSE:
        return new HeartbeatResponseMessage();
    default://  w  w w  .  java2 s . c  o  m
        throw new RuntimeException("Cannot decode message by GrapeCodec");
    }
}

From source file:io.grpc.alts.internal.TsiTest.java

License:Apache License

/** Test corrupted ciphertext. */
public static void corruptedCiphertextTest(Handshakers handshakers, RegisterRef ref)
        throws GeneralSecurityException {
    performHandshake(DEFAULT_TRANSPORT_BUFFER_SIZE, handshakers);

    TsiFrameProtector sender = handshakers.getClient().createFrameProtector(alloc);
    TsiFrameProtector receiver = handshakers.getServer().createFrameProtector(alloc);

    String message = "hello world";
    ByteBuf plaintextBuffer = Unpooled.wrappedBuffer(message.getBytes(UTF_8));
    final List<ByteBuf> protectOut = new ArrayList<>();
    List<Object> unprotectOut = new ArrayList<>();

    sender.protectFlush(Collections.singletonList(plaintextBuffer), new Consumer<ByteBuf>() {
        @Override/*from   ww w .j  a v  a 2  s.  co m*/
        public void accept(ByteBuf buf) {
            protectOut.add(buf);
        }
    }, alloc);
    assertThat(protectOut.size()).isEqualTo(1);

    ByteBuf protect = ref.register(protectOut.get(0));
    int ciphertextIdx = protect.writerIndex() - FakeChannelCrypter.getTagBytes() - 2;
    protect.setByte(ciphertextIdx, protect.getByte(ciphertextIdx) + 1);

    try {
        receiver.unprotect(protect, unprotectOut, alloc);
        fail("Exception expected");
    } catch (AEADBadTagException ex) {
        assertThat(ex).hasMessageThat().contains(DECRYPTION_FAILURE_RE);
    }

    sender.destroy();
    receiver.destroy();
}

From source file:io.grpc.alts.internal.TsiTest.java

License:Apache License

/** Test corrupted tag. */
public static void corruptedTagTest(Handshakers handshakers, RegisterRef ref) throws GeneralSecurityException {
    performHandshake(DEFAULT_TRANSPORT_BUFFER_SIZE, handshakers);

    TsiFrameProtector sender = handshakers.getClient().createFrameProtector(alloc);
    TsiFrameProtector receiver = handshakers.getServer().createFrameProtector(alloc);

    String message = "hello world";
    ByteBuf plaintextBuffer = Unpooled.wrappedBuffer(message.getBytes(UTF_8));
    final List<ByteBuf> protectOut = new ArrayList<>();
    List<Object> unprotectOut = new ArrayList<>();

    sender.protectFlush(Collections.singletonList(plaintextBuffer), new Consumer<ByteBuf>() {
        @Override//from w w w.  j a va2 s . c o  m
        public void accept(ByteBuf buf) {
            protectOut.add(buf);
        }
    }, alloc);
    assertThat(protectOut.size()).isEqualTo(1);

    ByteBuf protect = ref.register(protectOut.get(0));
    int tagIdx = protect.writerIndex() - 1;
    protect.setByte(tagIdx, protect.getByte(tagIdx) + 1);

    try {
        receiver.unprotect(protect, unprotectOut, alloc);
        fail("Exception expected");
    } catch (AEADBadTagException ex) {
        assertThat(ex).hasMessageThat().contains(DECRYPTION_FAILURE_RE);
    }

    sender.destroy();
    receiver.destroy();
}

From source file:io.grpc.netty.GrpcHpackDecoder.java

License:Apache License

/**
 * Unsigned Little Endian Base 128 Variable-Length Integer Encoding
 * <p>// w  w  w .j a v  a  2 s . c  o m
 * Visible for testing only!
 */
static long decodeULE128(ByteBuf in, long result) throws Http2Exception {
    assert result <= 0x7f && result >= 0;
    final boolean resultStartedAtZero = result == 0;
    final int writerIndex = in.writerIndex();
    for (int readerIndex = in.readerIndex(), shift = 0; readerIndex < writerIndex; ++readerIndex, shift += 7) {
        byte b = in.getByte(readerIndex);
        if (shift == 56 && (((b & 0x80) != 0 || b == 0x7F) && !resultStartedAtZero)) {
            // the maximum value that can be represented by a signed 64 bit number is:
            // [0x01L, 0x7fL] + 0x7fL + (0x7fL << 7) + (0x7fL << 14) + (0x7fL << 21) + (0x7fL << 28) + (0x7fL << 35)
            // + (0x7fL << 42) + (0x7fL << 49) + (0x7eL << 56)
            // OR
            // 0x0L + 0x7fL + (0x7fL << 7) + (0x7fL << 14) + (0x7fL << 21) + (0x7fL << 28) + (0x7fL << 35) +
            // (0x7fL << 42) + (0x7fL << 49) + (0x7fL << 56)
            // this means any more shifts will result in overflow so we should break out and throw an error.
            throw DECODE_ULE_128_TO_LONG_DECOMPRESSION_EXCEPTION;
        }

        if ((b & 0x80) == 0) {
            in.readerIndex(readerIndex + 1);
            return result + ((b & 0x7FL) << shift);
        }
        result += (b & 0x7FL) << shift;
    }

    throw DECODE_ULE_128_DECOMPRESSION_EXCEPTION;
}

From source file:io.lettuce.core.protocol.RedisStateMachine.java

License:Apache License

private int findLineEnd(ByteBuf buffer) {

    int index = buffer.forEachByte(ByteProcessor.FIND_LF);
    return (index > 0 && buffer.getByte(index - 1) == '\r') ? index : -1;
}

From source file:io.netlibs.bgp.netty.codec.UpdatePacketDecoder.java

License:Apache License

private ExtendedCommunityPathAttribute decodeExtendedCommunityPathAttribute(final ByteBuf buffer) {
    final ExtendedCommunityPathAttribute attr = new ExtendedCommunityPathAttribute();

    if ((buffer.readableBytes() < 8) || ((buffer.readableBytes() % 8) != 0)) {
        throw new OptionalAttributeErrorException();
    }//from   www.j a  va 2s .  co m

    while (buffer.isReadable()) {
        AbstractExtendedCommunityInterface extcomm;
        // we need to check whether this is a transitive or non-transitive value
        // and then determine whether we need to red the lower type byte
        byte higherType = buffer.readByte();
        byte higherTypeCompare = (byte) (higherType & ~(1 << 6));
        if (((higherType >> 6) & 1) == 0) {
            // bit 7 is not set in the byte, therefore this is a transitive type
            // clear bit 8, not interested in this value
            TransitiveExtendedCommunityType transCommType = TransitiveExtendedCommunityType
                    .fromCode((byte) (higherType & (~(3 << 6))));

            switch (transCommType) {
            case TWO_OCTET_AS_SPECIFIC:
                TransitiveTwoOctetASSpecificExtCommSubTypes twoOctASNLowerType = TransitiveTwoOctetASSpecificExtCommSubTypes
                        .fromCode(buffer.readByte());
                switch (twoOctASNLowerType) {
                case ROUTE_TARGET:
                    extcomm = new TransitiveTwoByteASNFourByteAdministratorRT((int) buffer.readShort(),
                            (long) buffer.readInt());
                    break;
                default:
                    // all non-RT types are currently unimplemented
                    extcomm = new UnknownTransitiveTwoByteASNSpecificExtendedCommunity(transCommType,
                            twoOctASNLowerType, buffer.readBytes(6).array());
                }
                break;

            case TWO_OCTET_IPv4_ADDRESS_SPECIFIC:

                TransitiveIPv4AddressSpecificExtCommSubTypes ipv4LowerType = TransitiveIPv4AddressSpecificExtCommSubTypes
                        .fromCode(buffer.readByte());

                switch (ipv4LowerType) {
                case ROUTE_TARGET:
                    try {
                        extcomm = new TransitiveIPv4AddressTwoByteAdministratorRT(
                                (Inet4Address) InetAddresses
                                        .fromLittleEndianByteArray(buffer.readBytes(4).array()),
                                (int) buffer.readShort());
                    } catch (UnknownHostException e) {
                        ByteBuf data = Unpooled.buffer();
                        data.getByte(ipv4LowerType.toCode());
                        data.readBytes(buffer.readBytes(6));
                        extcomm = new UnknownTransitiveExtendedCommunity(transCommType, data.array());
                    }
                    break;

                default:

                    // all non-RT types are currently unimplemented
                    extcomm = new UnknownTransitiveIPv4AddressSpecificExtendedCommunity(transCommType,
                            ipv4LowerType, buffer.readBytes(6).array());
                    break;

                }
                break;

            default:
                // by default, just create an unknown type, reading the subsequent
                // 7 bytes (we have already read byte 1)
                extcomm = new UnknownTransitiveExtendedCommunity(transCommType, buffer.readBytes(7).array());
            }
        } else {
            // bit 7 is set, these are non-transitive
            NonTransitiveExtendedCommunityType nonTransCommType = NonTransitiveExtendedCommunityType
                    .fromCode((byte) (higherType & (~(3 << 6))));
            // all non-transitive types are currently unimplemented
            extcomm = new UnknownNonTransitiveExtendedCommunity(nonTransCommType, buffer.readBytes(7).array());
        }
        attr.getMembers().add(extcomm);
    }
    return attr;
}

From source file:io.nodyn.http.HTTPParser.java

License:Apache License

protected boolean readVersion(ByteBuf versionBuf) {
    int dotLoc = versionBuf.indexOf(versionBuf.readerIndex(),
            versionBuf.readerIndex() + versionBuf.readableBytes(), (byte) '.');
    if (dotLoc < 0) {
        return false;
    }/*from   w w  w  . jav a 2 s.  c o  m*/

    char majorChar = (char) versionBuf.getByte(dotLoc - 1);
    char minorChar = (char) versionBuf.getByte(dotLoc + 1);
    try {
        this.versionMajor = Integer.parseInt("" + majorChar);
        this.versionMinor = Integer.parseInt("" + minorChar);
    } catch (NumberFormatException e) {
        return false;
    }
    return true;
}