List of usage examples for io.netty.buffer Unpooled wrappedBuffer
public static ByteBuf wrappedBuffer(ByteBuffer... buffers)
From source file:com.linkedin.pinot.transport.netty.NettySingleConnectionIntegrationTest.java
License:Apache License
@Test /**//from www . ja v a 2 s . co m * Send 10K small sized request in sequence. Verify each request and response. * @throws Exception */ public void test10KSmallRequestResponses() throws Exception { NettyClientMetrics metric = new NettyClientMetrics(null, "abc"); int port = 9089; MyRequestHandler handler = new MyRequestHandler(null, null); MyRequestHandlerFactory handlerFactory = new MyRequestHandlerFactory(handler); NettyTCPServer serverConn = new NettyTCPServer(port, handlerFactory, null); Thread serverThread = new Thread(serverConn, "ServerMain"); serverThread.start(); Thread.sleep(1000); ServerInstance server = new ServerInstance("localhost", port); EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); NettyTCPClientConnection clientConn = new NettyTCPClientConnection(server, eventLoopGroup, new HashedWheelTimer(), metric); try { LOGGER.info("About to connect the client !!"); boolean connected = clientConn.connect(); LOGGER.info("Client connected !!"); Assert.assertTrue(connected, "connected"); Thread.sleep(1000); for (int i = 0; i < 10000; i++) { String request = "dummy request :" + i; String response = "dummy response :" + i; handler.setResponse(response); LOGGER.info("Sending the request (" + request + ")"); ResponseFuture serverRespFuture = clientConn.sendRequest(Unpooled.wrappedBuffer(request.getBytes()), 1L, 5000L); LOGGER.info("Request sent !!"); ByteBuf serverResp = serverRespFuture.getOne(); if (null == serverResp) { LOGGER.error("Got unexpected error while trying to get response.", serverRespFuture.getError()); } byte[] b2 = new byte[serverResp.readableBytes()]; serverResp.readBytes(b2); String gotResponse = new String(b2); Assert.assertEquals(gotResponse, response, "Response Check at client"); Assert.assertEquals(handler.getRequest(), request, "Request Check at server"); } } finally { if (null != clientConn) { clientConn.close(); } if (null != serverConn) { serverConn.shutdownGracefully(); } } }
From source file:com.linkedin.pinot.transport.netty.NettySingleConnectionIntegrationTest.java
License:Apache License
/** * Send 100 large ( 2MB) sized request in sequence. Verify each request and response. * @throws Exception/*from w w w. ja va 2 s . c om*/ */ //@Test public void test100LargeRequestResponses() throws Exception { NettyClientMetrics metric = new NettyClientMetrics(null, "abc"); int port = 9089; MyRequestHandler handler = new MyRequestHandler(null, null); MyRequestHandlerFactory handlerFactory = new MyRequestHandlerFactory(handler); NettyTCPServer serverConn = new NettyTCPServer(port, handlerFactory, null); Thread serverThread = new Thread(serverConn, "ServerMain"); serverThread.start(); Thread.sleep(1000); ServerInstance server = new ServerInstance("localhost", port); EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); NettyTCPClientConnection clientConn = new NettyTCPClientConnection(server, eventLoopGroup, new HashedWheelTimer(), metric); LOGGER.info("About to connect the client !!"); boolean connected = clientConn.connect(); LOGGER.info("Client connected !!"); Assert.assertTrue(connected, "connected"); Thread.sleep(1000); try { for (int i = 0; i < 100; i++) { String request_prefix = "request_"; String request = generatePayload(request_prefix, 1024 * 1024 * 20); String response_prefix = "response_"; String response = generatePayload(response_prefix, 1024 * 1024 * 20); handler.setResponse(response); //LOG.info("Sending the request (" + request + ")"); ResponseFuture serverRespFuture = clientConn.sendRequest(Unpooled.wrappedBuffer(request.getBytes()), 1L, 5000L); //LOG.info("Request sent !!"); ByteBuf serverResp = serverRespFuture.getOne(); byte[] b2 = new byte[serverResp.readableBytes()]; serverResp.readBytes(b2); String gotResponse = new String(b2); Assert.assertEquals(gotResponse, response, "Response Check at client"); Assert.assertEquals(handler.getRequest(), request, "Request Check at server"); } } finally { if (null != clientConn) { clientConn.close(); } if (null != serverConn) { serverConn.shutdownGracefully(); } } }
From source file:com.linkedin.proxy.netty.MysqlQueryEncoder.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, MysqlQuery msg, List<Object> out) throws Exception { FullHttpResponse response = null;//from ww w . j a v a 2 s .c om if (msg.isSuccessfull()) { switch (msg.getType()) { case WRITE: case DELETE: case CREATE: response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "octet-stream"); response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes()); break; case READ: response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(msg.getValue())); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "octet-stream"); response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes()); break; default: break; } } else { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT); } out.add(response); }
From source file:com.linkedin.proxy.netty.RocksdbQueryEncoder.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, Query msg, List<Object> out) throws Exception { FullHttpResponse response = null;/*w ww . j a va 2 s . c o m*/ if (msg.isSuccessfull()) { switch (msg.getType()) { case WRITE: case DELETE: response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "octet-stream"); response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes()); break; case READ: response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(msg.getValue())); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "octet-stream"); response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes()); break; default: break; } } else { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT); } _LOG.debug("Query encoded"); out.add(response); }
From source file:com.linkedin.r2.transport.http.client.Http2StreamCodec.java
License:Apache License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (!(msg instanceof RequestWithCallback)) { ctx.write(msg, promise);/*www .j a v a 2 s . com*/ return; } Request request = ((RequestWithCallback) msg).request(); Http2ConnectionEncoder encoder = encoder(); int streamId = connection().local().incrementAndGetNextStreamId(); if (request instanceof StreamRequest) { LOG.debug("Writing StreamRequest..."); StreamRequest streamRequest = (StreamRequest) request; Http2Headers http2Headers = NettyRequestAdapter.toHttp2Headers(streamRequest); BufferedReader reader = new BufferedReader(ctx, encoder, streamId, ((RequestWithCallback) msg).handle()); streamRequest.getEntityStream().setReader(reader); encoder.writeHeaders(ctx, streamId, http2Headers, NO_PADDING, NOT_END_STREAM, promise) .addListener(future -> reader.request()); LOG.debug("Sent HTTP/2 HEADERS frame, stream={}, end={}, headers={}, padding={}bytes", new Object[] { streamId, NOT_END_STREAM, http2Headers.size(), NO_PADDING }); } else if (request instanceof RestRequest) { LOG.debug("Writing RestRequest..."); PromiseCombiner promiseCombiner = new PromiseCombiner(); ChannelPromise headersPromise = ctx.channel().newPromise(); ChannelPromise dataPromise = ctx.channel().newPromise(); promiseCombiner.add(headersPromise); promiseCombiner.add(dataPromise); promiseCombiner.finish(promise); RestRequest restRequest = (RestRequest) request; Http2Headers headers = NettyRequestAdapter.toHttp2Headers(restRequest); encoder.writeHeaders(ctx, streamId, headers, NO_PADDING, NOT_END_STREAM, headersPromise); LOG.debug("Sent HTTP/2 HEADERS frame, stream={}, end={}, headers={}, padding={}bytes", new Object[] { streamId, NOT_END_STREAM, headers.size(), NO_PADDING }); ByteBuf data = Unpooled.wrappedBuffer(restRequest.getEntity().asByteBuffer()); encoder.writeData(ctx, streamId, data, NO_PADDING, END_STREAM, dataPromise); LOG.debug("Sent HTTP/2 DATA frame, stream={}, end={}, data={}bytes, padding={}bytes", new Object[] { streamId, END_STREAM, data.readableBytes(), NO_PADDING }); } else { // Request type is not supported. Returns channel back to the pool and throws exception. ctx.fireChannelRead(((RequestWithCallback) msg).handle()); throw new IllegalArgumentException("Request is neither StreamRequest or RestRequest"); } // Sets TransportCallback as a stream property to be retrieved later TransportCallback<?> callback = ((RequestWithCallback) msg).callback(); Http2Connection.PropertyKey callbackKey = ctx.channel() .attr(Http2ClientPipelineInitializer.CALLBACK_ATTR_KEY).get(); connection().stream(streamId).setProperty(callbackKey, callback); // Sets AsyncPoolHandle as a stream property to be retrieved later AsyncPoolHandle<?> handle = ((RequestWithCallback) msg).handle(); Http2Connection.PropertyKey handleKey = ctx.channel() .attr(Http2ClientPipelineInitializer.CHANNEL_POOL_HANDLE_ATTR_KEY).get(); connection().stream(streamId).setProperty(handleKey, handle); }
From source file:com.linkedin.r2.transport.http.client.NettyRequestAdapter.java
License:Apache License
/** * Adapts a RestRequest to Netty's HttpRequest * @param request R2 rest request//from w w w .j ava 2s . co m * @return Adapted HttpRequest. */ static HttpRequest toNettyRequest(RestRequest request) throws Exception { HttpMethod nettyMethod = HttpMethod.valueOf(request.getMethod()); URL url = new URL(request.getURI().toString()); String path = url.getFile(); // RFC 2616, section 5.1.2: // Note that the absolute path cannot be empty; if none is present in the original URI, // it MUST be given as "/" (the server root). if (path.isEmpty()) { path = "/"; } ByteBuf content = Unpooled.wrappedBuffer(request.getEntity().asByteBuffer()); HttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, nettyMethod, path, content); nettyRequest.headers().set(HttpConstants.CONTENT_LENGTH, request.getEntity().length()); for (Map.Entry<String, String> entry : request.getHeaders().entrySet()) { nettyRequest.headers().set(entry.getKey(), entry.getValue()); } nettyRequest.headers().set(HttpHeaderNames.HOST, url.getAuthority()); nettyRequest.headers().set(HttpConstants.REQUEST_COOKIE_HEADER_NAME, request.getCookies()); return nettyRequest; }
From source file:com.look.netty.demo.client.WebSocketClient.java
License:Apache License
public static void main(String[] args) throws Exception { URI uri = new URI(URL); String scheme = uri.getScheme() == null ? "ws" : uri.getScheme(); final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); final int port; if (uri.getPort() == -1) { if ("ws".equalsIgnoreCase(scheme)) { port = 80;// w ww .j a v a2s. co m } else if ("wss".equalsIgnoreCase(scheme)) { port = 443; } else { port = -1; } } else { port = uri.getPort(); } if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) { System.err.println("Only WS(S) is supported."); return; } final boolean ssl = "wss".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } EventLoopGroup group = new NioEventLoopGroup(); try { // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. // If you change it to V00, ping is not supported and remember to change // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory .newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc(), host, port)); } p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler); } }); Channel ch = b.connect(uri.getHost(), port).sync().channel(); handler.handshakeFuture().sync(); BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); while (true) { String msg = console.readLine(); if (msg == null) { break; } else if ("bye".equals(msg.toLowerCase())) { ch.writeAndFlush(new CloseWebSocketFrame()); ch.closeFuture().sync(); break; } else if ("ping".equals(msg.toLowerCase())) { WebSocketFrame frame = new PingWebSocketFrame( Unpooled.wrappedBuffer(new byte[] { 8, 1, 8, 1 })); ch.writeAndFlush(frame); } else { WebSocketFrame frame = new TextWebSocketFrame(msg); ch.writeAndFlush(frame); } } } finally { group.shutdownGracefully(); } }
From source file:com.lxz.talk.websocketx.client.WebSocketClient.java
License:Apache License
public static void main(String[] args) throws Exception { URI uri = new URI(URL); String scheme = uri.getScheme() == null ? "http" : uri.getScheme(); final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); final int port; if (uri.getPort() == -1) { if ("http".equalsIgnoreCase(scheme)) { port = 80;/*from ww w. j a v a 2 s. c om*/ } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } else { port = -1; } } else { port = uri.getPort(); } if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) { System.err.println("Only WS(S) is supported."); return; } final boolean ssl = "wss".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } else { sslCtx = null; } EventLoopGroup group = new NioEventLoopGroup(); try { // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. // If you change it to V00, ping is not supported and remember to change // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory .newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc(), host, port)); } p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler); } }); Channel ch = b.connect(uri.getHost(), port).sync().channel(); handler.handshakeFuture().sync(); BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); while (true) { String msg = console.readLine(); if (msg == null) { break; } else if ("bye".equals(msg.toLowerCase())) { ch.writeAndFlush(new CloseWebSocketFrame()); ch.closeFuture().sync(); break; } else if ("ping".equals(msg.toLowerCase())) { WebSocketFrame frame = new PingWebSocketFrame( Unpooled.wrappedBuffer(new byte[] { 8, 1, 8, 1 })); ch.writeAndFlush(frame); } else { WebSocketFrame frame = new TextWebSocketFrame(msg); ch.writeAndFlush(frame); } } } finally { group.shutdownGracefully(); } }
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 ww w .jav a 2 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.mc.netty.handler.coder.ImMessageEncoder.java
License:Open Source License
@Override protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception { byte[] data = ((OutMessage) msg).toBytes(); System.out.println("get messge, begin encodes......"); out.add(Unpooled.wrappedBuffer(data)); }