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.smart.fulfilcamel.hxServerInitialFactory.java

@Override
protected void initChannel(Channel ch) throws Exception {
    ChannelPipeline channelPipeline = ch.pipeline();

    channelPipeline.addLast("encoder-SD", new StringEncoder(CharsetUtil.UTF_8));
    channelPipeline.addLast("decoder-DELIM",
            new DelimiterBasedFrameDecoder(maxLineSize, true, Delimiters.lineDelimiter()));
    channelPipeline.addLast("decoder-SD", new StringDecoder(CharsetUtil.UTF_8));
    // here we add the default Camel ServerChannelHandler for the consumer, to allow Camel to route the message etc.
    channelPipeline.addLast("handler", new ServerChannelHandler(consumer));
}

From source file:com.snowcattle.game.net.client.websocket.GameWebSocketClientHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();// ww w.j  a  va  2s  . co m
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        System.out.println("WebSocket Client connected!");
        handshakeFuture.setSuccess();

        sendTestMessage(ctx);

        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.status()
                + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
    }

    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        System.out.println("WebSocket Client received message: " + textFrame.text());
    } else if (frame instanceof PongWebSocketFrame) {
        System.out.println("WebSocket Client received pong");
    } else if (frame instanceof CloseWebSocketFrame) {
        System.out.println("WebSocket Client received closing");
        ch.close();
    } else if (frame instanceof BinaryWebSocketFrame) {
        System.out.println("WebSocket Client received binary");
        BinaryWebSocketFrame binaryWebSocketFrame = (BinaryWebSocketFrame) frame;
        ByteBuf byteBuf = binaryWebSocketFrame.content();

        AbstractNetProtoBufMessage netProtoBufMessage = null;
        //?
        NetProtoBufTcpMessageDecoderFactory netProtoBufTcpMessageDecoderFactory = new NetProtoBufTcpMessageDecoderFactory();
        try {
            netProtoBufMessage = netProtoBufTcpMessageDecoderFactory.praseMessage(byteBuf);
        } catch (CodecException e) {
            e.printStackTrace();
        }

        if (netProtoBufMessage instanceof OnlineLoginServerTcpMessage) {
            OnlineLoginServerTcpMessage onlineLoginServerTcpMessage = (OnlineLoginServerTcpMessage) netProtoBufMessage;
            System.out.println("playerId:" + onlineLoginServerTcpMessage.getPlayerId());
        }

        //????
        Thread.sleep(1000L);
        sendTestMessage(ctx);
    }
}

From source file:com.sohu.jafka.http.HttpServerHandler.java

License:Apache License

private boolean writeResponse(ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpHeaders.isKeepAlive(request);
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,
            Unpooled.copiedBuffer("OK", CharsetUtil.UTF_8));

    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        // Add keep alive header as per:
        // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }/*from   ww  w.  j  a  v  a2s.c o m*/

    // Write the response.
    ctx.write(response);

    return keepAlive;
}

From source file:com.sohu.jafka.http.HttpServerHandler.java

License:Apache License

private static void sendStatusMessage(ChannelHandlerContext ctx, HttpResponseStatus status, String msg) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status,
            Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8));
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    ctx.writeAndFlush(response);/*from   w  ww .  j  a  v  a 2 s.  c  om*/
    ctx.close();
}

From source file:com.spotify.ffwd.carbon.CarbonLineServer.java

License:Apache License

@Override
public ChannelInitializer<Channel> initializer() {
    return new ChannelInitializer<Channel>() {
        @Override/*from w w  w. j  a  v  a 2  s. c o  m*/
        protected void initChannel(final Channel ch) throws Exception {
            ch.pipeline().addLast(new LineBasedFrameDecoder(MAX_LINE));
            ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
            ch.pipeline().addLast(decoder, handler);
        }
    };
}

From source file:com.spring.cloud.study.websocket.WebSocketForwardClientHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();/*from   w  ww.  ja v  a  2 s  .c o m*/
    if (!handshaker.isHandshakeComplete()) {
        try {
            handshaker.finishHandshake(ch, (FullHttpResponse) msg);
            handshakeFuture.setSuccess();
        } catch (WebSocketHandshakeException e) {
            LOGGER.info("WebSocket Client failed to connect");
            handshakeFuture.setFailure(e);
        }
        return;
    }
    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.status()
                + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
    }
    WebSocketFrame frame = (WebSocketFrame) msg;
    webSocketSession.sendMessage(new TextMessage(ByteBufUtil.getBytes(convertMessage(frame))));
}

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);//  ww  w .  j a v  a2  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.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.springapp.mvc.netty.example.spdy.client.HttpResponseClientHandler.java

License:Apache License

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

        System.out.println("STATUS: " + response.getStatus());
        System.out.println("VERSION: " + response.getProtocolVersion());
        System.out.println();//w  w w.java  2 s  . c om

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

        if (HttpHeaders.isTransferEncodingChunked(response)) {
            System.out.println("CHUNKED CONTENT {");
        } else {
            System.out.println("CONTENT {");
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;

        System.out.print(content.content().toString(CharsetUtil.UTF_8));
        System.out.flush();

        if (content instanceof LastHttpContent) {
            System.out.println("} END OF CONTENT");
            queue.add(ctx.channel().newSucceededFuture());
        }
    }
}

From source file:com.springapp.mvc.netty.example.spdy.server.SpdyServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;

        if (is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }/* w  ww  .j a  v  a 2s .co  m*/
        boolean keepAlive = isKeepAlive(req);

        ByteBuf content = Unpooled.copiedBuffer("Hello World " + new Date(), CharsetUtil.UTF_8);

        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
        response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
        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);
        }
    }
}

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  a va  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();
    }
}