Example usage for io.netty.buffer ByteBuf readableBytes

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

Introduction

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

Prototype

public abstract int readableBytes();

Source Link

Document

Returns the number of readable bytes which is equal to (this.writerIndex - this.readerIndex) .

Usage

From source file:com.cloudhopper.smpp.transcoder.PduDecoderTest.java

License:Apache License

@Test
public void decodeQuerySmResp() throws Exception {
    ByteBuf buffer = BufferHelper.createBuffer("00000019800000030000000000004FE8313233343500000600");

    QuerySmResp pdu0 = (QuerySmResp) transcoder.decode(buffer);

    Assert.assertEquals(25, pdu0.getCommandLength());
    Assert.assertEquals(SmppConstants.CMD_ID_QUERY_SM_RESP, pdu0.getCommandId());
    Assert.assertEquals(0, pdu0.getCommandStatus());
    Assert.assertEquals(20456, pdu0.getSequenceNumber());
    Assert.assertEquals("12345", pdu0.getMessageId());
    Assert.assertEquals("", pdu0.getFinalDate());
    Assert.assertEquals((byte) 0x06, pdu0.getMessageState());
    Assert.assertEquals((byte) 0x00, pdu0.getErrorCode());
    Assert.assertEquals(true, pdu0.isResponse());

    Assert.assertEquals(0, buffer.readableBytes());
}

From source file:com.cloudhopper.smpp.util.ChannelBufferUtil.java

License:Apache License

/**
 * Read and create a new Address from a buffer.  Checks if there is
 * a minimum number of bytes readable from the buffer.
 * @param buffer/* w  ww  .  j av a 2 s.  co  m*/
 * @return
 * @throws UnrecoverablePduException
 * @throws RecoverablePduException
 */
static public Address readAddress(ByteBuf buffer) throws UnrecoverablePduException, RecoverablePduException {
    // an address is at least 3 bytes long (ton, npi, and null byte)
    if (buffer.readableBytes() < 3) {
        throw new NotEnoughDataInBufferException("Parsing address", buffer.readableBytes(), 3);
    }
    Address address = new Address();
    address.read(buffer);
    return address;
}

From source file:com.cloudhopper.smpp.util.ChannelBufferUtil.java

License:Apache License

/**
 * Reads a TLV from a buffer. This method is greedy and will read bytes
 * even if it won't be able to successfully complete.  It's assumed this
 * method will only be called if its known ahead of time that all bytes
 * will be available ahead of time./*www  . j a  va 2 s .  c  o m*/
 * @param buffer The buffer to read from
 * @return A new TLV instance
 * @throws NotEnoughDataInBufferException
 */
static public Tlv readTlv(ByteBuf buffer) throws NotEnoughDataInBufferException {
    // a TLV is at least 4 bytes (tag+length)
    if (buffer.readableBytes() < 4) {
        throw new NotEnoughDataInBufferException("Parsing TLV tag and length", buffer.readableBytes(), 4);
    }

    short tag = buffer.readShort();
    int length = buffer.readUnsignedShort();

    // check if we have enough data for the TLV
    if (buffer.readableBytes() < length) {
        throw new NotEnoughDataInBufferException("Parsing TLV value", buffer.readableBytes(), length);
    }

    byte[] value = new byte[length];
    buffer.readBytes(value);

    return new Tlv(tag, value);
}

From source file:com.cloudhopper.smpp.util.ChannelBufferUtil.java

License:Apache License

/**
 * Reads a C-String (null terminated) from a buffer.  This method will
 * attempt to find the null byte and read all data up to and including
 * the null byte.  The returned String does not include the null byte.
 * Will throw an exception if no null byte is found and it runs out of data
 * in the buffer to read.//from  ww  w.  jav a2 s  .  c o m
 * @param buffer
 * @return
 * @throws TerminatingNullByteNotFoundException
 */
static public String readNullTerminatedString(ByteBuf buffer) throws TerminatingNullByteNotFoundException {
    // maximum possible length are the readable bytes in buffer
    int maxLength = buffer.readableBytes();

    // if there are no readable bytes, return null
    if (maxLength == 0) {
        return null;
    }

    // the reader index is defaulted to the readerIndex
    int offset = buffer.readerIndex();
    int zeroPos = 0;

    // search for NULL byte until we hit end or find it
    while ((zeroPos < maxLength) && (buffer.getByte(zeroPos + offset) != 0x00)) {
        zeroPos++;
    }

    if (zeroPos >= maxLength) {
        // a NULL byte was not found
        throw new TerminatingNullByteNotFoundException(
                "Terminating null byte not found after searching [" + maxLength + "] bytes");
    }

    // at this point, we found a terminating zero
    String result = null;
    if (zeroPos > 0) {
        // read a new byte array
        byte[] bytes = new byte[zeroPos];
        buffer.readBytes(bytes);
        try {
            result = new String(bytes, "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            logger.error("Impossible error", e);
        }
    } else {
        result = "";
    }

    // at this point, we have just one more byte to skip over (the null byte)
    byte b = buffer.readByte();
    if (b != 0x00) {
        logger.error("Impossible error: last byte read SHOULD have been a null byte, but was [" + b + "]");
    }

    return result;
}

From source file:com.cloudhopper.smpp.util.ChannelBufferUtilTest.java

License:Apache License

@Test
public void readNullTerminatedString() throws Exception {
    // normal case with a termination zero
    ByteBuf buffer0 = BufferHelper.createBuffer("343439353133363139323000");
    String str0 = ChannelBufferUtil.readNullTerminatedString(buffer0);
    Assert.assertEquals("44951361920", str0);
    // make sure the entire buffer is still there we started with
    Assert.assertEquals(0, buffer0.readableBytes());

    // another case with an extra byte after NULL byte
    buffer0 = BufferHelper.createBuffer("343439353133363139323000FF");
    str0 = ChannelBufferUtil.readNullTerminatedString(buffer0);
    Assert.assertEquals("44951361920", str0);
    // make sure the entire buffer is still there we started with
    Assert.assertEquals(1, buffer0.readableBytes());

    // another case with an first extra byte
    buffer0 = BufferHelper.createBuffer("39343439353133363139323000");
    buffer0.readByte(); // skip 1 byte
    str0 = ChannelBufferUtil.readNullTerminatedString(buffer0);
    Assert.assertEquals("44951361920", str0);
    // make sure the entire buffer is still there we started with
    Assert.assertEquals(0, buffer0.readableBytes());

    // another case with an first extra byte and last extra byte
    buffer0 = BufferHelper.createBuffer("39343439353133363139323000FF");
    buffer0.readByte(); // skip 1 byte
    str0 = ChannelBufferUtil.readNullTerminatedString(buffer0);
    Assert.assertEquals("44951361920", str0);
    // make sure the entire buffer is still there we started with
    Assert.assertEquals(1, buffer0.readableBytes());

    // another case with an empty string
    buffer0 = BufferHelper.createBuffer("00");
    str0 = ChannelBufferUtil.readNullTerminatedString(buffer0);
    Assert.assertEquals("", str0);
    // make sure the entire buffer is still there we started with
    Assert.assertEquals(0, buffer0.readableBytes());

    // another case with an empty string and last extra byte
    buffer0 = BufferHelper.createBuffer("0039");
    str0 = ChannelBufferUtil.readNullTerminatedString(buffer0);
    Assert.assertEquals("", str0);
    // make sure the entire buffer is still there we started with
    Assert.assertEquals(1, buffer0.readableBytes());

    // no bytes left to read in buffer will return null
    buffer0 = BufferHelper.createBuffer("");
    str0 = ChannelBufferUtil.readNullTerminatedString(buffer0);
    Assert.assertNull(str0);//from   w ww  .  j a v  a2  s  . c  o m
    Assert.assertEquals(0, buffer0.readableBytes());

    // no terminating zero
    try {
        buffer0 = BufferHelper.createBuffer("39");
        str0 = ChannelBufferUtil.readNullTerminatedString(buffer0);
        Assert.fail();
    } catch (TerminatingNullByteNotFoundException e) {
        // correct behavior
        Assert.assertEquals(1, buffer0.readableBytes());
    }

    // unsupported latin-1 chars?
    buffer0 = BufferHelper.createBuffer("0100");
    str0 = ChannelBufferUtil.readNullTerminatedString(buffer0);
    // correct behavior
    Assert.assertEquals(0, buffer0.readableBytes());
}

From source file:com.cloudhopper.smpp.util.ChannelBufferUtilTest.java

License:Apache License

@Test
public void readTlv() throws Exception {
    Tlv tlv0 = null;/* ww  w .  jav a2 s .c o  m*/
    ByteBuf buffer0 = null;

    // a single byte TLV
    buffer0 = BufferHelper.createBuffer("0210000134");
    tlv0 = ChannelBufferUtil.readTlv(buffer0);

    Assert.assertEquals(0, buffer0.readableBytes());
    Assert.assertEquals((short) 0x0210, tlv0.getTag());
    Assert.assertEquals((short) 0x01, tlv0.getLength());
    Assert.assertArrayEquals(new byte[] { 0x34 }, tlv0.getValue());

    // a C-string TLV
    buffer0 = BufferHelper.createBuffer("140200056331657400");
    tlv0 = ChannelBufferUtil.readTlv(buffer0);

    Assert.assertEquals(0, buffer0.readableBytes());
    Assert.assertEquals((short) 0x1402, tlv0.getTag());
    Assert.assertEquals((short) 0x05, tlv0.getLength());
    Assert.assertArrayEquals(HexUtil.toByteArray("6331657400"), tlv0.getValue());

    // a short or just 2 byte TLV
    buffer0 = BufferHelper.createBuffer("02040002ce34");
    tlv0 = ChannelBufferUtil.readTlv(buffer0);

    Assert.assertEquals(0, buffer0.readableBytes());
    Assert.assertEquals((short) 0x0204, tlv0.getTag());
    Assert.assertEquals((short) 0x02, tlv0.getLength());
    Assert.assertArrayEquals(HexUtil.toByteArray("ce34"), tlv0.getValue());

    // a sample message payload TLV
    buffer0 = BufferHelper.createBuffer(
            "0424002f4f4d4720492077616e7420746f207365652022546865204372617a69657322206c6f6f6b73207369636b21203d5d20");
    tlv0 = ChannelBufferUtil.readTlv(buffer0);
    // OMG I want to see "The Crazies" looks sick! =]
    Assert.assertEquals(0, buffer0.readableBytes());
    Assert.assertEquals((short) 0x0424, tlv0.getTag());
    Assert.assertEquals((short) 0x2f, tlv0.getLength());
    // convert bytes to actual chars
    Assert.assertEquals("OMG I want to see \"The Crazies\" looks sick! =] ", new String(tlv0.getValue()));

    // multiple TLVs in a row
    buffer0 = BufferHelper.createBuffer("000e000101000600010104240001");
    tlv0 = ChannelBufferUtil.readTlv(buffer0);
    Assert.assertEquals(9, buffer0.readableBytes());
    Assert.assertEquals((short) 0x0e, tlv0.getTag());
    Assert.assertEquals((short) 0x01, tlv0.getLength());
    Assert.assertArrayEquals(HexUtil.toByteArray("01"), tlv0.getValue());

    tlv0 = ChannelBufferUtil.readTlv(buffer0);
    Assert.assertEquals(4, buffer0.readableBytes());
    Assert.assertEquals((short) 0x06, tlv0.getTag());
    Assert.assertEquals((short) 0x01, tlv0.getLength());
    Assert.assertArrayEquals(HexUtil.toByteArray("01"), tlv0.getValue());

    try {
        // this should error out since we don't have enough bytes
        tlv0 = ChannelBufferUtil.readTlv(buffer0);
        Assert.fail();
    } catch (NotEnoughDataInBufferException e) {
        // correct behavior
        Assert.assertEquals(0, buffer0.readableBytes());
    }

    // a TLV with an unsigned short length (1 above 15-bit integer)
    StringBuilder buf = new StringBuilder(40000);
    buf.append("FFFF8000");
    for (int i = 0; i < 0x8000; i++) {
        buf.append("01");
    }
    buffer0 = BufferHelper.createBuffer(buf.toString());
    tlv0 = ChannelBufferUtil.readTlv(buffer0);
    Assert.assertEquals(0, buffer0.readableBytes());
    Assert.assertEquals((short) 0xffff, tlv0.getTag());
    Assert.assertEquals(32768, tlv0.getUnsignedLength());
    Assert.assertEquals(-32768, tlv0.getLength()); // the "signed" version of the length

    // a TLV with an unsigned short length (1 above 15-bit integer)
    buf = new StringBuilder(70000);
    buf.append("FFFFFFFF");
    for (int i = 0; i < 0xFFFF; i++) {
        buf.append("02");
    }
    buffer0 = BufferHelper.createBuffer(buf.toString());
    tlv0 = ChannelBufferUtil.readTlv(buffer0);
    Assert.assertEquals(0, buffer0.readableBytes());
    Assert.assertEquals((short) 0xffff, tlv0.getTag());
    Assert.assertEquals(-1, tlv0.getLength()); // the "signed" version of the length
}

From source file:com.cloudhopper.smpp.util.ChannelBufferUtilTest.java

License:Apache License

@Test
public void readAddress() throws Exception {
    Address addr0 = null;//from ww  w.  j a  v  a2  s.co m
    ByteBuf buffer0 = null;

    buffer0 = BufferHelper.createBuffer("021000");
    addr0 = ChannelBufferUtil.readAddress(buffer0);
    Assert.assertEquals(0x02, addr0.getTon());
    Assert.assertEquals(0x10, addr0.getNpi());
    Assert.assertEquals("", addr0.getAddress());
    Assert.assertEquals(0, buffer0.readableBytes());

    // same, but one extra byte shouldn't be read
    buffer0 = BufferHelper.createBuffer("02100000");
    addr0 = ChannelBufferUtil.readAddress(buffer0);
    Assert.assertEquals(0x02, addr0.getTon());
    Assert.assertEquals(0x10, addr0.getNpi());
    Assert.assertEquals("", addr0.getAddress());
    Assert.assertEquals(1, buffer0.readableBytes());

    buffer0 = BufferHelper.createBuffer("02104142434400");
    addr0 = ChannelBufferUtil.readAddress(buffer0);
    Assert.assertEquals(0x02, addr0.getTon());
    Assert.assertEquals(0x10, addr0.getNpi());
    Assert.assertEquals("ABCD", addr0.getAddress());
    Assert.assertEquals(0, buffer0.readableBytes());
}

From source file:com.cmz.http.upload.HttpUploadServerHandler.java

License:Apache License

private void writeResponse(Channel channel) {
    // Convert the response content to a ChannelBuffer.
    ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
    responseContent.setLength(0);//from  www  .j a va2s .  c  o  m

    // Decide whether to close the connection or not.
    boolean close = request.headers().contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE, true)
            || request.protocolVersion().equals(HttpVersion.HTTP_1_0) && !request.headers()
                    .contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE, true);

    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (!close) {
        // There's no need to add 'Content-Length' header
        // if this is the last response.
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());
    }

    Set<Cookie> cookies;
    String value = request.headers().get(HttpHeaderNames.COOKIE);
    if (value == null) {
        cookies = Collections.emptySet();
    } else {
        cookies = ServerCookieDecoder.STRICT.decode(value);
    }
    if (!cookies.isEmpty()) {
        // Reset the cookies if necessary.
        for (Cookie cookie : cookies) {
            response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
        }
    }
    // Write the response.
    ChannelFuture future = channel.writeAndFlush(response);
    // Close the connection after the write operation is done if necessary.
    if (close) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.cmz.http.upload.HttpUploadServerHandler.java

License:Apache License

private void writeMenu(ChannelHandlerContext ctx) {
    // print several HTML forms
    // Convert the response content to a ChannelBuffer.
    responseContent.setLength(0);//  w w w.j  a va2  s.co  m

    // create Pseudo Menu
    responseContent.append("<html>");
    responseContent.append("<head>");
    responseContent.append("<title>Netty Test Form</title>\r\n");
    responseContent.append("</head>\r\n");
    responseContent.append("<body bgcolor=white><style>td{font-size: 12pt;}</style>");

    responseContent.append("<table border=\"0\">");
    responseContent.append("<tr>");
    responseContent.append("<td>");
    responseContent.append("<h1>Netty Test Form</h1>");
    responseContent.append("Choose one FORM");
    responseContent.append("</td>");
    responseContent.append("</tr>");
    responseContent.append("</table>\r\n");

    // GET
    responseContent.append("<CENTER>GET FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");
    responseContent.append("<FORM ACTION=\"/formget\" METHOD=\"GET\">");
    responseContent.append("<input type=hidden name=getform value=\"GET\">");
    responseContent.append("<table border=\"0\">");
    responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"info\" size=10></td></tr>");
    responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"secondinfo\" size=20>");
    responseContent
            .append("<tr><td>Fill with value: <br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>");
    responseContent.append("</td></tr>");
    responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>");
    responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>");
    responseContent.append("</table></FORM>\r\n");
    responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");

    // POST
    responseContent.append("<CENTER>POST FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");
    responseContent.append("<FORM ACTION=\"/formpost\" METHOD=\"POST\">");
    responseContent.append("<input type=hidden name=getform value=\"POST\">");
    responseContent.append("<table border=\"0\">");
    responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"info\" size=10></td></tr>");
    responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"secondinfo\" size=20>");
    responseContent
            .append("<tr><td>Fill with value: <br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>");
    responseContent.append("<tr><td>Fill with file (only file name will be transmitted): <br> "
            + "<input type=file name=\"myfile\">");
    responseContent.append("</td></tr>");
    responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>");
    responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>");
    responseContent.append("</table></FORM>\r\n");
    responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");

    // POST with enctype="multipart/form-data"
    responseContent.append("<CENTER>POST MULTIPART FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");
    responseContent
            .append("<FORM ACTION=\"/formpostmultipart\" ENCTYPE=\"multipart/form-data\" METHOD=\"POST\">");
    responseContent.append("<input type=hidden name=getform value=\"POST\">");
    responseContent.append("<table border=\"0\">");
    responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"info\" size=10></td></tr>");
    responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"secondinfo\" size=20>");
    responseContent
            .append("<tr><td>Fill with value: <br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>");
    responseContent.append("<tr><td>Fill with file: <br> <input type=file name=\"myfile\">");
    responseContent.append("</td></tr>");
    responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>");
    responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>");
    responseContent.append("</table></FORM>\r\n");
    responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");

    responseContent.append("</body>");
    responseContent.append("</html>");

    ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);

    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
    response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());

    // Write the response.
    ctx.channel().writeAndFlush(response);
}

From source file:com.cmz.http.websocketx.benchmarkserver.WebSocketServerHandler.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
    // Handle a bad request.
    if (!req.decoderResult().isSuccess()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;//w w  w. j av a2s. c  o  m
    }

    // Allow only GET methods.
    if (req.method() != GET) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }

    // Send the demo page and favicon.ico
    if ("/".equals(req.uri())) {
        ByteBuf content = WebSocketServerBenchmarkPage.getContent(getWebSocketLocation(req));
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);

        res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
        HttpUtil.setContentLength(res, content.readableBytes());

        sendHttpResponse(ctx, req, res);
        return;
    }
    if ("/favicon.ico".equals(req.uri())) {
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
        sendHttpResponse(ctx, req, res);
        return;
    }

    // Handshake
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
            null, true, 5 * 1024 * 1024);
    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), req);
    }
}