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.srotya.sidewinder.core.ingress.http.HTTPDataPointDecoder.java

License:Apache License

private boolean writeResponse(HttpObject httpObject, ChannelHandlerContext ctx) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
            httpObject.decoderResult().isSuccess() ? OK : BAD_REQUEST,
            Unpooled.copiedBuffer(responseString.toString().toString(), CharsetUtil.UTF_8));
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");

    response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
    response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);

    responseString = new StringBuilder();
    // Write the response.
    ctx.write(response);//  w w w . j ava2s .  co m
    return true;
}

From source file:com.stremebase.examples.todomvc.HttpRouter.java

License:Apache License

private static HttpResponse createResponse(HttpRequest req, Router<Integer> router) {
    RouteResult<Integer> routeResult = router.route(req.getMethod(), req.getUri());

    Integer request = routeResult.target();

    String data = "";
    String mimeType = "";

    if (request == CSS) {
        data = Todo.getCss();/*from   ww  w  . j av a2s  .c om*/
        mimeType = "text/css";
    } else if (request == ICON) {
        mimeType = "image/x-icon";
    } else if (request == GET) {
        data = Todo.get();
        mimeType = "text/html";
    } else if (request == FILTER) {
        data = Todo.filter(routeResult.pathParams().get("filtertype"));
        mimeType = "text/html";
    } else if (req.getMethod().equals(HttpMethod.POST)) {
        HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), req);

        Attribute attribute;

        String item_text = null;
        InterfaceHttpData httpData = decoder.getBodyHttpData("item-text");
        if (httpData != null) {
            attribute = (Attribute) httpData;
            try {
                item_text = attribute.getValue();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        String item_id = null;
        httpData = decoder.getBodyHttpData("item-id");
        if (httpData != null) {
            attribute = (Attribute) httpData;
            try {
                item_id = attribute.getValue();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (request == POST) {
            if (item_id == null)
                data = Todo.create(item_text);
            else
                data = Todo.save(Long.valueOf(item_id), item_text);
        } else if (request == DELETE) {
            data = Todo.delete(Long.valueOf(item_id));
        } else if (request == DELETECOMPLETED) {
            data = Todo.clearCompleted();
        } else if (request == TOGGLESTATUS)
            data = Todo.toggleStatus(Long.valueOf(item_id));

        mimeType = "text/html";
        decoder.destroy();
    }

    FullHttpResponse res;

    if (request == NOTFOUND) {
        res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.TEMPORARY_REDIRECT);
        res.headers().add(HttpHeaders.Names.LOCATION, "/");
        return res;
    }

    if (request == ICON)
        res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                Unpooled.copiedBuffer(Todo.favicon));
    else
        res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                Unpooled.copiedBuffer(data, CharsetUtil.UTF_8));

    res.headers().set(HttpHeaders.Names.CONTENT_TYPE, mimeType);
    res.headers().set(HttpHeaders.Names.CONTENT_LENGTH, res.content().readableBytes());
    if (request == CSS || request == ICON)
        setDateAndCacheHeaders(res);

    return res;
}

From source file:com.study.hc.net.netty.chat.client.WebSocketClientHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();/*from   w  w  w.ja v  a 2 s .  co m*/
    if (!handshaker.isHandshakeComplete()) {
        try {
            handshaker.finishHandshake(ch, (FullHttpResponse) msg);
            System.out.println("WebSocket Client connected!");
            handshakeFuture.setSuccess();
        } catch (WebSocketHandshakeException e) {
            System.out.println("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;
    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();
    }
}

From source file:com.system.distribute.server.FileServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*  w w  w.  ja v a  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 {
                        ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8),
                                new LineBasedFrameDecoder(8192), new StringDecoder(CharsetUtil.UTF_8),
                                new FileHandler());
                    }
                });

        // 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.tc.websocket.clients.WebSocketClientHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {

    Channel ch = ctx.channel();/*  www. j av a 2  s .  c om*/
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        handshakeFuture.setSuccess();

        //connection is opened.
        client.onOpen(handshaker);

        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;
        client.onMessage(textFrame.text());

    } else if (frame instanceof PongWebSocketFrame) {
        /*
         * placeholder.  maybe add onPong method to the RhinoClient
         */
    } else if (frame instanceof CloseWebSocketFrame) {
        client.onClose();
        ch.close();
    }
}

From source file:com.tc.websocket.server.handler.WebSocketValidationHandler.java

License:Apache License

/**
 * Send http response./*  w  w  w  .  ja v a2 s.  co  m*/
 *
 * @param ctx the ctx
 * @param req the req
 * @param res the res
 */
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);
        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.status().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.tesora.dve.db.mysql.common.MysqlAPIUtils.java

License:Open Source License

/**
 * Method to create a Length Coded string that has a Length Code Binary
 * /*from www  . j a  v a2s  .c om*/
 * As described in MySQL internals doc: Length Coded String: a
 * variable-length string. Used instead of Null-Terminated String,
 * especially for character strings which might contain '\0' or might be
 * very long. The first part of a Length Coded String is a Length Coded
 * Binary number (the length); the second part of a Length Coded String is
 * the actual data. An example of a short Length Coded String is these three
 * hexadecimal bytes: 02 61 62, which means "length = 2, contents = 'ab'".
 * 
 * Length Coded Binary: a variable-length number. To compute the value of a
 * Length Coded Binary, one must examine the value of its first byte.
 * 
 * Value Of # Of Bytes Description First Byte Following 0-250 0 = value of
 * first byte 251 0 column value = NULL only appropriate in a Row Data
 * Packet 252 2 = value of following 16-bit word 253 3 = value of following
 * 24-bit word 254 8 = value of following 64-bit word
 * 
 * Thus the length of a Length Coded Binary, including the first byte, will
 * vary from 1 to 9 bytes. The relevant MySQL source program is
 * sql/protocol.cc net_store_length().
 * 
 * All numbers are stored with the least significant byte first. All numbers
 * are unsigned.
 * 
 * @param cb
 *            - ByteBuf - length coded string is written here
 * @param data
 *            - string to put in buffer
 */
public static void putLengthCodedString(ByteBuf cb, String data, boolean codeNullasZero) {
    putLengthCodedString(cb, ((data == null) ? null : data.getBytes(CharsetUtil.UTF_8)), codeNullasZero);
}

From source file:com.tesora.dve.db.mysql.common.MysqlAPIUtils.java

License:Open Source License

public static String getLengthCodedString(ByteBuf cb) {
    return getLengthCodedString(cb, CharsetUtil.UTF_8);
}

From source file:com.tesora.dve.db.mysql.libmy.MyErrorResponse.java

License:Open Source License

@Override
public void unmarshallMessage(ByteBuf cb) {
    cb.skipBytes(1); // error header
    errorNumber = cb.readUnsignedShort();
    cb.skipBytes(1);//from   ww  w  .j  a  v  a 2  s.co  m
    sqlState = MysqlAPIUtils.readBytesAsString(cb, 5, CharsetUtil.UTF_8);
    errorMsg = MysqlAPIUtils.readBytesAsString(cb, CharsetUtil.UTF_8);
}

From source file:com.tesora.dve.db.mysql.libmy.MyErrorResponse.java

License:Open Source License

public static PESQLStateException asException(ByteBuf in) {

    ByteBuf cb = in.order(ByteOrder.LITTLE_ENDIAN);
    cb.skipBytes(1); // error header
    int errorNumber = cb.readUnsignedShort();
    cb.skipBytes(1); // sqlState header
    String sqlState = MysqlAPIUtils.readBytesAsString(cb, 5, CharsetUtil.UTF_8);
    String errorMsg = MysqlAPIUtils.readBytesAsString(cb, CharsetUtil.UTF_8);
    return new PESQLStateException(errorNumber, sqlState, errorMsg);
}