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.netthreads.audio.note.service.NoteBuilderHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
    String response = msg.data().toString(CharsetUtil.UTF_8);
    System.out.println(response.substring(6));
    ctx.close();//from ww  w  .  j  a  v  a 2s  . c om
}

From source file:com.netty.BaseHttpServerHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof FullHttpRequest) {
        FullHttpRequest request = (FullHttpRequest) msg;
        //            HttpPostRequestDecoder httpPostRequestDecoder = new HttpPostRequestDecoder(request);

        if (HttpHeaders.is100ContinueExpected(request)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }// w w w .  j av a 2s .  c  o m
        boolean keepAlive = HttpHeaders.isKeepAlive(request);
        ///////////////
        FullHttpResponse response = handleRequest(request.getUri(),
                request.content().toString(CharsetUtil.UTF_8), request);

        ////////////

        //            final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
        //            response.headers().set(CONTENT_TYPE, "text/plain");
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        ctx.write(response);
        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            //                ctx.executor().submit(new Runnable() {
            //                    @Override
            //                    public void run() {
            ctx.write(response);
            //                    }
            //                });

        }
    }
}

From source file:com.netty.file.HttpUploadServerHandler.java

License:Apache License

private void writeMenu(ChannelHandlerContext ctx) {
    // print several HTML forms
    // Convert the response content to a ChannelBuffer.
    responseContent.setLength(0);//from w  w w .  j  av  a 2 s.c om

    // 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>");

    // 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.netty.fileTest.file.FileSenderServer.java

License:Apache License

public static void main(String[] args) throws Exception {

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*ww w  .  j  a  va 2s  .  c  om*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new StringEncoder(CharsetUtil.UTF_8), new LineBasedFrameDecoder(8192),
                                new StringDecoder(CharsetUtil.UTF_8), new ChunkedWriteHandler(),
                                new FileSenderServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.netty.fileTest.http.upload.HttpUploadClientHandler.java

License:Apache License

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

        System.err.println("STATUS: " + response.getStatus());
        System.err.println("VERSION: " + response.getProtocolVersion());

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

        if (response.getStatus().code() == 200 && HttpHeaders.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.netty.HttpSnoopClientHandler.java

License:Apache License

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

        System.err.println("STATUS: " + response.getStatus());
        System.err.println("VERSION: " + response.getProtocolVersion());
        System.err.println();//  w w w .  j  a va2 s . c o  m

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

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

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

        if (content instanceof LastHttpContent) {
            System.err.println("} END OF CONTENT");
            ctx.close();
        }
    }
}

From source file:com.nettyhttpserver.server.util.HttpRequestHandler.java

public static void handle(ChannelHandlerContext ctx, HttpRequest req, DefaultChannelGroup channels) {
    allChannels = channels;//from www  .  jav a 2s.  co m
    FullHttpResponse response = null;
    boolean keepAlive = isKeepAlive(req);
    String requestUri = req.getUri().toLowerCase();

    /*
     * Write data about request to database
     */
    ServerRequestDTO requestServiceDTO = new ServerRequestDTO();
    requestServiceDTO.setIP(((InetSocketAddress) ctx.channel().remoteAddress()).getHostString());
    requestServiceDTO.setLastTimestamp(new Timestamp(System.currentTimeMillis()).toString());
    serverRequestService.setServerRequest(requestServiceDTO);

    if (is100ContinueExpected(req)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
    }

    /*
     * If request /hello
     */
    if (Requests.HELLO.toString().equalsIgnoreCase(requestUri)) {
        content = Unpooled
                .unreleasableBuffer(Unpooled.copiedBuffer("<h1>Hello World!</h1>", CharsetUtil.UTF_8));
        response = new DefaultFullHttpResponse(HTTP_1_1, OK, content.duplicate());
        /*
         * Create timer for /hello page.
         */
        timer.newTimeout(new ResponseTimerTask(ctx, response, keepAlive), 10, TimeUnit.SECONDS);

        writeToResponse(ctx, response, keepAlive);
        return;
    }

    /*
     * if request uri is /status
     */
    if (Requests.STATUS.toString().equalsIgnoreCase(requestUri)) {
        content = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(generateStatus(), CharsetUtil.UTF_8));
        response = new DefaultFullHttpResponse(HTTP_1_1, OK, content.duplicate());
        writeToResponse(ctx, response, keepAlive);
        return;
    }
    /*
     * If redirect
     */
    if (requestUri.matches(Requests.REDIRECT.toString())) {
        QueryStringDecoder qsd = new QueryStringDecoder(requestUri);
        List<String> redirectUrl = qsd.parameters().get("url");
        response = new DefaultFullHttpResponse(HTTP_1_1, FOUND);
        response.headers().set(LOCATION, redirectUrl);
        /*
         * Redirect database routine
         * Write url to database 
         */
        RedirectRequestDTO requestRedirectDTO = new RedirectRequestDTO();
        requestRedirectDTO.setUrl(redirectUrl.get(0));
        redirectRequestService.setRedirectRequest(requestRedirectDTO);
    } else {
        /*
         * If request URI is not handled by server.
         */
        response = new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN);
    }
    writeToResponse(ctx, response, keepAlive);

}

From source file:com.nextcont.ecm.fileengine.http.nettyServer.HttpUploadServerHandler.java

License:Apache License

private void writeResponse(Channel channel) {
    logger.info("writeResponse ...");
    // Convert the response content to a ChannelBuffer.
    ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
    responseContent.setLength(0);//from   www  .  j a  v  a 2 s.  co m

    // Decide whether to close the connection or not.
    boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.headers().get(CONNECTION))
            || request.getProtocolVersion().equals(HttpVersion.HTTP_1_0)
                    && !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(request.headers().get(CONNECTION));

    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buf);

    response.headers().set(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().set(CONTENT_LENGTH, buf.readableBytes());
    }

    Set<Cookie> cookies;
    String value = request.headers().get(COOKIE);
    if (value == null) {
        cookies = Collections.emptySet();
    } else {
        //            cookies = CookieDecoder.decode(value);
        cookies = ServerCookieDecoder.STRICT.decode(value);
    }
    if (!cookies.isEmpty()) {
        // Reset the cookies if necessary.
        for (Cookie cookie : cookies) {
            //                response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie));
            response.headers().add(HttpHeaders.Names.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.nitesh.netty.snoop.client.HttpSnoopClientHandler.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 o  m

        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");
            HttpSnoopClient.requestQueue.offer(new Object());
        }
    }
}

From source file:com.nitesh.netty.snoop.server.HttpSnoopServerHandler.java

License:Apache License

private boolean writeResponse(ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = isKeepAlive(request);
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,
            Unpooled.copiedBuffer(buf.toString(), 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 . ja va  2  s.  co m

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

    return keepAlive;
}