Example usage for io.netty.buffer ByteBuf toString

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

Introduction

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

Prototype

public abstract String toString(Charset charset);

Source Link

Document

Decodes this buffer's readable bytes into a string with the specified character set name.

Usage

From source file:com.ogarproject.ogar.server.net.packet.Packet.java

License:Open Source License

public static String readUTF8(ByteBuf in) {
    ByteBuf buffer = in.alloc().buffer();
    byte b;//w w w  . j  a va 2 s  . c  o m
    while (in.readableBytes() > 0 && (b = in.readByte()) != 0) {
        buffer.writeByte(b);
    }

    return buffer.toString(Charsets.UTF_8);
}

From source file:com.ogarproject.ogar.server.net.packet.Packet.java

License:Open Source License

public static String readUTF16(ByteBuf in) {
    in = in.order(ByteOrder.BIG_ENDIAN);
    ByteBuf buffer = in.alloc().buffer();
    char chr;/*w ww  .jav a 2 s  .co  m*/
    while (in.readableBytes() > 1 && (chr = in.readChar()) != 0) {
        buffer.writeChar(chr);
    }

    return buffer.toString(Charsets.UTF_16LE);
}

From source file:com.otcdlink.chiron.downend.Http11ProxyHandler.java

License:Apache License

public Http11ProxyHandler(SocketAddress proxyAddress, String username, String password) {
    super(proxyAddress);
    if (username == null) {
        throw new NullPointerException("username");
    }//w w w . j av  a 2  s  . c o m
    if (password == null) {
        throw new NullPointerException("password");
    }
    this.username = username;
    this.password = password;

    ByteBuf authz = Unpooled.copiedBuffer(username + ':' + password, CharsetUtil.UTF_8);
    ByteBuf authzBase64 = Base64.encode(authz, false);

    authorization = new AsciiString("Basic " + authzBase64.toString(CharsetUtil.US_ASCII));

    authz.release();
    authzBase64.release();
}

From source file:com.phei.netty.nio.http.snoop.HttpSnoopServerHandler.java

License:Apache License

@Override
protected void messageReceived(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;

        if (HttpHeaderUtil.is100ContinueExpected(request)) {
            send100Continue(ctx);//w w  w . java2 s.c  om
        }

        buf.setLength(0);
        buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        buf.append("===================================\r\n");

        buf.append("VERSION: ").append(request.protocolVersion()).append("\r\n");
        buf.append("HOSTNAME: ").append(request.headers().get(HOST, "unknown")).append("\r\n");
        buf.append("REQUEST_URI: ").append(request.uri()).append("\r\n\r\n");

        HttpHeaders headers = request.headers();
        if (!headers.isEmpty()) {
            for (Entry<CharSequence, CharSequence> h : headers) {
                CharSequence key = h.getKey();
                CharSequence value = h.getValue();
                buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n");
            }
            buf.append("\r\n");
        }

        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
        Map<String, List<String>> params = queryStringDecoder.parameters();
        if (!params.isEmpty()) {
            for (Entry<String, List<String>> p : params.entrySet()) {
                String key = p.getKey();
                List<String> vals = p.getValue();
                for (String val : vals) {
                    buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n");
                }
            }
            buf.append("\r\n");
        }

        appendDecoderResult(buf, request);
    }

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            buf.append("CONTENT: ");
            buf.append(content.toString(CharsetUtil.UTF_8));
            buf.append("\r\n");
            appendDecoderResult(buf, request);
        }

        if (msg instanceof LastHttpContent) {
            buf.append("END OF CONTENT\r\n");

            LastHttpContent trailer = (LastHttpContent) msg;
            if (!trailer.trailingHeaders().isEmpty()) {
                buf.append("\r\n");
                for (CharSequence name : trailer.trailingHeaders().names()) {
                    for (CharSequence value : trailer.trailingHeaders().getAll(name)) {
                        buf.append("TRAILING HEADER: ");
                        buf.append(name).append(" = ").append(value).append("\r\n");
                    }
                }
                buf.append("\r\n");
            }

            if (!writeResponse(trailer, ctx)) {
                // If keep-alive is off, close the connection once the content is fully written.
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }
}

From source file:com.phei.netty.protocol.http.xml.codec.AbstractHttpXmlDecoder.java

License:Apache License

protected Object decode0(ChannelHandlerContext arg0, ByteBuf body) throws Exception {
    //jibx??XML???
    factory = BindingDirectory.getFactory(clazz);
    String content = body.toString(UTF_8);
    if (isPrint)/*from w  w w.j  a va 2  s .  c  o  m*/
        System.out.println("The body is : " + content);
    reader = new StringReader(content);
    IUnmarshallingContext uctx = factory.createUnmarshallingContext();
    Object result = uctx.unmarshalDocument(reader);
    reader.close();
    reader = null;
    return result;
}

From source file:com.springapp.mvc.netty.example.http.snoop.HttpSnoopServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;

        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);/*from ww w .  j ava  2 s.c o m*/
        }

        buf.setLength(0);
        buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        buf.append("===================================\r\n");

        buf.append("VERSION: ").append(request.getProtocolVersion()).append("\r\n");
        buf.append("HOSTNAME: ").append(HttpHeaders.getHost(request, "unknown")).append("\r\n");
        buf.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n");

        HttpHeaders headers = request.headers();
        if (!headers.isEmpty()) {
            for (Entry<String, String> h : headers) {
                String key = h.getKey();
                String value = h.getValue();
                buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n");
            }
            buf.append("\r\n");
        }

        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
        Map<String, List<String>> params = queryStringDecoder.parameters();
        if (!params.isEmpty()) {
            for (Entry<String, List<String>> p : params.entrySet()) {
                String key = p.getKey();
                List<String> vals = p.getValue();
                for (String val : vals) {
                    buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n");
                }
            }
            buf.append("\r\n");
        }

        appendDecoderResult(buf, request);
    }

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            buf.append("CONTENT: ");
            buf.append(content.toString(CharsetUtil.UTF_8));
            buf.append("\r\n");
            appendDecoderResult(buf, request);
        }

        if (msg instanceof LastHttpContent) {
            buf.append("END OF CONTENT\r\n");

            LastHttpContent trailer = (LastHttpContent) msg;
            if (!trailer.trailingHeaders().isEmpty()) {
                buf.append("\r\n");
                for (String name : trailer.trailingHeaders().names()) {
                    for (String value : trailer.trailingHeaders().getAll(name)) {
                        buf.append("TRAILING HEADER: ");
                        buf.append(name).append(" = ").append(value).append("\r\n");
                    }
                }
                buf.append("\r\n");
            }

            if (!writeResponse(trailer, ctx)) {
                // If keep-alive is off, close the connection once the content is fully written.
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }
}

From source file:com.srotya.sidewinder.core.ingress.http.HTTPDataPointDecoder.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    try {/*  w w w . j  ava  2s  .  c o  m*/
        if (msg instanceof HttpRequest) {
            HttpRequest request = this.request = (HttpRequest) msg;
            if (HttpUtil.is100ContinueExpected(request)) {
                send100Continue(ctx);
            }

            QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
            path = queryStringDecoder.path();

            Map<String, List<String>> params = queryStringDecoder.parameters();
            if (!params.isEmpty()) {
                for (Entry<String, List<String>> p : params.entrySet()) {
                    String key = p.getKey();
                    if (key.equalsIgnoreCase("db")) {
                        dbName = p.getValue().get(0);
                    }
                }
            }

            if (path != null && path.contains("query")) {
                Gson gson = new Gson();
                JsonObject obj = new JsonObject();
                JsonArray ary = new JsonArray();
                ary.add(new JsonObject());
                obj.add("results", ary);
                responseString.append(gson.toJson(obj));
            }
        }

        if (msg instanceof HttpContent) {
            HttpContent httpContent = (HttpContent) msg;
            ByteBuf byteBuf = httpContent.content();
            if (byteBuf.isReadable()) {
                requestBuffer.append(byteBuf.toString(CharsetUtil.UTF_8));
            }

            if (msg instanceof LastHttpContent) {
                // LastHttpContent lastHttpContent = (LastHttpContent) msg;
                // if (!lastHttpContent.trailingHeaders().isEmpty()) {
                // }

                if (dbName == null) {
                    responseString.append("Invalid database null");
                    logger.severe("Invalid database null");
                } else {
                    String payload = requestBuffer.toString();
                    logger.fine("Request:" + payload);
                    List<DataPoint> dps = dataPointsFromString(dbName, payload);
                    for (DataPoint dp : dps) {
                        try {
                            engine.writeDataPoint(dp);
                            logger.fine("Accepted:" + dp + "\t" + new Date(dp.getTimestamp()));
                        } catch (IOException e) {
                            logger.fine("Dropped:" + dp + "\t" + e.getMessage());
                            responseString.append("Dropped:" + dp);
                        }
                    }
                }
                if (writeResponse(request, ctx)) {
                    ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.streamsets.pipeline.lib.parser.net.syslog.SyslogDecoder.java

License:Apache License

public void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out, InetSocketAddress recipient,
        InetSocketAddress sender) throws OnRecordErrorException {
    if (ctx != null) {
        if (sender == null) {
            SocketAddress socketAddress = ctx.channel().remoteAddress();
            if (socketAddress instanceof InetSocketAddress) {
                sender = (InetSocketAddress) socketAddress;
            }/*from  w w  w  .  jav  a2 s . c  o  m*/
        }
        if (recipient == null) {
            SocketAddress socketAddress = ctx.channel().localAddress();
            if (socketAddress instanceof InetSocketAddress) {
                recipient = (InetSocketAddress) socketAddress;
            }
        }
    }

    final SyslogMessage syslogMsg = new SyslogMessage();
    if (sender != null) {
        String senderHost = resolveHostAddressString(sender);
        syslogMsg.setSenderHost(senderHost);
        syslogMsg.setSenderAddress(resolveAddressString(senderHost, sender));
        syslogMsg.setSenderPort(sender.getPort());
    }
    final String msg = buf.toString(charset);
    int msgLen = msg.length();
    int curPos = 0;
    syslogMsg.setRawMessage(msg);
    if (msg.charAt(curPos) != '<') {
        throw new OnRecordErrorException(Errors.SYSLOG_01, "cannot find open bracket '<'", msg);
    }
    int endBracketPos = msg.indexOf('>');
    if (endBracketPos <= 0 || endBracketPos > 6) {
        throw new OnRecordErrorException(Errors.SYSLOG_01, "cannot find end bracket '>'", msg);
    }
    String priority = msg.substring(1, endBracketPos);
    int pri;
    try {
        pri = Integer.parseInt(priority);
    } catch (NumberFormatException nfe) {
        throw new OnRecordErrorException(Errors.SYSLOG_01, nfe, msg, nfe);
    }
    int facility = pri / 8;
    int severity = pri % 8;

    // Remember priority
    syslogMsg.setPriority(pri);

    // put fac / sev into header
    syslogMsg.setFacility(facility);
    syslogMsg.setSeverity(severity);

    if (msgLen <= endBracketPos + 1) {
        throw new OnRecordErrorException(Errors.SYSLOG_02, msg);
    }
    // update parsing position
    curPos = endBracketPos + 1;

    // remember version string
    if (msgLen > curPos + 2 && "1 ".equals(msg.substring(curPos, curPos + 2))) {
        // this is curious, I guess the code above matches 1 exactly because
        // there has not been another version.
        syslogMsg.setSyslogVersion(1);
        curPos += 2;
    }

    // now parse timestamp (handle different varieties)
    long ts;
    String tsString;
    char dateStartChar = msg.charAt(curPos);
    while (dateStartChar == ' ' && curPos < msgLen - 1) {
        // consume any spaces immediately after PRI
        dateStartChar = msg.charAt(++curPos);
    }

    // no timestamp specified; use relay current time
    if (dateStartChar == '-') {
        ts = clock.millis();
        if (msgLen <= curPos + 2) {
            throw new OnRecordErrorException(Errors.SYSLOG_03, msg);
        }
        curPos += 2; // assume we skip past a space to get to the hostname
        // rfc3164 timestamp
    } else if (dateStartChar >= 'A' && dateStartChar <= 'Z') {
        if (msgLen <= curPos + RFC3164_LEN) {
            throw new OnRecordErrorException(Errors.SYSLOG_04, msg);
        }
        tsString = msg.substring(curPos, curPos + RFC3164_LEN);
        ts = parseRfc3164Time(tsString);
        curPos += RFC3164_LEN + 1;
        // rfc 5424 timestamp
    } else {
        int nextSpace = msg.indexOf(' ', curPos);
        if (nextSpace == -1) {
            throw new OnRecordErrorException(Errors.SYSLOG_04, msg);
        }
        tsString = msg.substring(curPos, nextSpace);
        ts = parseRfc5424Date(tsString);
        curPos = nextSpace + 1;
    }
    syslogMsg.setTimestamp(ts);
    // parse out hostname
    int nextSpace = msg.indexOf(' ', curPos);
    if (nextSpace == -1) {
        throw new OnRecordErrorException(Errors.SYSLOG_03, msg);
    }
    String host = msg.substring(curPos, nextSpace);
    syslogMsg.setHost(host);
    if (msgLen > nextSpace + 1) {
        curPos = nextSpace + 1;
        syslogMsg.setRemainingMessage(msg.substring(curPos));
    } else {
        syslogMsg.setRemainingMessage("");
    }
    if (recipient != null) {
        String receiverHost = resolveHostAddressString(recipient);
        syslogMsg.setReceiverHost(receiverHost);
        syslogMsg.setReceiverAddress(resolveAddressString(receiverHost, recipient));
        syslogMsg.setReceiverPort(recipient.getPort());
    }
    out.add(syslogMsg);
    // consume the buffer that was just read (as an entire String)
    buf.skipBytes(buf.readableBytes());
}

From source file:com.streamsets.pipeline.lib.parser.net.TestDelimitedLengthFieldBasedFrameDecoder.java

License:Apache License

private void writeStringAndAssert(EmbeddedChannel channel, String value, Charset charset,
        boolean randomlyPartition, boolean expectFrameTooLarge) {
    String frame = makeFrame(value, charset);

    try {//from  ww  w.  j  a  v a2s . c  o  m
        if (randomlyPartition) {
            for (List<Byte> chunk : getRandomByteSlices(frame.getBytes())) {
                channel.writeInbound(Unpooled.copiedBuffer(Bytes.toArray(chunk)));
            }
        } else {
            channel.writeInbound(Unpooled.copiedBuffer(frame, charset));
        }
    } catch (TooLongFrameException e) {
        if (!expectFrameTooLarge) {
            Assert.fail("TooLongFrameException unexpectedly thrown");
        } else {
            Assert.assertNull(channel.readInbound());
        }
    }
    if (!expectFrameTooLarge) {
        ByteBuf in = (ByteBuf) channel.readInbound();
        Assert.assertEquals(value, in.toString(charset));
        in.release();
    }
}

From source file:com.streamsets.pipeline.lib.parser.syslog.SyslogParser.java

License:Apache License

@Override
public List<Record> parse(ByteBuf buf, InetSocketAddress recipient, InetSocketAddress sender)
        throws OnRecordErrorException {
    Map<String, Field> fields = new HashMap<>();
    final String msg = buf.toString(charset);
    int msgLen = msg.length();
    int curPos = 0;
    fields.put(RAW, Field.create(msg));
    if (msg.charAt(curPos) != '<') {
        throw new OnRecordErrorException(Errors.SYSLOG_01, "cannot find open bracket '<'", msg);
    }/*from www.j av a  2 s . c  om*/
    int endBracketPos = msg.indexOf('>');
    if (endBracketPos <= 0 || endBracketPos > 6) {
        throw new OnRecordErrorException(Errors.SYSLOG_01, "cannot find end bracket '>'", msg);
    }
    String priority = msg.substring(1, endBracketPos);
    int pri;
    try {
        pri = Integer.parseInt(priority);
    } catch (NumberFormatException nfe) {
        throw new OnRecordErrorException(Errors.SYSLOG_01, nfe, msg, nfe);
    }
    int facility = pri / 8;
    int severity = pri % 8;

    // Remember priority
    fields.put(SYSLOG_PRIORITY, Field.create(priority));

    // put fac / sev into header
    fields.put(SYSLOG_FACILITY, Field.create(facility));
    fields.put(SYSLOG_SEVERITY, Field.create(severity));

    if (msgLen <= endBracketPos + 1) {
        throw new OnRecordErrorException(Errors.SYSLOG_02, msg);
    }
    // update parsing position
    curPos = endBracketPos + 1;

    // remember version string
    if (msgLen > curPos + 2 && "1 ".equals(msg.substring(curPos, curPos + 2))) {
        // this is curious, I guess the code above matches 1 exactly because
        // there has not been another version.
        fields.put(SYSLOG_VERSION, SYSLOG_VERSION1);
        curPos += 2;
    }

    // now parse timestamp (handle different varieties)
    long ts;
    String tsString;
    char dateStartChar = msg.charAt(curPos);

    // no timestamp specified; use relay current time
    if (dateStartChar == '-') {
        tsString = Character.toString(dateStartChar);
        ts = System.currentTimeMillis();
        if (msgLen <= curPos + 2) {
            throw new OnRecordErrorException(Errors.SYSLOG_03, msg);
        }
        curPos += 2; // assume we skip past a space to get to the hostname
        // rfc3164 timestamp
    } else if (dateStartChar >= 'A' && dateStartChar <= 'Z') {
        if (msgLen <= curPos + RFC3164_LEN) {
            throw new OnRecordErrorException(Errors.SYSLOG_04, msg);
        }
        tsString = msg.substring(curPos, curPos + RFC3164_LEN);
        ts = parseRfc3164Time(tsString);
        curPos += RFC3164_LEN + 1;
        // rfc 5424 timestamp
    } else {
        int nextSpace = msg.indexOf(' ', curPos);
        if (nextSpace == -1) {
            throw new OnRecordErrorException(Errors.SYSLOG_04, msg);
        }
        tsString = msg.substring(curPos, nextSpace);
        ts = parseRfc5424Date(tsString);
        curPos = nextSpace + 1;
    }
    fields.put(TIMESTAMP, Field.create(ts));
    // parse out hostname
    int nextSpace = msg.indexOf(' ', curPos);
    if (nextSpace == -1) {
        throw new OnRecordErrorException(Errors.SYSLOG_03, msg);
    }
    fields.put(HOST, Field.create(msg.substring(curPos, nextSpace)));
    if (msgLen > nextSpace + 1) {
        curPos = nextSpace + 1;
        fields.put(REMAINING, Field.create(msg.substring(curPos)));
    } else {
        fields.put(REMAINING, EMPTY_STRING);
    }
    String receiverHost = recipient.getHostString();
    if (receiverHost == null) {
        receiverHost = recipient.toString();
    }
    Field receiverAddr = Field.create(receiverHost + ":" + recipient.getPort());
    fields.put(RECEIVER_ADDR, receiverAddr);
    fields.put(RECEIVER_PORT, Field.create(recipient.getPort()));
    String senderHost = sender.getHostString();
    if (senderHost == null) {
        senderHost = sender.toString();
    }
    Field senderAddr = Field.create(senderHost + ":" + sender.getPort());
    fields.put(SENDER_ADDR, senderAddr);
    fields.put(SENDER_PORT, Field.create(sender.getPort()));
    Record record = context.createRecord(senderAddr.getValueAsString() + "::" + recordId++);
    record.set(Field.create(fields));
    return Arrays.asList(record);
}