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.lunex.inputprocessor.testdemo.HttpSnoopClientHandler.java

License:Apache License

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

        System.err.println("STATUS: " + response.getStatus());
        System.err.println("VERSION: " + response.getProtocolVersion());
        System.err.println();/*w ww . jav  a2 s .  co 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.lunex.inputprocessor.testdemo.QuoteOfTheMomentClient.java

License:Apache License

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

    EventLoopGroup group = new NioEventLoopGroup();
    try {//from   ww  w . jav  a 2s. c  om
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .handler(new QuoteOfTheMomentClientHandler());

        Channel ch = b.bind(0).sync().channel();

        // Broadcast the QOTM request to port 8080.
        ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
                new InetSocketAddress("255.255.255.255", PORT))).sync();

        // QuoteOfTheMomentClientHandler will close the DatagramChannel when
        // a
        // response is received. If the channel is not closed within 5
        // seconds,
        // print an error message and quit.
        if (!ch.closeFuture().await(5000)) {
            System.err.println("QOTM request timed out.");
        }
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.lunex.inputprocessor.testdemo.QuoteOfTheMomentServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
    System.err.println(packet);//w w  w.  j av  a 2  s  . c  om
    String packageContent = packet.content().toString(CharsetUtil.UTF_8);
    if ("QOTM?".equals(packageContent)) {
        ctx.write(new DatagramPacket(Unpooled.copiedBuffer("QOTM: " + nextQuote(), CharsetUtil.UTF_8),
                packet.sender()));
    }
}

From source file:com.lxz.talk.websocketx.server.WebSocketServerHandler.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);/*from w  w w.  j  av a  2s  .  c o m*/
        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.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.lxz.talk.websocketx.server.WebSocketServerIndexPage.java

License:Apache License

public static ByteBuf canvas() {
    return Unpooled.copiedBuffer(FileUtil.html("canvas.html"), CharsetUtil.UTF_8);
}

From source file:com.mapple.http.HttpHelloWorldServerHandler.java

License:Apache License

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

        if (HttpUtil.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }/*from www  .  j av a2 s.  c o m*/

        QueryStringDecoder decoder = new QueryStringDecoder(req.uri());
        List<String> close = decoder.parameters().get("close");
        int pos = -1;
        if (close != null && close.size() > 0) {
            pos = Integer.valueOf(close.get(0));
        }

        StringBuilder body = new StringBuilder();
        ConcurrentSet<Channel> proxyList = ForwardLoginHandler.INSTANCE.proxyList();
        int i = 0;
        AttributeKey<ForwardLogin> Session = AttributeKey.valueOf("Session");
        Iterator<Channel> it = proxyList.iterator();
        while (it.hasNext()) {
            Channel ch = it.next();
            ForwardLogin p = ch.attr(Session).get();
            body.append(i + 1);
            body.append("  ");
            body.append(p.getUserName());
            body.append("  ");
            body.append(
                    p.getProvince() + (p.getCity() == null ? "" : p.getCity()) + "[" + p.getProvince2() + "]");
            body.append("  ");
            body.append(p.getRemoteAddr() + ":" + p.getRemotePort());
            body.append("  ");
            body.append(p.getCarrier());
            body.append("  ");
            if (ch instanceof SocketChannel) {
                body.append("TCP");
            } else {
                body.append("UDT");
            }
            if (i++ == pos) {
                body.append("  [CLOSED]");
                ch.writeAndFlush(new ForwardForceClose());
            }
            body.append("\n");
        }
        String data = body.toString();
        if (data.isEmpty()) {
            data = "?";
        }

        //            boolean keepAlive = HttpUtil.isKeepAlive(req);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,
                Unpooled.wrappedBuffer(data.getBytes(CharsetUtil.UTF_8)));
        response.headers().set(CONTENT_TYPE, "text/plain; charset=utf-8");
        response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

        //            if (!keepAlive) {
        ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        //            } else {
        //                response.headers().set(CONNECTION, KEEP_ALIVE);
        //                ctx.write(response);
        //            }
    }
}

From source file:com.mastfrog.acteur.resources.MimeTypes.java

License:Open Source License

public MimeTypes() {
    this(CharsetUtil.UTF_8, new NullExpiresPolicy());
}

From source file:com.mastfrog.acteur.sse.EventSink.java

License:Open Source License

private ByteBuf toByteBuf(Message msg) {
    StringBuilder builder = new StringBuilder();
    if (msg.eventType != null) {
        builder.append("\nevent: ").append(msg.eventType);
    }//from   ww w. jav a  2  s.  co  m
    String stringMessage = ren.toString(msg.message).replace("\n", "\ndata: "); //XXX support multiline
    builder.append("\nid: ").append(msg.id).append("-").append(msg.timestamp).append("\ndata: ")
            .append(stringMessage).append('\n').append('\n');
    return alloc.buffer(builder.length()).writeBytes(builder.toString().getBytes(CharsetUtil.UTF_8));
}

From source file:com.mastfrog.acteur.sse.SseTest.java

License:Open Source License

@Test(timeout = 90000)
public void test(TestHarness harn) throws Throwable {
    long when = System.currentTimeMillis();
    System.err.println("PORT " + harn.getPort());
    System.err.flush();//from   ww w . java2  s  .  c  o m
    harn.get("/foo").setTimeout(Duration.standardSeconds(60)).log().go().assertStatus(NOT_FOUND);
    final StringBuilder content = new StringBuilder();
    final CallResult[] res = new CallResult[1];
    final AtomicInteger count = new AtomicInteger();
    res[0] = harn.get("/sse").on(StateType.ContentReceived, new Receiver<HttpContent>() {

        @Override
        public void receive(HttpContent c) {
            if (c == null) {
                System.out.println("GOT NULL BUF");
                return;
            }
            ByteBuf buf = c.content();
            byte[] bytes = new byte[buf.readableBytes()];
            buf.readBytes(bytes);
            String s = new String(bytes, CharsetUtil.UTF_8);
            System.out.println("READ " + s);
            content.append(s);
            int ct = count.incrementAndGet();
            if (ct > 5) {
                res[0].cancel();
            }
        }
    }).setTimeout(Duration.standardSeconds(60)).go();
    try {
        res[0].await();
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
    List<String> ids = new ArrayList<>();
    List<String> items = new ArrayList<>();
    for (String line : content.toString().split("\n")) {
        if (line.startsWith("id: ")) {
            ids.add(line.substring(4));
        }
        if (line.startsWith("data: ")) {
            items.add(line.substring(6));
        }
    }
    int last = -1;
    for (String s : ids) {
        Matcher m = Pattern.compile("(\\d+)\\-(\\d*)$").matcher(s);
        assertTrue(m.find());
        int id = Integer.parseInt(m.group(1));
        long ts = Long.parseLong(m.group(2));
        assertTrue(id > last);
        assertTrue(ts > when);
        if (last != -1) {
            assertEquals(last + 1, id);
        }
        last = id;
    }
    last = -1;
    for (String item : items) {
        Matcher m = Pattern.compile("hello (\\d+)").matcher(item);
        assertTrue(m.find());
        int val = Integer.parseInt(m.group(1));
        if (last != -1) {
            assertEquals(last + 1, val);
        }
        last = val;
    }
}

From source file:com.mastfrog.acteur.twitter.TwitterSign.java

public OAuthResult startTwitterAuthentication(String oauth_nonce)
        throws IOException, InterruptedException, GeneralSecurityException {

    // this particular request uses POST
    String get_or_post = "POST";

    // I think this is the signature method used for all Twitter API calls
    String oauth_signature_method = "HMAC-SHA1";

    // get the timestamp
    long ts = DateTimeUtils.currentTimeMillis();
    String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

    // assemble the proper parameter string, which must be in alphabetical order, using your consumer key
    String parameter_string = "oauth_consumer_key=" + twitter_consumer_key + "&oauth_nonce=" + oauth_nonce
            + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp
            + "&oauth_version=1.0";

    // specify the proper twitter API endpoint at which to direct this request
    String twitter_endpoint = "https://api.twitter.com/oauth/request_token";
    String twitter_endpoint_host = "api.twitter.com";
    String twitter_endpoint_path = "/oauth/request_token";

    // assemble the string to be signed. It is METHOD & percent-encoded endpoint & percent-encoded parameter string
    // Java's native URLEncoder.encode function will not work. It is the wrong RFC specification (which does "+" where "%20" should be)...
    // the encode() function included in this class compensates to conform to RFC 3986 (which twitter requires)
    String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&"
            + encode(parameter_string);//ww w.ja v a2 s  . com

    // now that we've got the string we want to sign (see directly above) HmacSHA1 hash it against the consumer secret
    String oauth_signature = "";
    oauth_signature = computeSignature(signature_base_string, twitter_consumer_secret + "&"); // note the & at the end. Normally the user access_token would go here, but we don't know it yet for request_token

    // each request to the twitter API 1.1 requires an "Authorization: BLAH" header. The following is what BLAH should look like
    String authorization_header_string = "OAuth oauth_consumer_key=\"" + twitter_consumer_key
            + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
            + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
            + encode(oauth_signature) + "\"";

    String oauth_token = "";
    String oauth_token_secret = "";
    String oauth_callback_confirmed = "";

    // initialize the HTTPS connection
    // for HTTP, use this instead of the above.
    // Socket socket = new Socket(host.getHostName(), host.getPort());
    // conn.bind(socket, params);
    ResponseLatch receiver = new ResponseLatch();
    RH rh = new RH();

    client.post()
            .setBody("", MediaType.parse("application/x-www-form-urlencoded").withCharset(CharsetUtil.UTF_8))
            .addHeader(Headers.stringHeader("Authorization"), authorization_header_string)
            .setURL(URL.builder().setProtocol(Protocols.HTTPS).setHost(Host.parse(twitter_endpoint_host))
                    .setPath(twitter_endpoint_path).create().toString())
            .on(StateType.Closed, receiver).execute(rh);

    receiver.latch.await(1, TimeUnit.MINUTES);
    String responseBody = rh.getResponse();
    StringTokenizer st = new StringTokenizer(responseBody, "&");
    String currenttoken = "";
    while (st.hasMoreTokens()) {
        currenttoken = st.nextToken();
        if (currenttoken.startsWith("oauth_token=")) {
            oauth_token = currenttoken.substring(currenttoken.indexOf("=") + 1);
        } else if (currenttoken.startsWith("oauth_token_secret=")) {
            oauth_token_secret = currenttoken.substring(currenttoken.indexOf("=") + 1);
        } else if (currenttoken.startsWith("oauth_callback_confirmed=")) {
            oauth_callback_confirmed = currenttoken.substring(currenttoken.indexOf("=") + 1);
        } else {
            System.out.println("Warning... twitter returned a key we weren't looking for: " + currenttoken);
        }
    }
    return new OAuthResult(oauth_token, oauth_token_secret, oauth_callback_confirmed);
}