List of usage examples for io.netty.channel EventLoopGroup shutdownGracefully
Future<?> shutdownGracefully();
From source file:com.spotify.netty.handler.codec.zmtp.ZMTPTestConnector.java
License:Apache License
public boolean connectAndReceive(final String ip, final int port, final int serverType) { context = ZMQ.context(1);/*www .j av a 2s . co m*/ serverSocket = context.socket(serverType); preConnect(serverSocket); serverSocket.bind("tcp://" + ip + ":" + port); EventLoopGroup group = new NioEventLoopGroup(); // Configure the client. final Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { final ZMTPSession session = new ZMTPSession(ZMTPConnectionType.Addressed, "client".getBytes()); ChannelPipeline pl = ch.pipeline(); pl.addLast(new ZMTP10Codec(session)); pl.addLast(new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (onMessage((ZMTPIncomingMessage) msg)) { receivedMessage = true; ctx.channel().close(); } } }); } }); // Start the connection attempt. final ChannelFuture future = bootstrap.connect(new InetSocketAddress(ip, port)); future.awaitUninterruptibly(); afterConnect(serverSocket, future); // Wait until the connection is closed or the connection attempt fails. future.channel().closeFuture().awaitUninterruptibly(); // Shut down thread pools to exit. group.shutdownGracefully(); serverSocket.close(); context.term(); return receivedMessage; }
From source file:com.springapp.mvc.netty.example.http.snoop.HttpSnoopClient.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(); String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); int port = uri.getPort(); if (port == -1) { if ("http".equalsIgnoreCase(scheme)) { port = 80;// w w w .ja va 2 s .c om } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } } if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) { System.err.println("Only HTTP(S) is supported."); return; } // Configure SSL context if necessary. final boolean ssl = "https".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new HttpSnoopClientInitializer(sslCtx)); // Make the connection attempt. Channel ch = b.connect(host, port).sync().channel(); // Prepare the HTTP request. HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); request.headers().set(HttpHeaders.Names.HOST, host); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); // Set some example cookies. request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder .encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar"))); // Send the HTTP request. ch.writeAndFlush(request); // Wait for the server to close the connection. ch.closeFuture().sync(); } finally { // Shut down executor threads to exit. group.shutdownGracefully(); } }
From source file:com.springapp.mvc.netty.example.http.upload.HttpUploadClient.java
License:Apache License
public static void main(String[] args) throws Exception { String postSimple, postFile, get; if (BASE_URL.endsWith("/")) { postSimple = BASE_URL + "formpost"; postFile = BASE_URL + "formpostmultipart"; get = BASE_URL + "formget"; } else {// w ww . ja va2 s. com postSimple = BASE_URL + "/formpost"; postFile = BASE_URL + "/formpostmultipart"; get = BASE_URL + "/formget"; } URI uriSimple = new URI(postSimple); String scheme = uriSimple.getScheme() == null ? "http" : uriSimple.getScheme(); String host = uriSimple.getHost() == null ? "127.0.0.1" : uriSimple.getHost(); int port = uriSimple.getPort(); if (port == -1) { if ("http".equalsIgnoreCase(scheme)) { port = 80; } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } } if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) { System.err.println("Only HTTP(S) is supported."); return; } final boolean ssl = "https".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } URI uriFile = new URI(postFile); File file = new File(FILE); if (!file.canRead()) { throw new FileNotFoundException(FILE); } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); // setup the factory: here using a mixed memory/disk based on size threshold HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if MINSIZE exceed DiskFileUpload.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit) DiskFileUpload.baseDirectory = null; // system temp directory DiskAttribute.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit) DiskAttribute.baseDirectory = null; // system temp directory try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new HttpUploadClientIntializer(sslCtx)); // Simple Get form: no factory used (not usable) List<Entry<String, String>> headers = formget(b, host, port, get, uriSimple); if (headers == null) { factory.cleanAllHttpDatas(); return; } // Simple Post form: factory used for big attributes List<InterfaceHttpData> bodylist = formpost(b, host, port, uriSimple, file, factory, headers); if (bodylist == null) { factory.cleanAllHttpDatas(); return; } // Multipart Post form: factory used formpostmultipart(b, host, port, uriFile, factory, headers, bodylist); } finally { // Shut down executor threads to exit. group.shutdownGracefully(); // Really clean all temporary files if they still exist factory.cleanAllHttpDatas(); } }
From source file:com.springapp.mvc.netty.example.http.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;/* ww w. j a v a 2 s. c o m*/ } 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) { 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.springapp.mvc.netty.example.localecho.LocalEcho.java
License:Apache License
public static void main(String[] args) throws Exception { // Address to bind on / connect to. final LocalAddress addr = new LocalAddress(PORT); EventLoopGroup serverGroup = new LocalEventLoopGroup(); EventLoopGroup clientGroup = new NioEventLoopGroup(); // NIO event loops are also OK try {// w w w. j ava 2 s .c om // Note that we can use any event loop to ensure certain local channels // are handled by the same event loop thread which drives a certain socket channel // to reduce the communication latency between socket channels and local channels. ServerBootstrap sb = new ServerBootstrap(); sb.group(serverGroup).channel(LocalServerChannel.class) .handler(new ChannelInitializer<LocalServerChannel>() { @Override public void initChannel(LocalServerChannel ch) throws Exception { ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO)); } }).childHandler(new ChannelInitializer<LocalChannel>() { @Override public void initChannel(LocalChannel ch) throws Exception { ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoServerHandler()); } }); Bootstrap cb = new Bootstrap(); cb.group(clientGroup).channel(LocalChannel.class).handler(new ChannelInitializer<LocalChannel>() { @Override public void initChannel(LocalChannel ch) throws Exception { ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoClientHandler()); } }); // Start the server. sb.bind(addr).sync(); // Start the client. Channel ch = cb.connect(addr).sync().channel(); // Read commands from the stdin. System.out.println("Enter text (quit to end)"); ChannelFuture lastWriteFuture = null; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (;;) { String line = in.readLine(); if (line == null || "quit".equalsIgnoreCase(line)) { break; } // Sends the received line to the server. lastWriteFuture = ch.writeAndFlush(line); } // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.awaitUninterruptibly(); } } finally { serverGroup.shutdownGracefully(); clientGroup.shutdownGracefully(); } }
From source file:com.springapp.mvc.netty.example.spdy.client.SpdyClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE) .applicationProtocolConfig(/*from w w w .j a v a 2s . co m*/ new ApplicationProtocolConfig(Protocol.NPN, SelectorFailureBehavior.CHOOSE_MY_LAST_PROTOCOL, SelectedListenerFailureBehavior.CHOOSE_MY_LAST_PROTOCOL, SelectedProtocol.SPDY_3_1.protocolName(), SelectedProtocol.HTTP_1_1.protocolName())) .build(); HttpResponseClientHandler httpResponseHandler = new HttpResponseClientHandler(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.remoteAddress(HOST, PORT); b.handler(new SpdyClientInitializer(sslCtx, httpResponseHandler)); // Start the client. Channel channel = b.connect().syncUninterruptibly().channel(); System.out.println("Connected to " + HOST + ':' + PORT); // Create a GET request. HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""); request.headers().set(HttpHeaders.Names.HOST, HOST); request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); // Send the GET request. channel.writeAndFlush(request).sync(); // Waits for the complete HTTP response httpResponseHandler.queue().take().sync(); System.out.println("Finished SPDY HTTP GET"); // Wait until the connection is closed. channel.close().syncUninterruptibly(); } finally { if (workerGroup != null) { workerGroup.shutdownGracefully(); } } }
From source file:com.springapp.mvc.netty.example.spdy.server.SpdyServer.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. SelfSignedCertificate ssc = new SelfSignedCertificate(); SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()) .applicationProtocolConfig(//from www .jav a 2 s. c om new ApplicationProtocolConfig(Protocol.NPN, SelectorFailureBehavior.CHOOSE_MY_LAST_PROTOCOL, SelectedListenerFailureBehavior.CHOOSE_MY_LAST_PROTOCOL, SelectedProtocol.SPDY_3_1.protocolName(), SelectedProtocol.HTTP_1_1.protocolName())) .build(); // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, 1024); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new SpdyServerInitializer(sslCtx)); Channel ch = b.bind(PORT).sync().channel(); System.err .println("Open your SPDY-enabled web browser and navigate to https://127.0.0.1:" + PORT + '/'); System.err.println("If using Chrome browser, check your SPDY sessions at chrome://net-internals/#spdy"); ch.closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.streamsets.pipeline.lib.network.BaseNettyServer.java
License:Apache License
public void destroy() { LOG.info("Destroying server on address(es) {}", addresses); for (ChannelFuture channelFuture : channelFutures) { if (channelFuture != null && channelFuture.isCancellable()) { channelFuture.cancel(true);//from ww w. j a v a 2 s. c om } } try { for (EventLoopGroup group : groups) { if (group != null && !group.isShutdown() && !group.isShuttingDown()) { try { group.shutdownGracefully().get(); } catch (InterruptedException ex) { LOG.error("InterruptedException thrown while shutting down: " + ex, ex); Thread.currentThread().interrupt(); } catch (Exception ex) { LOG.error("Unexpected error shutting down: " + ex, ex); } } } } finally { channelFutures.clear(); } }
From source file:com.streamsets.pipeline.stage.origin.tcp.TestTCPServerSource.java
License:Apache License
@Test public void runTextRecordsWithAck() throws StageException, IOException, ExecutionException, InterruptedException { final String recordSeparatorStr = "\n"; final String[] expectedRecords = TEN_DELIMITED_RECORDS.split(recordSeparatorStr); final int batchSize = expectedRecords.length; final Charset charset = Charsets.ISO_8859_1; final TCPServerSourceConfig configBean = createConfigBean(charset); configBean.dataFormat = DataFormat.TEXT; configBean.tcpMode = TCPMode.DELIMITED_RECORDS; configBean.recordSeparatorStr = recordSeparatorStr; configBean.ports = NetworkUtils.getRandomPorts(1); configBean.recordProcessedAckMessage = "record_ack_${record:id()}"; configBean.batchCompletedAckMessage = "batch_ack_${batchSize}"; configBean.batchSize = batchSize;//from w w w . j ava 2s . co m final TCPServerSource source = new TCPServerSource(configBean); final String outputLane = "lane"; final PushSourceRunner runner = new PushSourceRunner.Builder(TCPServerDSource.class, source) .addOutputLane(outputLane).build(); final List<Record> records = new LinkedList<>(); runner.runInit(); EventLoopGroup workerGroup = new NioEventLoopGroup(); ChannelFuture channelFuture = startTcpClient(configBean, workerGroup, TEN_DELIMITED_RECORDS.getBytes(charset), true); runner.runProduce(new HashMap<>(), batchSize, output -> { records.addAll(output.getRecords().get(outputLane)); runner.setStop(); }); runner.waitOnProduce(); // Wait until the connection is closed. final Channel channel = channelFuture.channel(); TCPServerSourceClientHandler clientHandler = channel.pipeline().get(TCPServerSourceClientHandler.class); final List<String> responses = new LinkedList<>(); for (int i = 0; i < batchSize + 1; i++) { // one for each record, plus one for the batch responses.add(clientHandler.getResponse()); } channel.close(); workerGroup.shutdownGracefully(); assertThat(records, hasSize(batchSize)); final List<String> expectedAcks = new LinkedList<>(); for (int i = 0; i < records.size(); i++) { // validate the output record value assertThat(records.get(i).get("/text").getValueAsString(), equalTo(expectedRecords[i])); // validate the record-level ack expectedAcks.add(String.format("record_ack_%s", records.get(i).getHeader().getSourceId())); } // validate the batch-level ack expectedAcks.add(String.format("batch_ack_%d", batchSize)); // because of the vagaries of TCP, we can't be sure that a single ack is returned in each discrete read // this is due to the fact that the server can choose to flush the buffer in different ways, and the client // can choose if/how to buffer on its side when reading from the channel // therefore, we will simply combine all acks in the expected order into a single String and assert at that // level, rather than at an individual read/expected ack level final String combinedAcks = StringUtils.join(responses, ""); assertThat(combinedAcks, startsWith(StringUtils.join(expectedAcks, ""))); }
From source file:com.streamsets.pipeline.stage.origin.tcp.TestTCPServerSource.java
License:Apache License
private void runAndCollectRecords(PushSourceRunner runner, TCPServerSourceConfig configBean, List<Record> records, List<Record> errorRecords, int batchSize, String outputLane, byte[] data, boolean randomlySlice, boolean runEmptyProduceAtEnd) throws StageException, InterruptedException, ExecutionException { runner.runInit();/* ww w. j a va 2s.c o m*/ EventLoopGroup workerGroup = new NioEventLoopGroup(); runner.runProduce(new HashMap<>(), batchSize, output -> { records.addAll(output.getRecords().get(outputLane)); if (!runEmptyProduceAtEnd) { runner.setStop(); } }); ChannelFuture channelFuture = startTcpClient(configBean, workerGroup, data, randomlySlice); // Wait until the connection is closed. channelFuture.channel().closeFuture().sync(); // wait for the push source runner produce to complete runner.waitOnProduce(); errorRecords.addAll(runner.getErrorRecords()); if (runEmptyProduceAtEnd) { runner.runProduce(new HashMap<>(), 0, output -> { runner.setStop(); }); runner.waitOnProduce(); } runner.runDestroy(); workerGroup.shutdownGracefully(); }