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.caricah.iotracah.server.httpserver.netty.HttpServerHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

    try {/*from  w w w  .j  a va2 s .  co m*/
        log.info(" exceptionCaught : Unhandled exception: ", cause);

        JSONObject error = new JSONObject();
        error.put("message", cause.getMessage());
        error.put("status", "failure");

        ByteBuf buffer = Unpooled.copiedBuffer(error.toString(), CharsetUtil.UTF_8);

        // Build the response object.
        FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.INTERNAL_SERVER_ERROR, buffer);

        ctx.channel().writeAndFlush(httpResponse).addListener(ChannelFutureListener.CLOSE);
    } catch (Exception ex) {
        log.debug(" exceptionCaught : trying to close socket because we got an unhandled exception", ex);
    }

}

From source file:com.caricah.iotracah.server.httpserver.transform.HttpIOTTransformerImpl.java

License:Apache License

@Override
public IOTMessage toIOTMessage(FullHttpMessage serverMessage) {

    if (serverMessage instanceof FullHttpRequest) {

        FullHttpRequest request = (FullHttpRequest) serverMessage;
        final String content = request.content().toString(CharsetUtil.UTF_8);
        final JSONObject json = new JSONObject(content);

        log.debug(" toIOTMessage : received content {} ", content);

        final String path = request.uri().toUpperCase();

        switch (path) {

        case "/CONNECT":

            boolean isAnnonymousConnect = (!json.has("username") && !json.has("password"));

            int keepAliveTime = json.has("keepAliveTime") ? json.getInt("keepAliveTime") : 0;

            return ConnectMessage.from(false, 1, false, "MQTT", 4, false, isAnnonymousConnect,
                    json.getString("clientId"), json.has("username") ? json.getString("username") : "",
                    json.has("password") ? json.getString("password") : "", keepAliveTime, "");

        case "/PUBLISH":

            ByteBuffer byteBuffer = ByteBuffer.wrap(json.getString("payload").getBytes());

            PublishMessage publishMessage = PublishMessage.from(json.getInt("messageId"),
                    json.has("dup") && json.getBoolean("dup"), 1,
                    json.has("retain") && json.getBoolean("retain"), json.getString("topic"), byteBuffer, true);

            publishMessage.setSessionId(json.getString("sessionId"));
            publishMessage.setAuthKey(json.getString("authKey"));
            return publishMessage;

        case "/SUBSCRIBE":

            SubscribeMessage subscribeMessage = SubscribeMessage.from(1, false, 1, false);

            JSONArray jsonTopicQosList = json.getJSONArray("topicQosList");
            for (int i = 0; i < jsonTopicQosList.length(); i++) {
                JSONObject topicQos = jsonTopicQosList.getJSONObject(i);

                String topic = topicQos.getString("topic");
                int qos = topicQos.getInt("qos");

                Map.Entry<String, Integer> entry = new AbstractMap.SimpleEntry<>(topic, qos);
                subscribeMessage.getTopicFilterList().add(entry);
            }//from   w ww  .j a  v  a2  s  .c  o  m
            subscribeMessage.setReceptionUrl(json.getString("recipientUrl"));
            subscribeMessage.setSessionId(json.getString("sessionId"));
            subscribeMessage.setAuthKey(json.getString("authKey"));

            return subscribeMessage;

        case "/UNSUBSCRIBE":

            List<String> topicList = new ArrayList<>();
            JSONArray jsonTopicList = json.getJSONArray("topicList");
            for (int i = 0; i < jsonTopicList.length(); i++) {
                String topic = jsonTopicList.getString(i);
                topicList.add(topic);
            }

            UnSubscribeMessage unSubscribeMessage = UnSubscribeMessage.from(1, false, 1, false, topicList);
            unSubscribeMessage.setSessionId(json.getString("sessionId"));
            unSubscribeMessage.setAuthKey(json.getString("authKey"));

        case "/DISCONNECT":

            DisconnectMessage disconMessage = DisconnectMessage.from(false);
            disconMessage.setSessionId(json.getString("sessionId"));
            disconMessage.setAuthKey(json.getString("authKey"));

            return disconMessage;

        default:
            return null;
        }

    }

    return null;
}

From source file:com.caricah.iotracah.server.httpserver.transform.IOTHttpTransformerImpl.java

License:Apache License

@Override
public FullHttpMessage toServerMessage(IOTMessage internalMessage) {

    JSONObject json = new JSONObject();

    switch (internalMessage.getMessageType()) {

    case AcknowledgeMessage.MESSAGE_TYPE:
        AcknowledgeMessage ackMsg = (AcknowledgeMessage) internalMessage;

        json.put("messageId", ackMsg.getMessageId());
        json.put("qos", ackMsg.getQos());
        json.put("message", "published");
        break;/*from  w  w  w  .j a  v  a 2  s  .  c  o  m*/
    case ConnectAcknowledgeMessage.MESSAGE_TYPE:
        ConnectAcknowledgeMessage conAck = (ConnectAcknowledgeMessage) internalMessage;

        json.put("sessionId", conAck.getSessionId());
        json.put("authKey", conAck.getAuthKey());
        json.put("message", conAck.getReturnCode().name());

        break;
    case SubscribeAcknowledgeMessage.MESSAGE_TYPE:
        SubscribeAcknowledgeMessage subAck = (SubscribeAcknowledgeMessage) internalMessage;

        json.put("message", "subscribed");
        final JSONArray jsonGrantedQos = new JSONArray();
        subAck.getGrantedQos().forEach(jsonGrantedQos::put);
        json.put("grantedQos", jsonGrantedQos);
        break;

    case UnSubscribeAcknowledgeMessage.MESSAGE_TYPE:
        UnSubscribeAcknowledgeMessage unSubAck = (UnSubscribeAcknowledgeMessage) internalMessage;
        json.put("message", "unsubscribed");

        break;
    case DisconnectMessage.MESSAGE_TYPE:

        DisconnectMessage discMsg = (DisconnectMessage) internalMessage;

        json.put("sessionId", discMsg.getSessionId());
        json.put("message", "disconnected");

        break;
    default:
        /**
         *
         * Internally these are not expected to get here.
         * In such cases we just return a null
         * and log this anomaly as a gross error.
         *
         **/

        json.put("message", "UnExpected outcome");
        break;
    }

    ByteBuf buffer = Unpooled.copiedBuffer(json.toString(), CharsetUtil.UTF_8);

    // Build the response object.
    FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            buffer);

    httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
    httpResponse.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buffer.readableBytes());
    return httpResponse;

}

From source file:com.cat.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 w  w  .j  av a 2 s  .c o  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.cats.version.httpserver.HttpStaticFileServerHandler.java

License:Apache License

private static void sendListing(ChannelHandlerContext ctx, File dir) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
    response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");

    String dirPath = dir.getPath();
    StringBuilder buf = new StringBuilder().append("<!DOCTYPE html>\r\n").append("<html><head><title>")
            .append("Listing of: ").append(dirPath).append("</title></head><body>\r\n")

            .append("<h3>Listing of: ").append(dirPath).append("</h3>\r\n")

            .append("<ul>").append("<li><a href=\"../\">..</a></li>\r\n");

    for (File f : dir.listFiles()) {
        if (f.isHidden() || !f.canRead()) {
            continue;
        }/*w  w w.  j  ava2 s  .com*/

        String name = f.getName();
        if (!ALLOWED_FILE_NAME.matcher(name).matches()) {
            continue;
        }

        buf.append("<li><a href=\"").append(name).append("\">").append(name).append("</a></li>\r\n");
    }

    buf.append("</ul></body></html>\r\n");
    ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8);
    response.content().writeBytes(buffer);
    buffer.release();

    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.cats.version.httpserver.HttpStaticFileServerHandler.java

License:Apache License

private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status,
            Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8));
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");

    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.cats.version.httpserver.HttpStaticFileServerHandler.java

License:Apache License

public static void sendWarningInfo(ChannelHandlerContext ctx) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
    response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");

    StringBuffer buf = new StringBuffer();
    buf.append("<!DOCTYPE html>\r\n<html>");
    buf.append("<br/><br/><br/><br/><br/><br/>");
    buf.append("<center><font size='5px'>");
    buf.append(/*ww w. j av  a  2  s . com*/
            "Access denied, because this is version monitor service server</br></br> CTAS@Intel 2016~2026 All rights reserved");
    buf.append("</font></center>");
    buf.append("<html>");
    ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8);
    response.content().writeBytes(buffer);
    buffer.release();
    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.cats.version.httpserver.msg.IMsgHandler.java

License:Apache License

public void sendMessageToClient(String strRsp, ChannelHandlerContext ctx) {
    if (null == strRsp) {
        return;/*from   ww w  .jav  a 2  s  . c om*/
    }
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
    response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");

    ByteBuf buffer = Unpooled.copiedBuffer(strRsp, CharsetUtil.UTF_8);
    response.content().writeBytes(buffer);
    buffer.release();

    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.changxx.phei.netty.protocol.udp.ChineseProverbClientHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
    String response = msg.content().toString(CharsetUtil.UTF_8);
    if (response.startsWith(": ")) {
        System.out.println(response);
        ctx.close();//  w ww  .ja  va2  s .c o  m
    }
}

From source file:com.changxx.phei.netty.protocol.udp.ChineseProverbServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
    String req = packet.content().toString(CharsetUtil.UTF_8);
    System.out.println(req);//from   w  ww . j  a v  a  2 s.  com
    if ("?".equals(req)) {
        ctx.writeAndFlush(new DatagramPacket(
                Unpooled.copiedBuffer(": " + nextQuote(), CharsetUtil.UTF_8),
                packet.sender()));
    }
}