List of usage examples for io.netty.util CharsetUtil UTF_8
Charset UTF_8
To view the source code for io.netty.util CharsetUtil UTF_8.
Click Source Link
From source file:com.helome.messagecenter.master.HttpServerHandler.java
License:Apache License
private boolean writeResponse(HttpObject currentObj, 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, "application/json; 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: // -//from w w w . j av a 2s.c o m // http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } // Write the response. ctx.write(response); return keepAlive; }
From source file:com.hop.hhxx.example.http.file.HttpStaticFileServerHandler.java
License:Apache License
private static void sendListing(ChannelHandlerContext ctx, File dir) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK); response.headers().set(HttpHeaderNames.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; }// ww w . j a v a2 s .c om 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.hop.hhxx.example.http2.helloworld.client.Http2Client.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {//from w w w . j a va 2 s .co m SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK; sslCtx = SslContextBuilder.forClient().sslProvider(provider) /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification. * Please refer to the HTTP/2 specification for cipher requirements. */ .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .trustManager(InsecureTrustManagerFactory.INSTANCE) .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN, // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers. SelectorFailureBehavior.NO_ADVERTISE, // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers. SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) .build(); } else { sslCtx = null; } EventLoopGroup workerGroup = new NioEventLoopGroup(); Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE); try { // Configure the client. Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.remoteAddress(HOST, PORT); b.handler(initializer); // Start the client. Channel channel = b.connect().syncUninterruptibly().channel(); System.out.println("Connected to [" + HOST + ':' + PORT + ']'); // Wait for the HTTP/2 upgrade to occur. Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler(); http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS); HttpResponseHandler responseHandler = initializer.responseHandler(); int streamId = 3; HttpScheme scheme = SSL ? HttpScheme.HTTPS : HttpScheme.HTTP; AsciiString hostName = new AsciiString(HOST + ':' + PORT); System.err.println("Sending request(s)..."); if (URL != null) { // Create a simple GET request. FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL); request.headers().add(HttpHeaderNames.HOST, hostName); request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name()); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE); responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise()); streamId += 2; } if (URL2 != null) { // Create a simple POST request with a body. FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2, Unpooled.copiedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8))); request.headers().add(HttpHeaderNames.HOST, hostName); request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name()); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE); responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise()); streamId += 2; } responseHandler.awaitResponses(5, TimeUnit.SECONDS); System.out.println("Finished HTTP/2 request(s)"); // Wait until the connection is closed. channel.close().syncUninterruptibly(); } finally { workerGroup.shutdownGracefully(); } }
From source file:com.hop.hhxx.example.qotm.QuoteOfTheMomentClient.java
License:Apache License
public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {// www .j a v a2s . co m 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.hxr.javatone.concurrency.netty.official.filetransfer.FileServer.java
License:Apache License
public void run() throws Exception { // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/* w ww . ja v a 2 s . c o m*/ 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.hxr.javatone.concurrency.netty.official.qotm.QuoteOfTheMomentClient.java
License:Apache License
public void run() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {// w w w .j a v a2 s .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.hxr.javatone.concurrency.netty.official.qotm.QuoteOfTheMomentClientHandler.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("QOTM: ")) { System.out.println("Quote of the Moment: " + response.substring(6)); ctx.close();/*w w w.j a v a2 s.c om*/ } }
From source file:com.hxr.javatone.concurrency.netty.official.qotm.QuoteOfTheMomentServerHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception { System.err.println(packet);// w w w . java 2 s .co m if ("QOTM?".equals(packet.content().toString(CharsetUtil.UTF_8))) { ctx.write(new DatagramPacket(Unpooled.copiedBuffer("QOTM: " + nextQuote(), CharsetUtil.UTF_8), packet.sender())); } }
From source file:com.ibasco.agql.protocols.valve.source.query.packets.response.SourcePlayerResponsePacket.java
License:Open Source License
@Override public List<SourcePlayer> toObject() { ByteBuf data = getPayloadBuffer();//from w ww . j a va 2 s .c om List<SourcePlayer> playerList = new ArrayList<>(); byte numOfPlayers = data.readByte(); for (int i = 0; i < numOfPlayers; i++) playerList.add(new SourcePlayer(data.readByte(), ByteBufUtils.readString(data, CharsetUtil.UTF_8), data.readIntLE(), Float.intBitsToFloat(data.readIntLE()))); return playerList; }
From source file:com.imaginarycode.minecraft.bungeejson.impl.httpserver.HttpServerHandler.java
License:Open Source License
private HttpResponse getResponse(ChannelHandlerContext channelHandlerContext, HttpRequest hr) { QueryStringDecoder query = new QueryStringDecoder(hr.getUri()); Multimap<String, String> params = createMultimapFromMap(query.parameters()); Object reply;//from w w w. j av a2s. c o m HttpResponseStatus hrs; final RequestHandler handler = BungeeJSONPlugin.getRequestManager().getHandlerForEndpoint(query.path()); if (handler == null) { reply = BungeeJSONUtilities.error("No such endpoint exists."); hrs = HttpResponseStatus.NOT_FOUND; } else { final ApiRequest ar = new HttpServerApiRequest( ((InetSocketAddress) channelHandlerContext.channel().remoteAddress()).getAddress(), params, bodyBuilder.toString()); try { reply = handler.handle(ar); hrs = HttpResponseStatus.OK; } catch (Throwable throwable) { hrs = HttpResponseStatus.INTERNAL_SERVER_ERROR; reply = BungeeJSONUtilities .error("An internal error has occurred. Information has been logged to the console."); BungeeJSONPlugin.getPlugin().getLogger().log(Level.WARNING, "Error while handling " + hr.getUri() + " from " + ar.getRemoteIp(), throwable); } } String json = BungeeJSONPlugin.getPlugin().getGson().toJson(reply); DefaultFullHttpResponse hreply = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, hrs, Unpooled.wrappedBuffer(json.getBytes(CharsetUtil.UTF_8))); // Add a reminder that we're still running the show. hreply.headers().set("Content-Type", "application/json; charset=UTF-8"); hreply.headers().set("Access-Control-Allow-Origin", "*"); hreply.headers().set("Server", "BungeeJSON/0.1"); hreply.headers().set("Content-Length", json.length()); return hreply; }