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.torchmind.netty.msgpack.codec.MessageCodec.java

License:Apache License

/**
 * {@inheritDoc}//from  w  w w .j  a va  2 s . co  m
 */
@Override
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
    // verify argument
    Preconditions.checkNotNull(msg, "msg");

    // search message identifier
    short identifier = this.getRegistry().getMessageID(msg.getClass());

    // send identifier
    out.writeShort(identifier);

    // encode message
    out.writeBytes(this.messagePack.write(msg));
}

From source file:com.torchmind.netty.msgpack.codec.MessageFrameCodec.java

License:Apache License

/**
 * {@inheritDoc}/*from ww w  . ja v a2s.c  o  m*/
 */
@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
    // ensure buffer is writable
    out.ensureWritable((msg.readableBytes() + 4));

    // write length
    out.writeInt(msg.readableBytes());

    // write data
    out.writeBytes(msg);
}

From source file:com.torchmind.netty.msgpack.test.MessageCodecTest.java

License:Apache License

/**
 * Tests message decoding./*from w w  w .  ja  v a2  s  .  c o m*/
 */
@Test
public void decoding() throws IOException {
    // create a msgpack instance
    MessagePack messagePack = new MessagePack();

    // create ByteBuf
    ByteBuf buffer = this.channel.alloc().buffer();

    // generate a message
    buffer.writeShort(0x00);
    buffer.writeBytes(messagePack.write(new TestMessage1(42)));

    // write
    this.channel.writeInbound(buffer);

    // create ByteBuf
    buffer = this.channel.alloc().buffer();

    // generate a message
    buffer.writeShort(0x10);
    buffer.writeBytes(messagePack.write(new TestMessage2(42, 21)));

    // write
    this.channel.writeInbound(buffer);

    // check inbound queue
    Assert.assertEquals("Less than two messages decoded", 2, this.channel.inboundMessages().size());

    // get first object
    TestMessage1 message1 = ((TestMessage1) this.channel.inboundMessages().poll());
    TestMessage2 message2 = ((TestMessage2) this.channel.inboundMessages().poll());

    // verify values
    Assert.assertEquals("Test value one does not match", 42, message1.getValue());
    Assert.assertEquals("Test value one does not match", 42, message2.getValue());
    Assert.assertEquals("Test value two does not match", 21, message2.getValue2());
}

From source file:com.turn.ttorrent.client.io.PeerHandshakeMessage.java

License:Apache License

public void toWire(@Nonnull ByteBuf out) {
    out.writeByte(protocolName.length);/*  w  w w  .j a  va 2s.c o m*/
    out.writeBytes(protocolName);
    out.writeBytes(reserved);
    out.writeBytes(infoHash);
    out.writeBytes(peerId);
}

From source file:com.turn.ttorrent.common.protocol.udp.UDPAnnounceRequestMessage.java

License:Apache License

@Override
public void toWire(ByteBuf out) {
    _toWire(out);//from   w w w .  ja v  a 2s  .  co  m
    out.writeBytes(infoHash);
    out.writeBytes(getPeerId());
    out.writeLong(downloaded);
    out.writeLong(uploaded);
    out.writeLong(left);
    out.writeInt(event.getId());
    out.writeBytes(getIp4Address(peerAddress));
    out.writeInt(key);
    out.writeInt(numWant);
    out.writeShort(peerAddress.getPort());
}

From source file:com.turn.ttorrent.common.protocol.udp.UDPAnnounceResponseMessage.java

License:Apache License

@Override
public void toWire(ByteBuf out) {
    _toWire(out);//w w w  .ja  v  a  2s .c  o m
    out.writeInt(interval);

    /**
     * Leechers (incomplete) are first, before seeders (complete) in the packet.
     */
    out.writeInt(incomplete);
    out.writeInt(complete);

    for (Peer peer : peers) {
        byte[] ip = peer.getIpBytes();
        if (ip == null || ip.length != 4)
            continue;
        out.writeBytes(ip);
        out.writeShort((short) peer.getPort());
    }
}

From source file:com.turn.ttorrent.common.protocol.udp.UDPTrackerErrorMessage.java

License:Apache License

@Override
public void toWire(ByteBuf out) {
    _toWire(out);
    out.writeBytes(reason.getBytes(Torrent.BYTE_ENCODING));
}

From source file:com.turn.ttorrent.protocol.tracker.udp.UDPTrackerErrorMessage.java

License:Apache License

@Override
public void toWire(ByteBuf out) {
    _toWire(out);
    out.writeBytes(reason.getBytes(BEUtils.BYTE_ENCODING));
}

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

License:Open Source License

private void writePushNotification(final ChannelHandlerContext context,
        final PushNotificationPromise responsePromise, final ChannelPromise writePromise) {
    if (context.channel().isActive()) {
        final int streamId = this.connection().local().incrementAndGetNextStreamId();

        if (streamId > 0) {
            // We'll attach the push notification and response promise to the stream as soon as the stream is created.
            // Because we're using a StreamBufferingEncoder under the hood, there's no guarantee as to when the stream
            // will actually be created, and so we attach these in the onStreamAdded listener to make sure everything
            // is happening in a predictable order.
            this.unattachedResponsePromisesByStreamId.put(streamId, responsePromise);
            final ApnsPushNotification pushNotification = responsePromise.getPushNotification();

            final Http2Headers headers = getHeadersForPushNotification(pushNotification, streamId);

            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((ChannelFuture) headersPromise, dataPromise);
            promiseCombiner.finish(writePromise);

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

                @Override/*  w w w .jav a  2 s  .c  o  m*/
                public void operationComplete(final ChannelPromise future) {
                    if (!future.isSuccess()) {
                        log.trace("Failed to write push notification on stream {}.", streamId, future.cause());
                        responsePromise.tryFailure(future.cause());
                    }
                }
            });
        } else {
            // This is very unlikely, but in the event that we run out of stream IDs, we need to open a new
            // connection. Just closing the context should be enough; automatic reconnection should take things
            // from there.
            writePromise.tryFailure(STREAMS_EXHAUSTED_EXCEPTION);
            context.channel().close();
        }
    } else {
        writePromise.tryFailure(STREAM_CLOSED_BEFORE_REPLY_EXCEPTION);
    }
}

From source file:com.turo.pushy.apns.server.ValidatingPushNotificationHandlerTest.java

License:Open Source License

@Test
public void testHandleNotificationWithOversizedPayload() {
    final int size = 4096 * 2;
    final ByteBuf largePayload = UnpooledByteBufAllocator.DEFAULT.buffer(size);

    try {//from  ww w  .  ja va 2s .  c om
        final byte[] payloadBytes = new byte[size];
        new Random().nextBytes(payloadBytes);

        largePayload.writeBytes(payloadBytes);

        this.testWithExpectedRejection(
                "Push notifications with a device token for the wrong topic should be rejected.",
                this.getHandler(DEVICE_TOKENS_BY_TOPIC, Collections.<String, Date>emptyMap()), this.headers,
                largePayload, RejectionReason.PAYLOAD_TOO_LARGE);
    } finally {
        largePayload.release();
    }
}