Example usage for io.netty.buffer ByteBuf getUnsignedByte

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

Introduction

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

Prototype

public abstract short getUnsignedByte(int index);

Source Link

Document

Gets an unsigned byte at the specified absolute index in this buffer.

Usage

From source file:org.eclipse.scada.protocol.iec60870.asdu.types.InformationObjectAddress.java

License:Open Source License

@Override
public String toString() {
    final ByteBuf buf = Unpooled.buffer(4);
    buf.writeMedium(this.address);
    return String.format("[%d-%d-%d # %d]", buf.getUnsignedByte(0), buf.getUnsignedByte(1),
            buf.getUnsignedByte(2), this.address);
}

From source file:org.graylog.plugins.netflow.flows.NetFlowV5.java

License:Apache License

/**
 * Parse a Version 5 Flow/*  w  w  w .ja va 2s .c o m*/
 *
 * @param sender           The sender's InetSocketAddress
 * @param buf              Netty ByteBuf Slice containing the UDP Packet
 * @param fpId             FlowPacket-UUID this Flow arrived on
 * @param uptime           Millis since UNIX Epoch when the exporting device/sender booted
 * @param timestamp        DateTime when this flow was exported
 * @param samplingInterval Interval samples are sent
 * @param calculateSamples Switch to turn on/off samples calculation
 */
public static NetFlow parse(final InetSocketAddress sender, final ByteBuf buf, final UUID fpId,
        final long uptime, final DateTime timestamp, final int samplingInterval,
        final boolean calculateSamples) {

    final long pkts = getUnsignedInteger(buf, 16, 4);
    final long bytes = getUnsignedInteger(buf, 20, 4);

    final int srcPort = (int) getUnsignedInteger(buf, 32, 2);
    final int dstPort = (int) getUnsignedInteger(buf, 34, 2);
    final int srcAS = (int) getUnsignedInteger(buf, 40, 2);
    final int dstAS = (int) getUnsignedInteger(buf, 42, 2);
    final int proto = buf.getUnsignedByte(38);
    final int tos = buf.getUnsignedByte(39);
    final int tcpflags = buf.getUnsignedByte(37);
    final long start = getUnsignedInteger(buf, 24, 4);
    final long stop = getUnsignedInteger(buf, 28, 4);
    final InetAddress srcAddress = getInetAddress(buf, 0, 4);
    final InetAddress dstAddress = getInetAddress(buf, 4, 4);
    final InetAddress nextHop = getInetAddress(buf, 8, 4);
    final int snmpInput = (int) getUnsignedInteger(buf, 12, 2);
    final int snmpOutput = (int) getUnsignedInteger(buf, 14, 2);
    final int srcMask = buf.getUnsignedByte(44);
    final int dstMask = buf.getUnsignedByte(45);

    return new NetFlowV5(UUIDs.timeBased(), sender, buf.readableBytes(), uptime, timestamp, srcPort, dstPort,
            srcAS != -1 ? Optional.of(srcAS) : Optional.<Integer>absent(),
            dstAS != -1 ? Optional.of(dstAS) : Optional.<Integer>absent(),
            calculateSamples ? pkts * samplingInterval : pkts, // pkts
            calculateSamples ? bytes * samplingInterval : bytes, // bytes
            proto, tos, tcpflags,
            start != 0 ? Optional.of(timestamp.minus(uptime - start)) : Optional.<DateTime>absent(), // start
            stop != 0 ? Optional.of(timestamp.minus(uptime - stop)) : Optional.<DateTime>absent(), // stop
            srcAddress, dstAddress,
            ByteBufUtils.DEFAULT_INET_ADDRESS.equals(nextHop) ? Optional.<InetAddress>absent()
                    : Optional.of(nextHop), // nextHop
            snmpInput, snmpOutput, srcMask, dstMask, fpId);
}

From source file:org.graylog.plugins.netflow.utils.ByteBufUtils.java

License:Apache License

public static long getUnsignedInteger(final ByteBuf buf, final int offset, final int length) {
    switch (length) {
    case 1:/*from   w  w  w  . ja va  2  s  . c o  m*/
        return buf.getUnsignedByte(offset);
    case 2:
        return buf.getUnsignedShort(offset);
    case 3:
        return buf.getUnsignedMedium(offset);
    case 4:
        return buf.getUnsignedInt(offset);
    case 8:
        return buf.getLong(offset) & 0x00000000ffffffffL;
    default:
        return 0L;
    }
}

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   w w w. ja  v a  2 s . c  o  m
        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();

        }
    }

}

From source file:org.helios.octo.util.NettyUtil.java

License:Open Source License

public static String formatBuffer(ByteBuf buf) {
    int length = buf.readableBytes();
    int rows = length / 16 + (length % 15 == 0 ? 0 : 1) + 4;
    StringBuilder dump = new StringBuilder(rows * 80);

    dump.append(NEWLINE + "         +-------------------------------------------------+" + NEWLINE
            + "         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |" + NEWLINE
            + "+--------+-------------------------------------------------+----------------+");

    final int startIndex = buf.readerIndex();
    final int endIndex = buf.writerIndex();

    int i;//from   w  w w .  j a v  a2s .  co m
    for (i = startIndex; i < endIndex; i++) {
        int relIdx = i - startIndex;
        int relIdxMod16 = relIdx & 15;
        if (relIdxMod16 == 0) {
            dump.append(NEWLINE);
            dump.append(Long.toHexString(relIdx & 0xFFFFFFFFL | 0x100000000L));
            dump.setCharAt(dump.length() - 9, '|');
            dump.append('|');
        }
        dump.append(BYTE2HEX[buf.getUnsignedByte(i)]);
        if (relIdxMod16 == 15) {
            dump.append(" |");
            for (int j = i - 15; j <= i; j++) {
                dump.append(BYTE2CHAR[buf.getUnsignedByte(j)]);
            }
            dump.append('|');
        }
    }

    if ((i - startIndex & 15) != 0) {
        int remainder = length & 15;
        dump.append(HEXPADDING[remainder]);
        dump.append(" |");
        for (int j = i - remainder; j < i; j++) {
            dump.append(BYTE2CHAR[buf.getUnsignedByte(j)]);
        }
        dump.append(BYTEPADDING[remainder]);
        dump.append('|');
    }

    dump.append(NEWLINE + "+--------+-------------------------------------------------+----------------+");

    return dump.toString();
}

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

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (!in.isReadable()) {
        return;//from  ww  w  .  j  ava2s . co  m
    }

    FrameDecoder decoder;
    switch (state) {
    case NEXT:
        serverEvent = ServerEvent.valueOf(in.getUnsignedByte(0));
        decoder = frameDecoder.get(serverEvent);

        if (decoder == null) {
            logger.error("not handled server message type: {} ({})", serverEvent, in.getUnsignedByte(0));
            in.skipBytes(in.readableBytes());
            return;
        }
        if (!decoder.decode(ctx, in, out)) {
            state = State.FRAME;
        }
    case FRAME:
        decoder = frameDecoder.get(serverEvent);

        if (decoder == null) {
            logger.error("not handled server message type: {} ({})", serverEvent, in.getUnsignedByte(0));
            in.skipBytes(in.readableBytes());
            return;
        }
        if (decoder.decode(ctx, in, out)) {
            state = State.NEXT;
        }
        break;
    default:
        logger.warn("unknown state: {}", state);
        break;
    }
}

From source file:org.neo4j.bolt.transport.TransportSelectionHandler.java

License:Open Source License

private boolean isHttp(ByteBuf buf) {
    for (int i = 0; i < WEBSOCKET_MAGIC.length(); ++i) {
        if (buf.getUnsignedByte(buf.readerIndex() + i) != WEBSOCKET_MAGIC.charAt(i)) {
            return false;
        }/* w  w  w.  j ava 2 s.c o  m*/
    }
    return true;
}

From source file:org.onosproject.lisp.msg.protocols.LispMessageReaderFactory.java

License:Apache License

/**
 * Obtains corresponding LISP message reader.
 *
 * @param buffer netty byte buffer//from  ww  w .  ja v a  2s. c  o  m
 * @return LISP message reader
 */
public static LispMessageReader getReader(ByteBuf buffer) {
    LispMessageReader reader;

    LispType type = LispType.valueOf((short) (buffer.getUnsignedByte(0) >> TYPE_SHIFT_BIT));

    switch (type) {
    case LISP_MAP_REQUEST:
        reader = new RequestReader();
        break;
    case LISP_MAP_REPLY:
        reader = new ReplyReader();
        break;
    case LISP_MAP_REGISTER:
        reader = new RegisterReader();
        break;
    case LISP_MAP_NOTIFY:
        reader = new NotifyReader();
        break;
    case LISP_INFO:
        boolean isInfoReply = ByteOperator.getBit((byte) buffer.getUnsignedByte(0), INFO_REPLY_INDEX);
        if (isInfoReply) {
            reader = new InfoReplyReader();
        } else {
            reader = new InfoRequestReader();
        }
        break;
    case LISP_ENCAPSULATED_CONTROL:
        reader = new EcmReader();
        break;
    case UNKNOWN:
        throw new IllegalArgumentException("Unknown message type: " + type);
    default:
        throw new IllegalArgumentException("Undefined message type: " + type);
    }
    return reader;
}

From source file:org.opendaylight.openflowjava.protocol.impl.deserialization.action.OF13SetFieldActionDeserializer.java

License:Open Source License

@Override
public Action deserialize(ByteBuf input) {
    org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.action.rev150203.actions.grouping.ActionBuilder builder = new ActionBuilder();
    int startIndex = input.readerIndex();
    input.skipBytes(2 * EncodeConstants.SIZE_OF_SHORT_IN_BYTES);
    SetFieldCaseBuilder caseBuilder = new SetFieldCaseBuilder();
    SetFieldActionBuilder actionBuilder = new SetFieldActionBuilder();
    int oxmClass = input.getUnsignedShort(input.readerIndex());
    // get oxm_field & hasMask byte and extract the field value
    int oxmField = input.getUnsignedByte(input.readerIndex() + EncodeConstants.SIZE_OF_SHORT_IN_BYTES) >>> 1;
    MatchEntryDeserializerKey key = new MatchEntryDeserializerKey(EncodeConstants.OF13_VERSION_ID, oxmClass,
            oxmField);/*from w w w  . j  ava  2s. com*/
    if (oxmClass == EncodeConstants.EXPERIMENTER_VALUE) {
        long expId = input.getUnsignedInt(input.readerIndex() + EncodeConstants.SIZE_OF_SHORT_IN_BYTES
                + 2 * EncodeConstants.SIZE_OF_BYTE_IN_BYTES);
        key.setExperimenterId(expId);
    }
    OFDeserializer<MatchEntry> matchDeserializer = registry.getDeserializer(key);
    List<MatchEntry> entry = new ArrayList<>();
    entry.add(matchDeserializer.deserialize(input));
    actionBuilder.setMatchEntry(entry);
    caseBuilder.setSetFieldAction(actionBuilder.build());
    builder.setActionChoice(caseBuilder.build());
    int paddingRemainder = (input.readerIndex() - startIndex) % EncodeConstants.PADDING;
    if (paddingRemainder != 0) {
        input.skipBytes(EncodeConstants.PADDING - paddingRemainder);
    }
    return builder.build();
}

From source file:org.opendaylight.openflowjava.protocol.impl.util.ByteBufUtils.java

License:Open Source License

/**
 * Converts ByteBuf into String/*  w w  w.  j  a v a  2 s  .  c om*/
 * @param bb input ByteBuf
 * @return String
 */
public static String byteBufToHexString(ByteBuf bb) {
    StringBuffer sb = new StringBuffer();
    for (int i = bb.readerIndex(); i < (bb.readerIndex() + bb.readableBytes()); i++) {
        sb.append(String.format(" %02x", bb.getUnsignedByte(i)));
    }
    return sb.toString().trim();
}