Example usage for io.netty.buffer Unpooled buffer

List of usage examples for io.netty.buffer Unpooled buffer

Introduction

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

Prototype

public static ByteBuf buffer(int initialCapacity) 

Source Link

Document

Creates a new big-endian Java heap buffer with the specified capacity , which expands its capacity boundlessly on demand.

Usage

From source file:com.dempe.chat.common.mqtt.codec.PublishDecoder.java

License:Open Source License

@Override
void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception {
    LOG.debug("decode invoked with buffer {}", in);
    in.resetReaderIndex();//ww w  .  j  av  a 2 s .  c o  m
    int startPos = in.readerIndex();

    //Common decoding part
    PublishMessage message = new PublishMessage();
    if (!decodeCommonHeader(message, in)) {
        LOG.debug("decode ask for more data after {}", in);
        in.resetReaderIndex();
        return;
    }

    if (Utils.isMQTT3_1_1(ctx)) {
        if (message.getQos() == AbstractMessage.QOSType.MOST_ONE && message.isDupFlag()) {
            //bad protocol, if QoS=0 => DUP = 0
            throw new CorruptedFrameException("Received a PUBLISH with QoS=0 & DUP = 1, MQTT 3.1.1 violation");
        }

        if (message.getQos() == AbstractMessage.QOSType.RESERVED) {
            throw new CorruptedFrameException(
                    "Received a PUBLISH with QoS flags setted 10 b11, MQTT 3.1.1 violation");
        }
    }

    int remainingLength = message.getRemainingLength();

    //Topic name
    String topic = Utils.decodeString(in);
    if (topic == null) {
        in.resetReaderIndex();
        return;
    }
    //[MQTT-3.3.2-2] The Topic Name in the PUBLISH Packet MUST NOT contain wildcard characters.
    if (topic.contains("+") || topic.contains("#")) {
        throw new CorruptedFrameException(
                "Received a PUBLISH with topic containing wild card chars, topic: " + topic);
    }
    //check topic is at least one char [MQTT-4.7.3-1]
    if (topic.length() == 0) {
        throw new CorruptedFrameException("Received a PUBLISH with topic without any character");
    }

    message.setTopicName(topic);

    if (message.getQos() == AbstractMessage.QOSType.LEAST_ONE
            || message.getQos() == AbstractMessage.QOSType.EXACTLY_ONCE) {
        message.setMessageID(in.readUnsignedShort());
    }
    int stopPos = in.readerIndex();

    //read the payload
    int payloadSize = remainingLength - (stopPos - startPos - 2)
            + (Utils.numBytesToEncode(remainingLength) - 1);
    if (in.readableBytes() < payloadSize) {
        in.resetReaderIndex();
        return;
    }
    ByteBuf bb = Unpooled.buffer(payloadSize);
    in.readBytes(bb);
    message.setPayload(bb.nioBuffer());

    out.add(message);
}

From source file:com.dempe.chat.common.mqtt.codec.Utils.java

License:Open Source License

/**
 * Encode the value in the format defined in specification as variable length
 * array./*from  w  ww.  ja v a 2  s . co  m*/
 *
 * @throws IllegalArgumentException if the value is not in the specification bounds
 *                                  [0..268435455].
 */
static ByteBuf encodeRemainingLength(int value) throws CorruptedFrameException {
    if (value > MAX_LENGTH_LIMIT || value < 0) {
        throw new CorruptedFrameException("Value should in range 0.." + MAX_LENGTH_LIMIT + " found " + value);
    }

    ByteBuf encoded = Unpooled.buffer(4);
    byte digit;
    do {
        digit = (byte) (value % 128);
        value = value / 128;
        // if there are more digits to encode, set the top bit of this digit
        if (value > 0) {
            digit = (byte) (digit | 0x80);
        }
        encoded.writeByte(digit);
    } while (value > 0);
    return encoded;
}

From source file:com.dempe.chat.common.mqtt.codec.Utils.java

License:Open Source License

/**
 * Return the IoBuffer with string encoded as MSB, LSB and bytes array content.
 *///  w  ww  .j a v a 2  s.c  o  m
public static ByteBuf encodeFixedLengthContent(byte[] content) {
    ByteBuf out = Unpooled.buffer(2);
    out.writeShort(content.length);
    out.writeBytes(content);
    return out;
}

From source file:com.ebay.jetstream.http.netty.client.HttpClient.java

License:MIT License

public void post(URI uri, Object content, Map<String, String> headers, ResponseFuture responsefuture)
        throws Exception {

    if (m_shutDown.get()) {
        throw new IOException("IO has been Shutdown = ");

    }/*www .j a v  a2s  .  c om*/

    if (uri == null)
        throw new NullPointerException("uri is null or incorrect");

    if (!m_started.get()) {
        synchronized (this) {
            if (!m_started.get()) {
                start();
                m_started.set(true);
            }
        }
    }

    ByteBuf byteBuf = Unpooled.buffer(m_config.getInitialRequestBufferSize());
    ByteBufOutputStream outputStream = new ByteBufOutputStream(byteBuf);

    // transform to json
    try {
        m_mapper.writeValue(outputStream, content);
    } catch (JsonGenerationException e) {
        throw e;
    } catch (JsonMappingException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        outputStream.close();
    }

    EmbeddedChannel encoder;
    String contenteEncoding;
    if ("gzip".equals(m_config.getCompressEncoder())) {
        encoder = new EmbeddedChannel(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.GZIP, 1));
        contenteEncoding = "gzip";

    } else if ("deflate".equals(m_config.getCompressEncoder())) {
        encoder = new EmbeddedChannel(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.ZLIB, 1));
        contenteEncoding = "deflate";
    } else {
        encoder = null;
        contenteEncoding = null;
    }

    if (encoder != null) {
        encoder.config().setAllocator(UnpooledByteBufAllocator.DEFAULT);
        encoder.writeOutbound(byteBuf);
        encoder.finish();
        byteBuf = (ByteBuf) encoder.readOutbound();
        encoder.close();
    }

    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            uri.toString(), byteBuf);
    if (contenteEncoding != null) {
        HttpHeaders.setHeader(request, HttpHeaders.Names.CONTENT_ENCODING, contenteEncoding);
    }
    HttpHeaders.setHeader(request, HttpHeaders.Names.ACCEPT_ENCODING, "gzip, deflate");
    HttpHeaders.setHeader(request, HttpHeaders.Names.CONTENT_TYPE, "application/json");
    HttpHeaders.setContentLength(request, byteBuf.readableBytes());

    if (isKeepAlive())
        HttpHeaders.setHeader(request, HttpHeaders.Names.CONNECTION, "keep-alive");

    if (headers != null) {
        @SuppressWarnings("rawtypes")
        Iterator it = headers.entrySet().iterator();
        while (it.hasNext()) {
            @SuppressWarnings("rawtypes")
            Map.Entry pairs = (Map.Entry) it.next();
            HttpHeaders.setHeader(request, (String) pairs.getKey(), pairs.getValue());
        }
    }

    if (responsefuture != null) {
        RequestId reqid = RequestId.newRequestId();

        m_responseDispatcher.add(reqid, responsefuture);

        HttpHeaders.setHeader(request, "X_EBAY_REQ_ID", reqid.toString());
        // we expect this to be echoed in the response used for correlation.
    }

    if (m_dataQueue.size() < m_workQueueCapacity) {
        ProcessHttpWorkRequest workRequest = new ProcessHttpWorkRequest(this, uri, request);

        if (!m_dataQueue.offer(workRequest)) {
            if (responsefuture != null) {
                responsefuture.setFailure();
                m_responseDispatcher.remove(request.headers().get("X_EBAY_REQ_ID"));
            }
        }
    } else {
        throw new IOException("downstream Queue is full ");
    }

}

From source file:com.ebay.jetstream.http.netty.server.DefaultHttpServletResponse.java

License:MIT License

public DefaultHttpServletResponse(HttpVersion version, HttpResponseStatus status, int bufsz) {
    m_bufsz = bufsz;/* w w  w.j a  va 2  s.  c  o  m*/
    if (m_bufsz == 0) {
        m_buffer = Unpooled.EMPTY_BUFFER;
    } else {
        m_buffer = Unpooled.buffer(m_bufsz);
    }
    m_nettyhttpresp = new DefaultFullHttpResponse(version, status, m_buffer);
}

From source file:com.example.spring.boot.netty.TcpClientHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    new Thread(new Runnable() {
        @Override//from  w  ww. j av a2  s .c o  m
        public void run() {
            while (true) {
                ByteBuf buf = Unpooled.buffer(256);
                buf.writeBytes(MSG.getBytes());
                ctx.writeAndFlush(buf);
                try {
                    Thread.sleep(tcpClient.getInterval());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();
}

From source file:com.feihong.newzxclient.tcp.NettyClientHandler.java

License:Apache License

protected void sendMsg(Msg.CommonMessage msg) {
    if (mContext != null) {
        byte[] result = msg.toByteArray();

        ByteBuf buf = Unpooled.buffer(4 + result.length);
        buf.writeInt(result.length);// w w w.  j  a  v a 2s.  c  o m
        buf.writeBytes(result);

        //System.out.println("send Msg success!");
        mContext.writeAndFlush(buf);
    }
}

From source file:com.flowpowered.network.pipeline.MessageProcessorDecoderTest.java

License:MIT License

@Test
public void test() throws Exception {
    // Preprocessor basically is split into two parts
    // Part 1 is just a direct copy
    // Part 2 negates all bytes before copying
    final AtomicReference<MessageProcessor> processor = new AtomicReference<>();
    MessageProcessorDecoder processorDecoder = new MessageProcessorDecoder(null) {
        @Override//from   w w  w. j av a  2s . c  o  m
        protected MessageProcessor getProcessor() {
            return processor.get();
        }
    };

    // Set up a fake ChannelHandlerContext
    FakeChannelHandlerContext fake = ChannelHandlerContextFaker.setup();
    AtomicReference<ByteBuf> ref = new AtomicReference<>();
    fake.setReference(ref);
    LinkedList<byte[]> outputList = new LinkedList<>();

    Random r = new Random();

    // Get some random bytes for data
    byte[] input = new byte[LENGTH];
    r.nextBytes(input);

    boolean breakOccured = false;
    int position = 0;

    for (int i = 0; i < input.length;) {
        // Simulate real data read
        int burstSize = r.nextInt(512);
        // With a 1/10 chance of having an extra-large burst
        if (r.nextInt(10) == 0) {
            burstSize *= 10;
        }

        // Final burst needs to be clamped
        if (i + burstSize > input.length) {
            burstSize = input.length - i;
        }

        // And we can't negate in the middle of a burst
        if (i + burstSize > BREAK && !breakOccured) {
            burstSize = BREAK - i;
        }

        // Write info to a new ByteBuf
        final ByteBuf buf = Unpooled.buffer(burstSize);
        buf.writeBytes(input, i, burstSize);
        i += burstSize;

        // Fake a read
        processorDecoder.channelRead(fake, buf);

        final ByteBuf returned = ref.get();

        while (returned != null) {
            int packetSize = r.nextInt(128) + 1;
            if (r.nextInt(10) == 0) {
                packetSize *= 20;
            }

            if (packetSize > returned.readableBytes()) {
                packetSize = returned.readableBytes();
            }
            if (position + packetSize > BREAK && !breakOccured) {
                packetSize = BREAK - position;
            }
            if (position + packetSize > LENGTH) {
                packetSize = LENGTH - position;
            }

            if (packetSize == 0) {
                break;
            }

            byte[] array = new byte[packetSize];

            returned.readBytes(array);
            position += packetSize;

            if (position == BREAK) {
                processor.set(new NegatingProcessor(512));
                breakOccured = true;
            }
            outputList.add(array);
        }
    }

    // Get the output data and combine into one array
    byte[] output = new byte[LENGTH];
    int i = 0;
    for (byte[] array : outputList) {
        for (int j = 0; j < array.length; j++) {
            output[i++] = array[j];
        }
    }

    for (i = 0; i < input.length; i++) {
        byte expected = i < BREAK ? input[i] : (byte) ~input[i];
        if (output[i] != expected) {
            for (int j = Math.max(0, i - 10); j <= i + 10; j++) {
                System.out.println(j + ") " + Integer.toBinaryString(j < BREAK ? input[j] : (byte) ~input[j])
                        + " " + Integer.toBinaryString(output[j]));
            }
        }

        if (i < BREAK) {
            assertTrue("Input/Output mismatch at position " + i + ". Expected " + input[i] + " but got "
                    + output[i] + ". Break is: " + BREAK, output[i] == input[i]);
        } else {
            assertTrue(
                    "Input/Output mismatch at position " + i + ", after the processor change. Expected "
                            + (byte) ~input[i] + " but got " + output[i] + ". Break is: " + BREAK,
                    output[i] == (byte) ~input[i]);
        }
    }
}

From source file:com.flowpowered.networking.pipeline.MessageProcessorDecoderTest.java

License:MIT License

@Test
public void test() throws Exception {
    // Preprocessor basically is split into two parts
    // Part 1 is just a direct copy
    // Part 2 negates all bytes before copying
    final AtomicReference<MessageProcessor> processor = new AtomicReference<>();
    MessageProcessorDecoder processorDecoder = new MessageProcessorDecoder(null) {
        @Override//  ww w.  j a v  a2 s  .c  o  m
        protected MessageProcessor getProcessor() {
            return processor.get();
        }
    };

    // Set up a fake ChannelHandlerContext
    FakeChannelHandlerContext fake = ChannelHandlerContextFaker.setup();
    AtomicReference<ByteBuf> ref = new AtomicReference<>();
    fake.setReference(ref);
    LinkedList<byte[]> outputList = new LinkedList<byte[]>();

    Random r = new Random();

    // Get some random bytes for data
    byte[] input = new byte[LENGTH];
    r.nextBytes(input);

    boolean breakOccured = false;
    int position = 0;

    for (int i = 0; i < input.length;) {
        // Simulate real data read
        int burstSize = r.nextInt(512);
        // With a 1/10 chance of having an extra-large burst
        if (r.nextInt(10) == 0) {
            burstSize *= 10;
        }

        // Final burst needs to be clamped
        if (i + burstSize > input.length) {
            burstSize = input.length - i;
        }

        // And we can't negate in the middle of a burst
        if (i + burstSize > BREAK && !breakOccured) {
            burstSize = BREAK - i;
        }

        // Write info to a new ByteBuf
        final ByteBuf buf = Unpooled.buffer(burstSize);
        buf.retain();
        buf.writeBytes(input, i, burstSize);
        i += burstSize;

        // Fake a read
        processorDecoder.channelRead(fake, buf);

        final ByteBuf returned = ref.get();

        while (returned != null && true) {
            int packetSize = r.nextInt(128) + 1;
            if (r.nextInt(10) == 0) {
                packetSize *= 20;
            }

            if (packetSize > returned.readableBytes()) {
                packetSize = returned.readableBytes();
            }
            if (position + packetSize > BREAK && !breakOccured) {
                packetSize = BREAK - position;
            }
            if (position + packetSize > LENGTH) {
                packetSize = LENGTH - position;
            }

            if (packetSize == 0) {
                break;
            }

            byte[] array = new byte[packetSize];

            returned.readBytes(array);
            position += packetSize;

            if (position == BREAK) {
                processor.set(new NegatingProcessor(512));
                breakOccured = true;
            }
            outputList.add(array);
        }
    }

    // Get the output data and combine into one array
    byte[] output = new byte[LENGTH];
    int i = 0;
    for (byte[] array : outputList) {
        for (int j = 0; j < array.length; j++) {
            output[i++] = array[j];
        }
    }

    for (i = 0; i < input.length; i++) {
        byte expected = i < BREAK ? input[i] : (byte) ~input[i];
        if (output[i] != expected) {
            for (int j = Math.max(0, i - 10); j <= i + 10; j++) {
                System.out.println(j + ") " + Integer.toBinaryString(j < BREAK ? input[j] : (byte) ~input[j])
                        + " " + Integer.toBinaryString(output[j]));
            }
        }

        if (i < BREAK) {
            assertTrue("Input/Output mismatch at position " + i + ". Expected " + input[i] + " but got "
                    + output[i] + ". Break is: " + BREAK, output[i] == input[i]);
        } else {
            assertTrue(
                    "Input/Output mismatch at position " + i + ", after the processor change. Expected "
                            + (byte) ~input[i] + " but got " + output[i] + ". Break is: " + BREAK,
                    output[i] == (byte) ~input[i]);
        }
    }
}

From source file:com.flysoloing.learning.network.netty.udt.echo.bytes.ByteEchoClientHandler.java

License:Apache License

public ByteEchoClientHandler() {
    super(false);

    message = Unpooled.buffer(ByteEchoClient.SIZE);
    for (int i = 0; i < message.capacity(); i++) {
        message.writeByte((byte) i);
    }/*from  w w  w.  j  av  a  2  s  . c o m*/
}