List of usage examples for io.netty.channel ChannelFuture addListener
@Override ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);
From source file:com.hxr.javatone.concurrency.netty.official.factorial.FactorialClientHandler.java
License:Apache License
private void sendNumbers() { // Do not send more than 4096 numbers. ChannelFuture future = null; for (int i = 0; i < 4096 && next <= count; i++) { future = ctx.write(Integer.valueOf(next)); next++;/*from w w w. j a v a2s.c o m*/ } if (next <= count) { assert future != null; future.addListener(numberSender); } ctx.flush(); }
From source file:com.hxr.javatone.concurrency.netty.official.proxy.HexDumpProxyFrontendHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { final Channel inboundChannel = ctx.channel(); // Start the connection attempt. Bootstrap b = new Bootstrap(); b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass()) .handler(new HexDumpProxyBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false); ChannelFuture f = b.connect(remoteHost, remotePort); outboundChannel = f.channel();//from w ww .j av a 2 s.com f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // connection complete start to read first data inboundChannel.read(); } else { // Close the connection if the connection attempt has failed. inboundChannel.close(); } } }); }
From source file:com.hxr.javatone.concurrency.netty.official.telnet.TelnetServerHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, String request) throws Exception { // Generate and write a response. String response;/* www.ja v a 2s.co m*/ boolean close = false; if (request.isEmpty()) { response = "Please type something.\r\n"; } else if ("bye".equals(request.toLowerCase())) { response = "Have a good day!\r\n"; close = true; } else { response = "Did you say '" + request + "'?\r\n"; } // We do not need to write a ChannelBuffer here. // We know the encoder inserted at TelnetPipelineFactory will do the conversion. ChannelFuture future = ctx.write(response); // Close the connection after sending 'Have a good day!' // if the client has sent 'bye'. if (close) { future.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.ibasco.agql.core.transport.NettyTransport.java
License:Open Source License
/** * <p>A method to send data over the transport. Since the current netty version does not yet support {@link * CompletableFuture}, we need to convert the returned {@link ChannelFuture} to it's {@link CompletableFuture} * version.</p>//from w w w . ja v a2s . c o m * * @param channel * The underlying {@link Channel} to be used for data transport. * @param data * An instance of {@link AbstractMessage} that will be sent through the transport * @param flushImmediately * True if transport should immediately flush the message after send. * * @return A {@link CompletableFuture} with return type of {@link Channel} (The channel used for the transport) */ private CompletableFuture<Void> writeToChannel(Channel channel, Msg data, boolean flushImmediately) { final CompletableFuture<Void> writeResultFuture = new CompletableFuture<>(); log.debug("Writing data '{}' to channel : {}", data, channel); final ChannelFuture writeFuture = (flushImmediately) ? channel.writeAndFlush(data) : channel.write(data); writeFuture.addListener((ChannelFuture future) -> { try { if (future.isSuccess()) writeResultFuture.complete(null); else writeResultFuture.completeExceptionally(future.cause()); } finally { cleanupChannel(future.channel()); } }); return writeResultFuture; }
From source file:com.ibasco.agql.core.transport.tcp.NettyBasicTcpTransport.java
License:Open Source License
@Override public CompletableFuture<Channel> getChannel(M address) { final CompletableFuture<Channel> channelFuture = new CompletableFuture<>(); ChannelFuture f = getBootstrap().connect(address.recipient()); //Acquire from pool and listen for completion f.addListener((ChannelFuture future) -> { if (future.isSuccess()) { channelFuture.complete(future.channel()); } else {/*from w ww .j a v a2s . c om*/ channelFuture.completeExceptionally(future.cause()); } }); return channelFuture; }
From source file:com.ibasco.agql.protocols.valve.source.query.logger.SourceLogListenService.java
License:Open Source License
/** * Start listening for log messages// ww w . j av a 2 s . co m */ public void listen() throws InterruptedException { final ChannelFuture bindFuture = bootstrap.localAddress(listenAddress).bind().await(); bindFuture.addListener((ChannelFuture future) -> { String hostAddress = ((InetSocketAddress) future.channel().localAddress()).getAddress() .getHostAddress(); int port = ((InetSocketAddress) future.channel().localAddress()).getPort(); log.debug("Log Service listening on port {} via address {}", port, hostAddress); future.channel().closeFuture().addListener(future1 -> log.debug("Service Shutting Down")); }); }
From source file:com.ibm.mqlight.api.impl.network.NettyNetworkService.java
License:Apache License
@Override public void connect(Endpoint endpoint, NetworkListener listener, Promise<NetworkChannel> promise) { final String methodName = "connect"; logger.entry(this, methodName, endpoint, listener, promise); SslContext sslCtx = null;/*from w w w. ja va2 s .c o m*/ try { if (endpoint.getCertChainFile() != null && endpoint.getCertChainFile().exists()) { try (FileInputStream fileInputStream = new FileInputStream(endpoint.getCertChainFile())) { KeyStore jks = KeyStore.getInstance("JKS"); jks.load(fileInputStream, null); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(jks); sslCtx = SslContext.newClientContext(); if (sslCtx instanceof JdkSslContext) { ((JdkSslContext) sslCtx).context().init(null, trustManagerFactory.getTrustManagers(), null); } } catch (IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException | KeyManagementException e) { logger.data(this, methodName, e.toString()); } } // fallback to passing as .PEM file (or null, which loads default cacerts) if (sslCtx == null) { sslCtx = SslContext.newClientContext(endpoint.getCertChainFile()); } final SSLEngine sslEngine = sslCtx.newEngine(null, endpoint.getHost(), endpoint.getPort()); sslEngine.setUseClientMode(true); final LinkedList<String> enabledProtocols = new LinkedList<String>() { private static final long serialVersionUID = 7838479468739671083L; { for (String protocol : sslEngine.getSupportedProtocols()) { if (!disabledProtocolPattern.matcher(protocol).matches()) { add(protocol); } } } }; sslEngine.setEnabledProtocols(enabledProtocols.toArray(new String[0])); logger.data(this, methodName, "enabledProtocols", Arrays.toString(sslEngine.getEnabledProtocols())); final LinkedList<String> enabledCipherSuites = new LinkedList<String>() { private static final long serialVersionUID = 7838479468739671083L; { for (String cipher : sslEngine.getSupportedCipherSuites()) { if (!disabledCipherPattern.matcher(cipher).matches()) { add(cipher); } } } }; sslEngine.setEnabledCipherSuites(enabledCipherSuites.toArray(new String[0])); logger.data(this, methodName, "enabledCipherSuites", Arrays.toString(sslEngine.getEnabledCipherSuites())); if (endpoint.getVerifyName()) { SSLParameters sslParams = sslEngine.getSSLParameters(); sslParams.setEndpointIdentificationAlgorithm("HTTPS"); sslEngine.setSSLParameters(sslParams); } // The listener must be added to the ChannelFuture before the bootstrap channel initialisation completes (i.e. // before the NettyInboundHandler is added to the channel pipeline) otherwise the listener may not be able to // see the NettyInboundHandler, when its operationComplete() method is called (there is a small window where // the socket connection fails just after initChannel has complete but before ConnectListener is added, with // the ConnectListener.operationComplete() being called as though the connection was successful) // Hence we synchronise here and within the ChannelInitializer.initChannel() method. synchronized (bootstrapSync) { final ChannelHandler handler; if (endpoint.useSsl()) { handler = new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { synchronized (bootstrapSync) { ch.pipeline().addFirst(new SslHandler(sslEngine)); ch.pipeline().addLast(new NettyInboundHandler(ch)); } } }; } else { handler = new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { synchronized (bootstrapSync) { ch.pipeline().addLast(new NettyInboundHandler(ch)); } } }; } final Bootstrap bootstrap = getBootstrap(endpoint.useSsl(), sslEngine, handler); final ChannelFuture f = bootstrap.connect(endpoint.getHost(), endpoint.getPort()); f.addListener(new ConnectListener(endpoint, f, promise, listener)); } } catch (SSLException e) { if (e.getCause() == null) { promise.setFailure(new SecurityException(e.getMessage(), e)); } else { promise.setFailure(new SecurityException(e.getCause().getMessage(), e.getCause())); } } logger.exit(this, methodName); }
From source file:com.informatica.surf.sources.http.HttpServerHandler.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 . jav a 2 s . c om*/ buf.release(); setContentLength(res, res.content().readableBytes()); } else { setContentLength(res, 0); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.jansegre.jwar.webapi.FileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { request.retain();//from ww w . ja va 2 s . co m if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST); ctx.fireChannelRead(request); return; } if (request.getMethod() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); ctx.fireChannelRead(request); return; } final String uri = request.getUri(); final String path = sanitizeUri(uri); if (path == null) { sendError(ctx, FORBIDDEN); ctx.fireChannelRead(request); return; } //XXX: notice hardcoded socket.io namespace if (uri.startsWith("/socket.io")) { ctx.fireChannelRead(request); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { File index_file = new File(sanitizeUri(uri + INDEX_FILE)); if (index_file.exists()) { file = index_file; } else { sendListing(ctx, file); return; } } else { sendRedirect(ctx, uri + '/'); return; } } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } // Cache Validation String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince); // Only compare up to the second because the datetime format we send to the client // does not have milliseconds long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000; long fileLastModifiedSeconds = file.lastModified() / 1000; if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) { sendNotModified(ctx); return; } } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException fnfe) { sendError(ctx, NOT_FOUND); return; } long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } // Write the initial line and the header. ctx.write(response); // Write the content. ChannelFuture sendFileFuture; if (useSendFile) { sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); } else { sendFileFuture = ctx.write(new ChunkedFile(raf, 0, fileLength, 8192), ctx.newProgressivePromise()); } sendFileFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { if (total < 0) { // total unknown System.err.println("Transfer progress: " + progress); } else { System.err.println("Transfer progress: " + progress + " / " + total); } } @Override public void operationComplete(ChannelProgressiveFuture future) throws Exception { System.err.println("Transfer complete."); } }); // Write the end marker ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); // Decide whether to close the connection or not. if (!isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.jjneko.jjnet.networking.http.server.WebSocketHttpServerHandler.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.status().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf);// w ww . 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.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }