Example usage for io.netty.buffer ByteBuf readShort

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

Introduction

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

Prototype

public abstract short readShort();

Source Link

Document

Gets a 16-bit short integer at the current readerIndex and increases the readerIndex by 2 in this buffer.

Usage

From source file:eu.matejkormuth.rpgdavid.starving.remote.netty.packets.CommandPacket.java

License:Open Source License

@Override
public void readFrom(ByteBuf fromBuffer) {
    short length = fromBuffer.readShort();
    byte[] array = new byte[length];
    fromBuffer.readBytes(array);/*from   www  . j av a 2  s .c  o  m*/
    this.command = new String(array, PROTOCOL_ENCODING);
}

From source file:eu.matejkormuth.rpgdavid.starving.remote.netty.packets.DisconnectPacket.java

License:Open Source License

@Override
public void readFrom(ByteBuf fromBuffer) {
    short length = fromBuffer.readShort();
    byte[] array = new byte[length];
    fromBuffer.readBytes(array);/*w ww  .  j  a  v  a 2s  . com*/
    this.reason = new String(array, PROTOCOL_ENCODING);
}

From source file:gedi.remote.codec.DefaultDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

    if (in.readableBytes() < Integer.BYTES)
        return;//w w  w  .  ja v  a  2 s . co m

    in.markReaderIndex();
    int size = in.readInt();

    if (in.readableBytes() < size) {
        in.resetReaderIndex();
        return;
    }

    // everything has arrived, decode
    char[] classname = new char[in.readInt()];
    for (int i = 0; i < classname.length; i++)
        classname[i] = (char) (in.readByte() & 255);

    String clsName = String.valueOf(classname);

    if (clsName.length() == 1) {

        switch (clsName) {
        case "A":
            char[] re = new char[in.readInt()];
            for (int i = 0; i < re.length; i++)
                re[i] = (char) (in.readByte() & 255);
            out.add(String.valueOf(re));
            break;
        case "B":
            out.add(in.readByte());
            break;
        case "S":
            out.add(in.readShort());
            break;
        case "I":
            out.add(in.readInt());
            break;
        case "L":
            out.add(in.readLong());
            break;
        case "F":
            out.add(in.readFloat());
            break;
        case "D":
            out.add(in.readDouble());
            break;
        }

    } else {

        if (!ClassPathCache.getInstance().existsClass(clsName)) {
            in.resetReaderIndex();
            return;
        }

        Class<?> cls = Class.forName(clsName);
        BinarySerializable re = (BinarySerializable) cls.newInstance();

        BinaryBlob buff = new BinaryBlob(size - Integer.BYTES - classname.length);
        in.readBytes(buff.getBuffer());
        buff.getBuffer().flip();

        re.deserialize(buff);

        out.add(re);
    }
}

From source file:gwlpr.protocol.NettyGWCodec.java

License:Open Source License

@Override
public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> result) {
    ByteBuf buf = in.order(ByteOrder.LITTLE_ENDIAN);

    while (buf.isReadable()) {
        buf.markReaderIndex();//  www  .  ja v  a 2s  .c  o m

        // get the header failsafe
        int header = buf.readableBytes() >= 2 ? buf.readShort() : -1;

        // failcheck
        if (header == -1) {
            return;
        }

        // try get the message class
        Class<? extends GWMessage> messageClazz = getByHeader(header);

        // failcheck
        if (messageClazz == null) {
            buf.resetReaderIndex();
            return;
        }

        // try retrieve the serialization filter
        NettySerializationFilter filter = GWMessageSerializationRegistry.getFilter(messageClazz);

        // failcheck
        if (filter == null) {
            buf.resetReaderIndex();
            return;
        }

        // try create the message
        Message message;
        try {
            message = messageClazz.newInstance();
        } catch (InstantiationException | IllegalAccessException ex) {
            LOGGER.error("Could not create an instance of an message.", ex);

            buf.resetReaderIndex();
            return;
        }

        // dont forget to initialize the message
        message.init(ctx.channel());

        // try serialize the message
        if (!filter.deserialize(buf, message)) {
            buf.resetReaderIndex();
            return;
        }

        // finally add the message
        result.add(message);

        LOGGER.debug("Got: {}", message.toString());
    }
}

From source file:hellfirepvp.astralsorcery.common.network.packet.server.PktSyncConfig.java

License:Open Source License

@Override
public void fromBytes(ByteBuf buf) {
    int count = buf.readByte();
    fields = new ArrayList<>(count);
    for (int i = 0; i < count; i++) {
        fields.add(new SyncTuple(null, null)); //Empty init
    }/*  w ww  .  j a v  a  2 s .  c om*/

    for (int i = 0; i < count; i++) {
        byte[] data = new byte[buf.readShort()];
        buf.readBytes(data);

        ByteArrayInputStream in = new ByteArrayInputStream(data);
        SyncTuple tuple = null;
        String key = null;
        try {
            key = new DataInputStream(in).readUTF();
            Object value = new ObjectInputStream(in).readObject();
            tuple = new SyncTuple(key, value);
        } catch (Exception ignored) {
        }

        if (tuple == null) {
            fields = null;
            if (key != null) {
                AstralSorcery.log.info("Could not read config from server with key: " + key);
            }
            break;
        }
        fields.set(i, tuple);
    }
}

From source file:herddb.proto.PduCodec.java

License:Apache License

public static Object readObject(ByteBuf dii) {

    int type = ByteBufUtils.readVInt(dii);

    switch (type) {
    case TYPE_BYTEARRAY:
        return ByteBufUtils.readArray(dii);
    case TYPE_LONG:
        return dii.readLong();
    case TYPE_INTEGER:
        return dii.readInt();
    case TYPE_SHORT:
        return dii.readShort();
    case TYPE_BYTE:
        return dii.readByte();
    case TYPE_STRING:
        return ByteBufUtils.readUnpooledRawString(dii);
    case TYPE_TIMESTAMP:
        return new java.sql.Timestamp(dii.readLong());
    case TYPE_NULL:
        return null;
    case TYPE_BOOLEAN:
        return dii.readBoolean();
    case TYPE_DOUBLE:
        return dii.readDouble();
    default:/*from w w w . j  a v a 2s. co  m*/
        throw new IllegalArgumentException("bad column type " + type);
    }
}

From source file:hivemall.mix.MixMessageDecoder.java

License:Open Source License

@Override
protected MixMessage decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    ByteBuf frame = (ByteBuf) super.decode(ctx, in);
    if (frame == null) {
        return null;
    }/*from w w w .  ja  v  a  2  s  .  c  o  m*/

    byte b = frame.readByte();
    MixEventName event = MixEventName.resolve(b);
    Object feature = decodeObject(frame);
    float weight = frame.readFloat();
    float covariance = frame.readFloat();
    short clock = frame.readShort();
    int deltaUpdates = frame.readInt();
    boolean cancelRequest = frame.readBoolean();
    String groupID = readString(frame);

    MixMessage msg = new MixMessage(event, feature, weight, covariance, clock, deltaUpdates, cancelRequest);
    msg.setGroupID(groupID);
    return msg;
}

From source file:io.advantageous.conekt.dns.impl.netty.decoder.MailExchangerDecoder.java

License:Open Source License

/**
 * Returns a decoded MX (mail exchanger) resource record, stored as an
 * instance of {@link MailExchangerRecord}.
 *
 * @param response the {@link DnsResponse} received that contained the resource
 *                 record being decoded/*from w  w  w. ja v  a  2 s  .com*/
 * @param resource the {@link DnsResource} being decoded
 */
@Override
public MailExchangerRecord decode(DnsResponse response, DnsResource resource) {
    ByteBuf packet = response.content().readerIndex(resource.contentIndex());
    int priority = packet.readShort();
    String name = DnsResponseDecoder.readName(packet);
    return new MailExchangerRecord(priority, name);
}

From source file:io.advantageous.conekt.dns.impl.netty.decoder.ServiceDecoder.java

License:Open Source License

/**
 * Returns a decoded SRV (service) resource record, stored as an instance of
 * {@link ServiceRecord}./*from  ww w. jav  a 2 s.co  m*/
 *
 * @param response the DNS response that contains the resource record being
 *                 decoded
 * @param resource the resource record being decoded
 */
@Override
public ServiceRecord decode(DnsResponse response, DnsResource resource) {
    ByteBuf packet = response.content().readerIndex(resource.contentIndex());
    int priority = packet.readShort();
    int weight = packet.readShort();
    int port = packet.readUnsignedShort();
    String target = DnsResponseDecoder.readName(packet);
    return new ServiceRecord(resource.name(), priority, weight, port, target);
}

From source file:io.airlift.drift.transport.netty.codec.HeaderTransport.java

License:Apache License

/**
 * Decodes the ByteBuf into a HeaderFrame transferring the reference ownership.
 * @param buffer buffer to be decoded; reference count ownership is transferred to this method
 * @return the decoded frame; caller is responsible for releasing this object
 *//* ww  w . j av  a2s.c o  m*/
public static ThriftFrame decodeFrame(ByteBuf buffer) {
    ByteBuf messageHeader = null;
    try {
        // frame header
        short magic = buffer.readShort();
        verify(magic == HEADER_MAGIC, "Invalid header magic");
        short flags = buffer.readShort();
        boolean outOfOrderResponse;
        switch (flags) {
        case FLAGS_NONE:
            outOfOrderResponse = false;
            break;
        case FLAG_SUPPORT_OUT_OF_ORDER:
            outOfOrderResponse = true;
            break;
        default:
            throw new IllegalArgumentException("Unsupported header flags: " + flags);
        }
        int frameSequenceId = buffer.readInt();
        int headerSize = buffer.readShort() << 2;
        messageHeader = buffer.readBytes(headerSize);

        // encoding info
        byte protocolId = messageHeader.readByte();
        Protocol protocol = Protocol.getProtocolByHeaderTransportId(protocolId);
        byte numberOfTransforms = messageHeader.readByte();
        if (numberOfTransforms > 0) {
            // currently there are only two transforms, a cryptographic extension which is deprecated, and gzip which is too expensive
            throw new IllegalArgumentException("Unsupported transform");
        }

        // headers
        // todo what about duplicate headers?
        ImmutableMap.Builder<String, String> allHeaders = ImmutableMap.builder();
        allHeaders.putAll(decodeHeaders(NORMAL_HEADERS, messageHeader));
        allHeaders.putAll(decodeHeaders(PERSISTENT_HEADERS, messageHeader));

        // message
        ByteBuf message = buffer.readBytes(buffer.readableBytes());

        // header frame wraps message byte buffer, so message should not be release yet
        return new ThriftFrame(frameSequenceId, message, allHeaders.build(), HEADER, protocol,
                outOfOrderResponse);
    } finally {
        // message header in an independent buffer and must be released
        if (messageHeader != null) {
            messageHeader.release();
        }

        // input buffer has been consumed and transformed into a HeaderFrame, so release it
        buffer.release();
    }
}