Example usage for io.netty.util CharsetUtil UTF_8

List of usage examples for io.netty.util CharsetUtil UTF_8

Introduction

In this page you can find the example usage for io.netty.util CharsetUtil UTF_8.

Prototype

Charset UTF_8

To view the source code for io.netty.util CharsetUtil UTF_8.

Click Source Link

Document

8-bit UTF (UCS Transformation Format)

Usage

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");
    }/*from w ww .j  ava 2  s .co 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.ottogroup.bi.asap.server.emitter.kafka.KafkaTopicPartitionConsumer.java

License:Apache License

/**
 * @see java.lang.Runnable#run()//  w w w.  j a  va2s  . com
 */
public void run() {

    ConsumerIterator<byte[], byte[]> topicPartitionStreamIterator = this.kafkaTopicPartitionStream.iterator();

    this.running = true;
    // ensure that the partition iterator still has some elements left and the receiving
    // web socket producer still wants more
    while (running) {
        if (topicPartitionStreamIterator.hasNext()) {
            // next message must neither be null nor empty
            MessageAndMetadata<byte[], byte[]> message = topicPartitionStreamIterator.next();
            if (message != null && message.message() != null && message.message().length > 0) {
                // try to convert the content into a UTF-8 encoded string
                String messageContent = new String(message.message(), CharsetUtil.UTF_8);

                // return only if the message is not empty or blank
                // as we do not transport sender references it is forwarded with a reference to a dead letter box
                if (StringUtils.isNotBlank(messageContent)) {
                    messages.add(new StreamingDataMessage(origin, messageContent, System.currentTimeMillis()));
                }
            }
        } else {
            Thread.yield();
            // TODO wait strategy
        }
    }
}

From source file:com.ottogroup.bi.spqr.websocket.server.SPQRWebSocketServerHandler.java

License:Apache License

/** 
 * Sends a {@link HttpResponse} according to prepared {@link FullHttpResponse} to the client. The 
 * code was copied from netty.io websocket server example. The origins may be found at:
 * {@linkplain https://github.com/netty/netty/blob/4.0/example/src/main/java/io/netty/example/http/websocketx/server/WebSocketServerHandler.java} 
 * @param ctx/*from  ww w.  ja v a 2  s. com*/
 * @param req
 * @param res
 */
private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        HttpHeaders.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

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);/*from w w w  .  j  ava2s  .co m*/
        }

        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.nio.http.upload.HttpUploadClientHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, HttpObject msg) {
    if (msg instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) msg;

        System.err.println("STATUS: " + response.status());
        System.err.println("VERSION: " + response.protocolVersion());

        if (!response.headers().isEmpty()) {
            for (CharSequence name : response.headers().names()) {
                for (CharSequence value : response.headers().getAll(name)) {
                    System.err.println("HEADER: " + name + " = " + value);
                }/*from   w ww  . j  ava  2 s.  c o  m*/
            }
        }

        if (response.status().code() == 200 && HttpHeaderUtil.isTransferEncodingChunked(response)) {
            readingChunks = true;
            System.err.println("CHUNKED CONTENT {");
        } else {
            System.err.println("CONTENT {");
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent chunk = (HttpContent) msg;
        System.err.println(chunk.content().toString(CharsetUtil.UTF_8));

        if (chunk instanceof LastHttpContent) {
            if (readingChunks) {
                System.err.println("} END OF CHUNKED CONTENT");
            } else {
                System.err.println("} END OF CONTENT");
            }
            readingChunks = false;
        } else {
            System.err.println(chunk.content().toString(CharsetUtil.UTF_8));
        }
    }
}

From source file:com.phei.netty.nio.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);// w  w w .  j  a v  a2s.c om

    // 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().getAndConvert(HttpHeaderNames.COOKIE);
    if (value == null) {
        cookies = Collections.emptySet();
    } else {
        cookies = ServerCookieDecoder.decode(value);
    }
    if (!cookies.isEmpty()) {
        // Reset the cookies if necessary.
        for (Cookie cookie : cookies) {
            response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.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.phei.netty.protocol.http.xml.codec.HttpXmlRequestDecoder.java

License:Apache License

private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    //??//  ww  w  . j ava2 s .  c  o m
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status,
            Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.pokersu.server.WebSocketServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);/*from w  ww  .j  a v a  2 s  .com*/
        buf.release();
        //            HttpUtil.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (/*!HttpUtil.isKeepAlive(req) || */ res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.qq.servlet.demo.netty.sample.http.helloworld.HttpHelloWorldClientHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    System.out.println(msg);/*from ww w. ja va  2s  .co m*/
    if (msg instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) msg;

        logger.info("STATUS: " + response.getStatus());
        logger.info("VERSION: " + response.getProtocolVersion());

        if (!response.headers().isEmpty()) {
            for (String name : response.headers().names()) {
                for (String value : response.headers().getAll(name)) {
                    logger.info("HEADER: " + name + " = " + value);
                }
            }
        }

        if (response.getStatus().code() == 200 && HttpHeaders.isTransferEncodingChunked(response)) {
            readingChunks = true;
            logger.info("CHUNKED CONTENT {");
        } else {
            logger.info("CONTENT {");
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent chunk = (HttpContent) msg;
        logger.info(chunk.content().toString(CharsetUtil.UTF_8));

        System.out.println(chunk.content().toString(CharsetUtil.UTF_8));

        if (chunk instanceof LastHttpContent) {
            if (readingChunks) {
                logger.info("} END OF CHUNKED CONTENT");
            } else {
                logger.info("} END OF CONTENT");
            }
            readingChunks = false;
        } else {
            logger.info(chunk.content().toString(CharsetUtil.UTF_8));
        }
    }
}

From source file:com.qq.servlet.demo.netty.sample.http.helloworld.HttpHelloWorldServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    System.out.println(msg);/*from   w ww.  j  a  v a 2s . com*/
    System.out.println("\n\n\n\n============" + msg.getClass().getName() + "=================\n\n\n");
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        String uri = req.getUri();
        System.out.println("uri--->>>" + uri);
        if (is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }
        boolean keepAlive = isKeepAlive(req);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,
                Unpooled.wrappedBuffer("".getBytes()));
        response.headers().set(CONTENT_TYPE, "text/plain");
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    } else if (msg instanceof DefaultLastHttpContent) {
        DefaultLastHttpContent httpContent = (DefaultLastHttpContent) msg;
        String body = httpContent.content().toString(CharsetUtil.UTF_8);
        System.out.println("body===>>> " + body);
    }
}