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:org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientMessageHandler.java

License:Open Source License

private boolean accumulateChunk(ByteBuf buffer) throws UaException {
    int chunkSize = buffer.readerIndex(0).readableBytes();

    if (chunkSize > maxChunkSize) {
        throw new UaException(StatusCodes.Bad_TcpMessageTooLarge,
                String.format("max chunk size exceeded (%s)", maxChunkSize));
    }//from  w ww.j  a v  a2  s  .  co  m

    chunkBuffers.add(buffer.retain());

    if (maxChunkCount > 0 && chunkBuffers.size() > maxChunkCount) {
        throw new UaException(StatusCodes.Bad_TcpMessageTooLarge,
                String.format("max chunk count exceeded (%s)", maxChunkCount));
    }

    char chunkType = (char) buffer.getByte(3);

    return (chunkType == 'A' || chunkType == 'F');
}

From source file:org.eclipse.neoscada.protocol.iec60870.apci.APDUDecoder.java

License:Open Source License

@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out)
        throws Exception {
    if (logger.isTraceEnabled()) {
        logger.trace("decode - bytes: {}", ByteBufUtil.hexDump(in));
    }/* ww  w .  java 2s.c o  m*/

    if (in.readableBytes() < Constants.APCI_MIN_LENGTH) {
        return;
    }

    final byte start = in.getByte(in.readerIndex() + 0);
    if (start != Constants.START_BYTE) {
        throw new DecoderException(
                String.format("ACPI must start with 0x%02x but did with 0x%02x", Constants.START_BYTE, start));
    }

    final short len = in.getUnsignedByte(in.readerIndex() + 1);

    if (len > Constants.APCI_MAX_DATA_LENGTH) {
        throw new DecoderException(String.format("APCI has a maximum length of %s bytes, but we received %s",
                Constants.APCI_MAX_DATA_LENGTH, len));
    }

    if (in.readableBytes() < len + 2) {
        return;
    }

    // we have the full InformationTransfer

    // skip start & len
    in.skipBytes(2);

    // read control fields
    final ByteBuf controlFields = in.readSlice(4);

    final ByteBuf data;
    if (len > 4) {
        data = Unpooled.copiedBuffer(in.readSlice(len - 4)).order(ByteOrder.LITTLE_ENDIAN);
    } else {
        data = null;
    }

    // now add the PDU

    out.add(decode(controlFields, data));
}

From source file:org.eclipse.neoscada.protocol.iec60870.apci.APDUDecoder.java

License:Open Source License

private APCIBase decode(ByteBuf controlFields, final ByteBuf data) {
    logger.trace("Control Fields: {}", ByteBufUtil.hexDump(controlFields));

    controlFields = controlFields.order(ByteOrder.LITTLE_ENDIAN);

    final byte first = controlFields.getByte(0);
    if ((first & 0x01) == 0) {
        // I format
        final int sendSequenceNumber = controlFields.readUnsignedShort() >> 1;
        final int receiveSequenceNumber = controlFields.readUnsignedShort() >> 1;
        logger.debug("S: {}, R: {}", sendSequenceNumber, receiveSequenceNumber);
        return new InformationTransfer(sendSequenceNumber, receiveSequenceNumber, data);
    } else if ((first & 0x03) == 1) {
        // S format
        controlFields.skipBytes(2);/*w ww. j a v a 2  s  .c om*/
        final int receiveSequenceNumber = controlFields.readUnsignedShort() >> 1;
        return new Supervisory(receiveSequenceNumber);
    } else if ((first & 0x03) == 3) {
        // U format
        final Function function = convertFunction(controlFields.readUnsignedByte());
        return new UnnumberedControl(function);
    }

    // this should actually never happen

    throw new DecoderException("Invalid control fields");
}

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

License:Apache License

public void testBytesAreUsed() {
    byte[] bytes1 = new byte[10];
    byte[] bytes2 = new byte[10];

    for (int i = 0; i < 10; ++i) {
        bytes1[i] = (byte) i;
    }/*from   w w  w.ja  v a  2 s .com*/

    for (int i = 10; i < 20; ++i) {
        bytes2[i - 10] = (byte) i;
    }

    InboundChannelBuffer.Page[] pages = new InboundChannelBuffer.Page[2];
    pages[0] = new InboundChannelBuffer.Page(ByteBuffer.wrap(bytes1), () -> {
    });
    pages[1] = new InboundChannelBuffer.Page(ByteBuffer.wrap(bytes2), () -> {
    });

    ByteBuf byteBuf = PagedByteBuf.byteBufFromPages(pages);
    assertEquals(20, byteBuf.readableBytes());

    for (int i = 0; i < 20; ++i) {
        assertEquals((byte) i, byteBuf.getByte(i));
    }

    InboundChannelBuffer.Page[] pages2 = new InboundChannelBuffer.Page[2];
    ByteBuffer firstBuffer = ByteBuffer.wrap(bytes1);
    firstBuffer.position(2);
    ByteBuffer secondBuffer = ByteBuffer.wrap(bytes2);
    secondBuffer.limit(8);
    pages2[0] = new InboundChannelBuffer.Page(firstBuffer, () -> {
    });
    pages2[1] = new InboundChannelBuffer.Page(secondBuffer, () -> {
    });

    ByteBuf byteBuf2 = PagedByteBuf.byteBufFromPages(pages2);
    assertEquals(16, byteBuf2.readableBytes());

    for (int i = 2; i < 18; ++i) {
        assertEquals((byte) i, byteBuf2.getByte(i - 2));
    }
}

From source file:org.elasticsearch.transport.netty4.ESLoggingHandler.java

License:Apache License

private String format(final ChannelHandlerContext ctx, final String eventName, final ByteBuf arg)
        throws IOException {
    final int readableBytes = arg.readableBytes();
    if (readableBytes == 0) {
        return super.format(ctx, eventName, arg);
    } else if (readableBytes >= 2) {
        final StringBuilder sb = new StringBuilder();
        sb.append(ctx.channel().toString());
        final int offset = arg.readerIndex();
        // this might be an ES message, check the header
        if (arg.getByte(offset) == (byte) 'E' && arg.getByte(offset + 1) == (byte) 'S') {
            if (readableBytes == TcpHeader.MARKER_BYTES_SIZE + TcpHeader.MESSAGE_LENGTH_SIZE) {
                final int length = arg.getInt(offset + MESSAGE_LENGTH_OFFSET);
                if (length == TcpTransport.PING_DATA_SIZE) {
                    sb.append(" [ping]").append(' ').append(eventName).append(": ").append(readableBytes)
                            .append('B');
                    return sb.toString();
                }// w w  w . j av  a  2s  . c  om
            } else if (readableBytes >= TcpHeader.HEADER_SIZE) {
                // we are going to try to decode this as an ES message
                final int length = arg.getInt(offset + MESSAGE_LENGTH_OFFSET);
                final long requestId = arg.getLong(offset + REQUEST_ID_OFFSET);
                final byte status = arg.getByte(offset + STATUS_OFFSET);
                final boolean isRequest = TransportStatus.isRequest(status);
                final String type = isRequest ? "request" : "response";
                final String version = Version.fromId(arg.getInt(offset + VERSION_ID_OFFSET)).toString();
                sb.append(" [length: ").append(length);
                sb.append(", request id: ").append(requestId);
                sb.append(", type: ").append(type);
                sb.append(", version: ").append(version);
                if (isRequest) {
                    // it looks like an ES request, try to decode the action
                    final int remaining = readableBytes - ACTION_OFFSET;
                    final ByteBuf slice = arg.slice(offset + ACTION_OFFSET, remaining);
                    // the stream might be compressed
                    try (StreamInput in = in(status, slice, remaining)) {
                        // the first bytes in the message is the context headers
                        try (ThreadContext context = new ThreadContext(Settings.EMPTY)) {
                            context.readHeaders(in);
                        }
                        // now we can decode the action name
                        sb.append(", action: ").append(in.readString());
                    }
                }
                sb.append(']');
                sb.append(' ').append(eventName).append(": ").append(readableBytes).append('B');
                return sb.toString();
            }
        }
    }
    // we could not decode this as an ES message, use the default formatting
    return super.format(ctx, eventName, arg);
}

From source file:org.graylog2.inputs.syslog.tcp.SyslogTCPFramingRouterHandler.java

License:Open Source License

private boolean usesOctetCountFraming(ByteBuf message) {
    // Octet counting framing needs to start with a non-zero digit.
    // See: http://tools.ietf.org/html/rfc6587#section-3.4.1
    final byte firstByte = message.getByte(0);
    return '0' < firstByte && firstByte <= '9';
}

From source file:org.graylog2.inputs.transports.netty.LenientDelimiterBasedFrameDecoder.java

License:Open Source License

/**
 * Returns true if the delimiters are "\n" and "\r\n".
 *//*  ww  w  . ja v a  2 s . co  m*/
private static boolean isLineBased(final ByteBuf[] delimiters) {
    if (delimiters.length != 2) {
        return false;
    }
    ByteBuf a = delimiters[0];
    ByteBuf b = delimiters[1];
    if (a.capacity() < b.capacity()) {
        a = delimiters[1];
        b = delimiters[0];
    }
    return a.capacity() == 2 && b.capacity() == 1 && a.getByte(0) == '\r' && a.getByte(1) == '\n'
            && b.getByte(0) == '\n';
}

From source file:org.graylog2.inputs.transports.netty.LenientLineBasedFrameDecoder.java

License:Open Source License

/**
 * Create a frame out of the {@link ByteBuf} and return it.
 *
 * @param ctx    the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
 * @param buffer the {@link ByteBuf} from which to read data
 * @return frame           the {@link ByteBuf} which represent the frame or {@code null} if no frame could
 * be created.//from  w ww. ja v a 2 s .c o  m
 */
protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
    final int eol = findEndOfLine(buffer);
    if (!discarding) {
        if (eol < 0 && emitLastLineWithoutDelimiter && !ctx.channel().isActive()) {
            final ByteBuf frame;
            final int length = buffer.readableBytes();

            if (length > maxLength) {
                buffer.readerIndex(length);
                fail(ctx, length);
                return null;
            }

            frame = buffer.readRetainedSlice(length);

            return frame;
        } else if (eol >= 0) {
            final ByteBuf frame;
            final int length = eol - buffer.readerIndex();
            final int delimLength = buffer.getByte(eol) == '\r' ? 2 : 1;

            if (length > maxLength) {
                buffer.readerIndex(eol + delimLength);
                fail(ctx, length);
                return null;
            }

            if (stripDelimiter) {
                frame = buffer.readRetainedSlice(length);
                buffer.skipBytes(delimLength);
            } else {
                frame = buffer.readRetainedSlice(length + delimLength);
            }

            return frame;
        } else {
            final int length = buffer.readableBytes();
            if (length > maxLength) {
                discardedBytes = length;
                buffer.readerIndex(buffer.writerIndex());
                discarding = true;
                offset = 0;
                if (failFast) {
                    fail(ctx, "over " + discardedBytes);
                }
            }
            return null;
        }
    } else {
        if (eol >= 0) {
            final int length = discardedBytes + eol - buffer.readerIndex();
            final int delimLength = buffer.getByte(eol) == '\r' ? 2 : 1;
            buffer.readerIndex(eol + delimLength);
            discardedBytes = 0;
            discarding = false;
            if (!failFast) {
                fail(ctx, length);
            }
        } else {
            discardedBytes += buffer.readableBytes();
            buffer.readerIndex(buffer.writerIndex());
        }
        return null;
    }
}

From source file:org.graylog2.inputs.transports.netty.LenientLineBasedFrameDecoder.java

License:Open Source License

/**
 * Returns the index in the buffer of the end of line found.
 * Returns -1 if no end of line was found in the buffer.
 */// w w  w. j av a 2 s.co  m
private int findEndOfLine(final ByteBuf buffer) {
    int totalLength = buffer.readableBytes();
    int i = buffer.forEachByte(buffer.readerIndex() + offset, totalLength - offset, ByteProcessor.FIND_LF);
    if (i >= 0) {
        offset = 0;
        if (i > 0 && buffer.getByte(i - 1) == '\r') {
            i--;
        }
    } else {
        offset = totalLength;
    }
    return i;
}

From source file:org.hawkular.metrics.clients.ptrans.ganglia.UdpGangliaDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket in, List<Object> out) throws Exception {
    ByteBuf msg = in.content();
    if (msg.readableBytes() < 5) {
        msg.clear();//from   ww w  . j av  a2 s  . c om
        ctx.close();
        return;
    }

    short magic = msg.getUnsignedByte(3);
    if (msg.getByte(0) == 0 && msg.getByte(1) == 0 && msg.getByte(2) == 0 && magic == 134) {

        // We have an UnsafeSuperDuperBuffer, so we need to "manually" pull the bytes from it.
        byte[] bytes = new byte[msg.readableBytes()];
        msg.readBytes(bytes);

        XdrBufferDecodingStream stream = new XdrBufferDecodingStream(bytes);
        stream.beginDecoding();
        stream.xdrDecodeInt(); // Packet id , should be 134 as in above magic => type of value
        String host = stream.xdrDecodeString();
        String metricName = stream.xdrDecodeString();
        stream.xdrDecodeInt();
        String format = stream.xdrDecodeString(); // e.g. .0f for a number
        String value;
        if (format.endsWith("f")) {
            value = String.valueOf(stream.xdrDecodeFloat());
        } else {
            value = stream.xdrDecodeString();
        }
        stream.endDecoding();

        try {
            String path = host + "." + metricName;
            Double val = Double.parseDouble(value);

            SingleMetric metric = new SingleMetric(path, System.currentTimeMillis(), val);
            out.add(metric);
        } catch (Exception e) {
            e.printStackTrace();
            msg.clear();
            ctx.close();

        }
    }

}