Example usage for io.netty.buffer ByteBuf writeBytes

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

Introduction

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

Prototype

public abstract ByteBuf writeBytes(ByteBuffer src);

Source Link

Document

Transfers the specified source buffer's data to this buffer starting at the current writerIndex until the source buffer's position reaches its limit, and increases the writerIndex by the number of the transferred bytes.

Usage

From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.PubRelEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext chc, PubRelMessage msg, ByteBuf out) {
    out.writeByte(AbstractMessage.PUBREL << 4);
    out.writeBytes(Utils.encodeRemainingLength(2));
    out.writeShort(msg.getMessageID());//from   w w  w .  j  a  va2 s.  c  o  m
}

From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.SubAckEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext chc, SubAckMessage message, ByteBuf out) {
    if (message.types().isEmpty()) {
        throw new IllegalArgumentException("Found a suback message with empty topics");
    }//from w w  w .j a va  2  s.  c  o m

    int variableHeaderSize = 2 + message.types().size();
    ByteBuf buff = chc.alloc().buffer(6 + variableHeaderSize);
    try {
        buff.writeByte(AbstractMessage.SUBACK << 4);
        buff.writeBytes(Utils.encodeRemainingLength(variableHeaderSize));
        buff.writeShort(message.getMessageID());
        for (AbstractMessage.QOSType c : message.types()) {
            buff.writeByte(c.ordinal());
        }

        out.writeBytes(buff);
    } finally {
        buff.release();
    }
}

From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.SubscribeEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext chc, SubscribeMessage message, ByteBuf out) {
    if (message.subscriptions().isEmpty()) {
        throw new IllegalArgumentException("Found a subscribe message with empty topics");
    }// ww w. j av a  2  s . co  m

    if (message.getQos() != AbstractMessage.QOSType.LEAST_ONE) {
        throw new IllegalArgumentException("Expected a message with QOS 1, found " + message.getQos());
    }

    ByteBuf variableHeaderBuff = chc.alloc().buffer(4);
    ByteBuf buff = null;
    try {
        variableHeaderBuff.writeShort(message.getMessageID());
        for (SubscribeMessage.Couple c : message.subscriptions()) {
            variableHeaderBuff.writeBytes(Utils.encodeString(c.getTopicFilter()));
            variableHeaderBuff.writeByte(c.getQos());
        }

        int variableHeaderSize = variableHeaderBuff.readableBytes();
        byte flags = Utils.encodeFlags(message);
        buff = chc.alloc().buffer(2 + variableHeaderSize);

        buff.writeByte(AbstractMessage.SUBSCRIBE << 4 | flags);
        buff.writeBytes(Utils.encodeRemainingLength(variableHeaderSize));
        buff.writeBytes(variableHeaderBuff);

        out.writeBytes(buff);
    } finally {
        variableHeaderBuff.release();
        buff.release();
    }
}

From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.Utils.java

License:Open Source License

/**
 * Return the IoBuffer with string encoded as MSB, LSB and UTF-8 encoded
 * string content./*from  w  w  w .  jav  a2s  . co  m*/
 */
public static ByteBuf encodeString(String str) {
    ByteBuf out = Unpooled.buffer(2);
    byte[] raw;
    try {
        raw = str.getBytes("UTF-8");
        //NB every Java platform has got UTF-8 encoding by default, so this 
        //exception are never raised.
    } catch (UnsupportedEncodingException ex) {
        LoggerFactory.getLogger(Utils.class).error(null, ex);
        return null;
    }
    //Utils.writeWord(out, raw.length);
    out.writeShort(raw.length);
    out.writeBytes(raw);
    return out;
}

From source file:com.quavo.osrs.network.protocol.codec.game.GamePacketEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, GamePacketResponse msg, ByteBuf out) throws Exception {
    PacketEncoder<PacketContext> packet = msg.getPacket();
    PacketType type = packet.getPacket().getType();
    ByteBuf buffer = packet.getBuilder().getBuffer();

    out.writeByte(packet.getPacket().getId()/* + encoder.nextInt() */);
    if (type == PacketType.VARIABLE_BYTE) {
        out.writeByte(buffer.writerIndex());
    } else if (type == PacketType.VARIABLE_SHORT) {
        out.writeShort(buffer.writerIndex());
    }/*  w  w  w  . j a  v a  2s.  c  om*/
    out.writeBytes(buffer);
}

From source file:com.quavo.osrs.network.protocol.codec.update.UpdateEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, UpdateResponse msg, ByteBuf out) throws Exception {
    int type = msg.getType();
    int id = msg.getId();
    ByteBuf container = msg.getContainer();

    int compression = container.readUnsignedByte();
    int length = container.readInt();

    out.writeByte(type);/*from ww  w.  j  a  v  a  2  s  .  c  om*/
    out.writeShort(id);
    out.writeByte(compression);
    out.writeInt(length);

    int bytes = container.readableBytes();
    if (bytes > 504) {
        bytes = 504;
    }
    out.writeBytes(container.readBytes(bytes));
    while ((bytes = container.readableBytes()) != 0) {
        if (bytes == 0) {
            break;
        } else if (bytes > 511) {
            bytes = 511;
        }
        out.writeByte(0xff);
        out.writeBytes(container.readBytes(bytes));
    }
}

From source file:com.quavo.util.buf.ByteBufUtils.java

License:Open Source License

/**
 * Writes a jag string into the buffer.//from ww  w  .  j  av a  2 s.c  o  m
 *
 * @param out The buffer.
 * @param str The string.
 */
public static void writeJagString(ByteBuf out, String str) {
    out.writeByte(0);
    out.writeBytes(str.getBytes());
    out.writeByte(ByteBufUtils.STRING_TERMINATOR);
}

From source file:com.relayrides.pushy.apns.ApnsClientHandler.java

License:Open Source License

@Override
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise writePromise)
        throws Http2Exception {
    if (message instanceof PushNotificationAndResponsePromise) {
        final PushNotificationAndResponsePromise pushNotificationAndResponsePromise = (PushNotificationAndResponsePromise) message;

        final ApnsPushNotification pushNotification = pushNotificationAndResponsePromise.getPushNotification();

        if (this.responsePromises.containsKey(pushNotification)) {
            writePromise.tryFailure(new PushNotificationStillPendingException());
        } else {//from   ww w .j av  a2  s  .co m
            this.responsePromises.put(pushNotification,
                    pushNotificationAndResponsePromise.getResponsePromise());

            pushNotificationAndResponsePromise.getResponsePromise().addListener(
                    new GenericFutureListener<Future<PushNotificationResponse<ApnsPushNotification>>>() {

                        @Override
                        public void operationComplete(
                                final Future<PushNotificationResponse<ApnsPushNotification>> future) {
                            // Regardless of the outcome, when the response promise is finished, we want to remove it from
                            // the map of pending promises.
                            ApnsClientHandler.this.responsePromises.remove(pushNotification);
                        }
                    });

            this.write(context, pushNotification, writePromise);
        }
    } else if (message instanceof ApnsPushNotification) {
        final ApnsPushNotification pushNotification = (ApnsPushNotification) message;

        try {
            final int streamId = (int) this.nextStreamId;

            final Http2Headers headers = new DefaultHttp2Headers().method(HttpMethod.POST.asciiName())
                    .authority(this.authority).path(APNS_PATH_PREFIX + pushNotification.getToken())
                    .addInt(APNS_EXPIRATION_HEADER, pushNotification.getExpiration() == null ? 0
                            : (int) (pushNotification.getExpiration().getTime() / 1000));

            final String authenticationToken = this.apnsClient
                    .getAuthenticationTokenSupplierForTopic(pushNotification.getTopic()).getToken();
            headers.add(APNS_AUTHORIZATION_HEADER, "bearer " + authenticationToken);

            if (pushNotification.getCollapseId() != null) {
                headers.add(APNS_COLLAPSE_ID_HEADER, pushNotification.getCollapseId());
            }

            if (pushNotification.getPriority() != null) {
                headers.addInt(APNS_PRIORITY_HEADER, pushNotification.getPriority().getCode());
            }

            if (pushNotification.getTopic() != null) {
                headers.add(APNS_TOPIC_HEADER, pushNotification.getTopic());
            }

            final ChannelPromise headersPromise = context.newPromise();
            this.encoder().writeHeaders(context, streamId, headers, 0, false, headersPromise);
            log.trace("Wrote headers on stream {}: {}", streamId, headers);

            final ByteBuf payloadBuffer = context.alloc().ioBuffer(INITIAL_PAYLOAD_BUFFER_CAPACITY);
            payloadBuffer.writeBytes(pushNotification.getPayload().getBytes(StandardCharsets.UTF_8));

            final ChannelPromise dataPromise = context.newPromise();
            this.encoder().writeData(context, streamId, payloadBuffer, 0, true, dataPromise);
            log.trace("Wrote payload on stream {}: {}", streamId, pushNotification.getPayload());

            final PromiseCombiner promiseCombiner = new PromiseCombiner();
            promiseCombiner.addAll(headersPromise, dataPromise);
            promiseCombiner.finish(writePromise);

            writePromise.addListener(new GenericFutureListener<ChannelPromise>() {

                @Override
                public void operationComplete(final ChannelPromise future) throws Exception {
                    if (future.isSuccess()) {
                        ApnsClientHandler.this.pushNotificationsByStreamId.put(streamId, pushNotification);
                        ApnsClientHandler.this.authenticationTokensByStreamId.put(streamId,
                                authenticationToken);
                    } else {
                        log.trace("Failed to write push notification on stream {}.", streamId, future.cause());

                        final Promise<PushNotificationResponse<ApnsPushNotification>> responsePromise = ApnsClientHandler.this.responsePromises
                                .get(pushNotification);

                        if (responsePromise != null) {
                            responsePromise.tryFailure(future.cause());
                        } else {
                            log.error("Notification write failed, but no response promise found.");
                        }
                    }
                }
            });

            this.nextStreamId += 2;

            if (this.nextStreamId >= STREAM_ID_RESET_THRESHOLD) {
                // This is very unlikely, but in the event that we run out of stream IDs (the maximum allowed is
                // 2^31, per https://httpwg.github.io/specs/rfc7540.html#StreamIdentifiers), we need to open a new
                // connection. Just closing the context should be enough; automatic reconnection should take things
                // from there.
                context.close();
            }
        } catch (NoKeyForTopicException | SignatureException e) {
            writePromise.tryFailure(e);
        }

    } else {
        // This should never happen, but in case some foreign debris winds up in the pipeline, just pass it through.
        log.error("Unexpected object in pipeline: {}", message);
        context.write(message, writePromise);
    }
}

From source file:com.rs3e.network.protocol.codec.js5.UpdateEncoder.java

License:Open Source License

@Override
public void encode(ChannelHandlerContext ctx, FileResponse response, ByteBuf buf) throws Exception {
    ByteBuf container = response.getContainer();
    int type = response.getType();
    int file = response.getFile();

    int compression = container.readUnsignedByte();
    int size = ((container.readByte() & 0xff) << 24) + ((container.readByte() & 0xff) << 16)
            + ((container.readByte() & 0xff) << 8) + (container.readByte() & 0xff);
    if (!response.isPriority()) {
        file |= 0x80000000;//  ww w.j a  va  2  s.  c  o m
    }

    buf.writeByte(type);
    buf.writeInt(file);
    buf.writeByte(compression);
    buf.writeInt(size);

    int bytes = container.readableBytes();
    if (bytes > 502) {
        bytes = 502;
    }

    buf.writeBytes(container.readBytes(bytes));

    for (;;) {
        bytes = container.readableBytes();
        if (bytes == 0) {
            break;
        } else if (bytes > 507) {
            bytes = 507;
        }
        buf.writeByte(type);
        buf.writeInt(file);
        buf.writeBytes(container.readBytes(bytes));

    }
}

From source file:com.rs3e.network.protocol.worldlist.WorldListEncoder.java

License:Open Source License

@Override
public void encode(ChannelHandlerContext ctx, WorldListMessage list, ByteBuf out) throws Exception {
    ByteBuf buf = Unpooled.buffer();//from www . ja  v a 2  s. c  o m
    buf.writeByte(1);
    buf.writeByte(1);

    Country[] countries = list.getCountries();
    ByteBufUtils.writeSmart(buf, countries.length);
    for (Country country : countries) {
        ByteBufUtils.writeSmart(buf, country.getFlag());
        ByteBufUtils.writeWorldListString(buf, country.getName());
    }

    World[] worlds = list.getWorlds();
    int minId = worlds[0].getId();
    int maxId = worlds[0].getId();
    for (int i = 1; i < worlds.length; i++) {
        World world = worlds[i];
        int id = world.getId();

        if (id > maxId)
            maxId = id;
        if (id < minId)
            minId = id;
    }

    ByteBufUtils.writeSmart(buf, minId);
    ByteBufUtils.writeSmart(buf, maxId);
    ByteBufUtils.writeSmart(buf, worlds.length);

    for (World world : worlds) {
        ByteBufUtils.writeSmart(buf, world.getId() - minId);
        buf.writeByte(world.getCountry());
        buf.writeInt(world.getFlags());
        ByteBufUtils.writeWorldListString(buf, world.getActivity());
        ByteBufUtils.writeWorldListString(buf, world.getIp());
    }

    buf.writeInt(list.getSessionId());
    for (int i = 0; i < worlds.length; i++) {
        World world = worlds[i];
        ByteBufUtils.writeSmart(buf, world.getId() - minId);
        buf.writeShort(0);
    }

    out.writeByte(0); // 0 = ok, 7/9 = world full
    out.writeShort(buf.readableBytes());
    out.writeBytes(buf);
}