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.indigo.game.common.network.websocket.WebSocketServerIndexPage.java

License:Apache License

static ByteBuf getContent(String webSocketLocation) {
    return Unpooled.copiedBuffer("<html><head><title>Web Socket Test</title></head>" + NEWLINE + "<body>"
            + NEWLINE + "<com.indigo.game.common.script type=\"text/javascript\">" + NEWLINE + "var socket;"
            + NEWLINE + "if (!window.WebSocket) {" + NEWLINE + "  window.WebSocket = window.MozWebSocket;"
            + NEWLINE + '}' + NEWLINE + "if (window.WebSocket) {" + NEWLINE + "  socket = new WebSocket(\""
            + webSocketLocation + "\");" + NEWLINE + "  socket.onmessage = function(event) {" + NEWLINE
            + "    var ta = document.getElementById('responseText');" + NEWLINE
            + "    ta.value = ta.value + '\\n' + event.data" + NEWLINE + "  };" + NEWLINE
            + "  socket.onopen = function(event) {" + NEWLINE
            + "    var ta = document.getElementById('responseText');" + NEWLINE
            + "    ta.value = \"Web Socket opened!\";" + NEWLINE + "  };" + NEWLINE
            + "  socket.onclose = function(event) {" + NEWLINE
            + "    var ta = document.getElementById('responseText');" + NEWLINE
            + "    ta.value = ta.value + \"Web Socket closed\"; " + NEWLINE + "  };" + NEWLINE + "} else {"
            + NEWLINE + "  alert(\"Your browser does not support Web Socket.\");" + NEWLINE + '}' + NEWLINE
            + NEWLINE + "function send(message) {" + NEWLINE + "  if (!window.WebSocket) { return; }" + NEWLINE
            + "  if (socket.readyState == WebSocket.OPEN) {" + NEWLINE + "    socket.send(message);" + NEWLINE
            + "  } else {" + NEWLINE + "    alert(\"The socket is not open.\");" + NEWLINE + "  }" + NEWLINE
            + '}' + NEWLINE + "</com.indigo.game.common.script>" + NEWLINE + "<form onsubmit=\"return false;\">"
            + NEWLINE + "<input type=\"text\" name=\"message\" value=\"Hello, World!\"/>"
            + "<input type=\"button\" value=\"Send Web Socket Data\"" + NEWLINE
            + "       onclick=\"send(this.form.message.value)\" />" + NEWLINE + "<h3>Output</h3>" + NEWLINE
            + "<textarea id=\"responseText\" style=\"width:500px;height:300px;\"></textarea>" + NEWLINE
            + "</form>" + NEWLINE + "</body>" + NEWLINE + "</html>" + NEWLINE, CharsetUtil.UTF_8);
}

From source file:com.informatica.surf.sources.http.HttpServerHandler.java

License:Apache License

private static 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);/*  w w w.ja va  2  s.  c  om*/
        buf.release();
        setContentLength(res, res.content().readableBytes());
    } else {
        setContentLength(res, 0);
    }

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

From source file:com.intuit.karate.netty.FeatureServerHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) {
    long startTime = System.currentTimeMillis();
    backend.getContext().logger.debug("handling method: {}, uri: {}", msg.method(), msg.uri());
    FullHttpResponse nettyResponse;//from  w w w.  java 2  s.  c  o m
    if (msg.uri().startsWith(STOP_URI)) {
        backend.getContext().logger.info("stop uri invoked, shutting down");
        ByteBuf responseBuf = Unpooled.copiedBuffer("stopped", CharsetUtil.UTF_8);
        nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, responseBuf);
        stopFunction.run();
    } else {
        StringUtils.Pair url = HttpUtils.parseUriIntoUrlBaseAndPath(msg.uri());
        HttpRequest request = new HttpRequest();
        if (url.left == null) {
            String requestScheme = ssl ? "https" : "http";
            String host = msg.headers().get(HttpUtils.HEADER_HOST);
            request.setUrlBase(requestScheme + "://" + host);
        } else {
            request.setUrlBase(url.left);
        }
        request.setUri(url.right);
        request.setMethod(msg.method().name());
        msg.headers().forEach(h -> request.addHeader(h.getKey(), h.getValue()));
        QueryStringDecoder decoder = new QueryStringDecoder(url.right);
        decoder.parameters().forEach((k, v) -> request.putParam(k, v));
        HttpContent httpContent = (HttpContent) msg;
        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            byte[] bytes = new byte[content.readableBytes()];
            content.readBytes(bytes);
            request.setBody(bytes);
        }
        HttpResponse response = backend.buildResponse(request, startTime);
        HttpResponseStatus httpResponseStatus = HttpResponseStatus.valueOf(response.getStatus());
        byte[] responseBody = response.getBody();
        if (responseBody != null) {
            ByteBuf responseBuf = Unpooled.copiedBuffer(responseBody);
            nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpResponseStatus, responseBuf);
        } else {
            nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpResponseStatus);
        }
        MultiValuedMap karateHeaders = response.getHeaders();
        if (karateHeaders != null) {
            HttpHeaders nettyHeaders = nettyResponse.headers();
            karateHeaders.forEach((k, v) -> nettyHeaders.add(k, v));
        }
    }
    ctx.write(nettyResponse);
    ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.intuit.karate.netty.WebSocketClientHandler.java

License:Open Source License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();/*w  w w .j a  v a2s .  c om*/
    if (!handshaker.isHandshakeComplete()) {
        try {
            handshaker.finishHandshake(ch, (FullHttpResponse) msg);
            logger.debug("websocket client connected");
            handshakeFuture.setSuccess();
        } catch (WebSocketHandshakeException e) {
            logger.debug("websocket client connect failed: {}", e.getMessage());
            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;
    if (frame instanceof TextWebSocketFrame) {
        if (logger.isTraceEnabled()) {
            logger.trace("websocket received text");
        }
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        listener.onMessage(textFrame.text());
    } else if (frame instanceof PongWebSocketFrame) {
        if (logger.isTraceEnabled()) {
            logger.trace("websocket received pong");
        }
    } else if (frame instanceof CloseWebSocketFrame) {
        logger.debug("websocket closing");
        ch.close();
    } else if (frame instanceof BinaryWebSocketFrame) {
        logger.debug("websocket received binary");
        BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame;
        ByteBuf buf = binaryFrame.content();
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        listener.onMessage(bytes);
    }
}

From source file:com.jason.netty.file.FileServer.java

License:Apache License

public void run(int port) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from   w ww . ja  va  2  s . co m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).childHandler(new ChannelInitializer<SocketChannel>() {
                    /*
                     * (non-Javadoc)
                     * 
                     * @see
                     * io.netty.channel.ChannelInitializer#initChannel(io
                     * .netty.channel.Channel)
                     */
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8),
                                new LineBasedFrameDecoder(1024), new StringDecoder(CharsetUtil.UTF_8),
                                new FileServerHandler());
                    }
                });
        ChannelFuture f = b.bind(port).sync();
        System.out.println("Server start at port : " + port);
        f.channel().closeFuture().sync();
    } finally {
        // ?
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.jjneko.jjnet.networking.http.client.WebSocketClientHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();//from ww w. java2s.  c om
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        System.out.println("WebSocket Client connected!");
        handshakeFuture.setSuccess();
        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;
        pipe.queuePacket(textFrame.text().getBytes("ISO-8859-1"));
    } else if (frame instanceof CloseWebSocketFrame) {
        System.out.println("WebSocket Client received closing");
        ch.close();
    }
}

From source file:com.jjneko.jjnet.networking.http.server.WebSocketHttpServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.status().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);//  ww  w  . j  ava  2  s.com
        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.status().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.jjneko.jjnet.networking.http.server.WebSocketHttpServerTestPage.java

License:Apache License

public static ByteBuf getContent(String webSocketLocation) {
    return Unpooled.copiedBuffer(

            "<html><body><p style=\"font-size:22px;\">This peer is accessible!</p></body></html>"

            /* "<html><head><title>Web Socket Test</title></head>" + NEWLINE +
             "<body>" + NEWLINE +//from   w ww .  jav a 2  s. c  o  m
             "<script type=\"text/javascript\">" + NEWLINE +
             "var socket;" + NEWLINE +
             "if (!window.WebSocket) {" + NEWLINE +
             "  window.WebSocket = window.MozWebSocket;" + NEWLINE +
             '}' + NEWLINE +
             "if (window.WebSocket) {" + NEWLINE +
             "  socket = new WebSocket(\"" + webSocketLocation + "\");" + NEWLINE +
             "  socket.onmessage = function(event) {" + NEWLINE +
             "    var ta = document.getElementById('responseText');" + NEWLINE +
             "    ta.value = ta.value + '\\n' + event.data" + NEWLINE +
             "  };" + NEWLINE +
             "  socket.onopen = function(event) {" + NEWLINE +
             "    var ta = document.getElementById('responseText');" + NEWLINE +
             "    ta.value = \"Web Socket opened!\";" + NEWLINE +
             "  };" + NEWLINE +
             "  socket.onclose = function(event) {" + NEWLINE +
             "    var ta = document.getElementById('responseText');" + NEWLINE +
             "    ta.value = ta.value + \"Web Socket closed\"; " + NEWLINE +
             "  };" + NEWLINE +
             "} else {" + NEWLINE +
             "  alert(\"Your browser does not support Web Socket.\");" + NEWLINE +
             '}' + NEWLINE +
             NEWLINE +
             "function send(message) {" + NEWLINE +
             "  if (!window.WebSocket) { return; }" + NEWLINE +
             "  if (socket.readyState == WebSocket.OPEN) {" + NEWLINE +
             "    socket.send(message);" + NEWLINE +
             "  } else {" + NEWLINE +
             "    alert(\"The socket is not open.\");" + NEWLINE +
             "  }" + NEWLINE +
             '}' + NEWLINE +
             "</script>" + NEWLINE +
             "<form onsubmit=\"return false;\">" + NEWLINE +
             "<input type=\"text\" name=\"message\" value=\"Hello, World!\"/>" +
             "<input type=\"button\" value=\"Send Web Socket Data\"" + NEWLINE +
             "       onclick=\"send(this.form.message.value)\" />" + NEWLINE +
             "<h3>Output</h3>" + NEWLINE +
             "<textarea id=\"responseText\" style=\"width:500px;height:300px;\"></textarea>" + NEWLINE +
             "</form>" + NEWLINE +
             "</body>" + NEWLINE +
             "</html>" + NEWLINE*/

            , CharsetUtil.UTF_8);
}

From source file:com.jjzhk.Chapter10.xml.HttpXmlServerHandler.java

License:Apache License

private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status,
            Unpooled.copiedBuffer(": " + 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.jjzhk.Chapter11.websocket.WebSocketServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // ?????/*  w w w  . j  a v  a 2s .  c o  m*/
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        setContentLength(res, res.content().readableBytes());
    }

    // ??Keep-Alive?
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}