List of usage examples for io.netty.channel ChannelFuture cause
Throwable cause();
From source file:org.thingsplode.synapse.proxy.Dispatcher.java
License:Apache License
/** * * @param request {@link Request} or {@link Event} * @param requestTimeout in milliseconds * @return {@link DispatchedFuture}/* w w w. j ava 2 s . c o m*/ * @throws InterruptedException when the channel is inactive and * reconnection is interrupted */ public DispatchedFuture<Request, Response> dispatch(Request request, long requestTimeout) throws InterruptedException { checkChannel(); request.getHeader().setMsgId(idGeneratorStrategy.getNextId()); DispatchedFuture<Request, Response> dispatcherFuture = new DispatchedFuture<>(request, channel, requestTimeout); if (pattern != null && (pattern == DispatcherPattern.CORRELATED_ASYNC || pattern == DispatcherPattern.BLOCKING_REQUEST)) { dispatchedFutureHandler.beforeDispatch(dispatcherFuture); } ChannelFuture cf = channel.writeAndFlush(request); cf.addListener((ChannelFutureListener) (ChannelFuture future) -> { if (!future.isSuccess()) { //the message could not be sent //todo: build a retry mechanism? dispatchedFutureHandler.responseReceived(request.getHeader().getMsgId()); dispatcherFuture.completeExceptionally(future.cause()); future.channel().close(); } else if (logger.isTraceEnabled()) { logger.trace("Request message is succesfully dispatched with Msg. Id.: " + request.getHeader().getMsgId()); } }); return dispatcherFuture; }
From source file:org.vertx.java.core.http.impl.DefaultHttpClient.java
License:Open Source License
void internalConnect(final Handler<ClientConnection> connectHandler, final Handler<Throwable> connectErrorHandler) { if (bootstrap == null) { // Share the event loop thread to also serve the HttpClient's network traffic. VertxEventLoopGroup pool = new VertxEventLoopGroup(); pool.addWorker(actualCtx.getEventLoop()); bootstrap = new Bootstrap(); bootstrap.group(pool);/* www . j a va 2s.c om*/ bootstrap.channel(NioSocketChannel.class); tcpHelper.checkSSL(vertx); bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (tcpHelper.isSSL()) { SSLEngine engine = tcpHelper.getSSLContext().createSSLEngine(host, port); if (tcpHelper.isVerifyHost()) { SSLParameters sslParameters = engine.getSSLParameters(); sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(sslParameters); } engine.setUseClientMode(true); //We are on the client side of the connection pipeline.addLast("ssl", new SslHandler(engine)); } pipeline.addLast("codec", new HttpClientCodec(4096, 8192, 8192, false, false)); if (tryUseCompression) { pipeline.addLast("inflater", new HttpContentDecompressor(true)); } pipeline.addLast("handler", new ClientHandler()); } }); } tcpHelper.applyConnectionOptions(bootstrap); ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); future.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture channelFuture) throws Exception { final Channel ch = channelFuture.channel(); if (channelFuture.isSuccess()) { if (tcpHelper.isSSL()) { // TCP connected, so now we must do the SSL handshake SslHandler sslHandler = ch.pipeline().get(SslHandler.class); Future<Channel> fut = sslHandler.handshakeFuture(); fut.addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(Future<Channel> future) throws Exception { if (future.isSuccess()) { connected(ch, connectHandler); } else { connectionFailed(ch, connectErrorHandler, new SSLHandshakeException("Failed to create SSL connection")); } } }); } else { connected(ch, connectHandler); } } else { connectionFailed(ch, connectErrorHandler, channelFuture.cause()); } } }); }
From source file:org.vertx.java.core.http.impl.DefaultHttpServer.java
License:Open Source License
public HttpServer listen(int port, String host, final Handler<AsyncResult<HttpServer>> listenHandler) { if (requestHandler == null && wsHandler == null) { throw new IllegalStateException("Set request or websocket handler first"); }/*from ww w. ja v a2s .com*/ if (listening) { throw new IllegalStateException("Listen already called"); } listening = true; synchronized (vertx.sharedHttpServers()) { id = new ServerID(port, host); serverOrigin = (isSSL() ? "https" : "http") + "://" + host + ":" + port; DefaultHttpServer shared = vertx.sharedHttpServers().get(id); if (shared == null) { serverChannelGroup = new DefaultChannelGroup("vertx-acceptor-channels", GlobalEventExecutor.INSTANCE); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(availableWorkers); bootstrap.channel(NioServerSocketChannel.class); tcpHelper.applyConnectionOptions(bootstrap); tcpHelper.checkSSL(vertx); bootstrap.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (tcpHelper.isSSL()) { SSLEngine engine = tcpHelper.getSSLContext().createSSLEngine(); engine.setUseClientMode(false); switch (tcpHelper.getClientAuth()) { case REQUEST: { engine.setWantClientAuth(true); break; } case REQUIRED: { engine.setNeedClientAuth(true); break; } case NONE: { engine.setNeedClientAuth(false); break; } } pipeline.addLast("ssl", new SslHandler(engine)); } pipeline.addLast("flashpolicy", new FlashPolicyHandler()); pipeline.addLast("httpDecoder", new HttpRequestDecoder(4096, 8192, 8192, false)); pipeline.addLast("httpEncoder", new VertxHttpResponseEncoder()); if (compressionSupported) { pipeline.addLast("deflater", new HttpChunkContentCompressor()); } if (tcpHelper.isSSL() || compressionSupported) { // only add ChunkedWriteHandler when SSL is enabled otherwise it is not needed as FileRegion is used. pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // For large file / sendfile support } pipeline.addLast("handler", new ServerHandler()); } }); addHandlers(this); try { bindFuture = bootstrap.bind(new InetSocketAddress(InetAddress.getByName(host), port)); Channel serverChannel = bindFuture.channel(); serverChannelGroup.add(serverChannel); bindFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { if (!channelFuture.isSuccess()) { vertx.sharedHttpServers().remove(id); } } }); } catch (final Throwable t) { // Make sure we send the exception back through the handler (if any) if (listenHandler != null) { vertx.runOnContext(new VoidHandler() { @Override protected void handle() { listenHandler.handle(new DefaultFutureResult<HttpServer>(t)); } }); } else { // No handler - log so user can see failure actualCtx.reportException(t); } listening = false; return this; } vertx.sharedHttpServers().put(id, this); actualServer = this; } else { // Server already exists with that host/port - we will use that actualServer = shared; addHandlers(actualServer); } actualServer.bindFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (listenHandler != null) { final AsyncResult<HttpServer> res; if (future.isSuccess()) { res = new DefaultFutureResult<HttpServer>(DefaultHttpServer.this); } else { res = new DefaultFutureResult<>(future.cause()); listening = false; } actualCtx.execute(future.channel().eventLoop(), new Runnable() { @Override public void run() { listenHandler.handle(res); } }); } else if (!future.isSuccess()) { listening = false; // No handler - log so user can see failure actualCtx.reportException(future.cause()); } } }); } return this; }
From source file:org.vertx.java.core.http.impl.DefaultHttpServerResponse.java
License:Open Source License
private void doSendFile(String filename, String notFoundResource, final Handler<AsyncResult<Void>> resultHandler) { if (headWritten) { throw new IllegalStateException("Head already written"); }/*w w w . j av a 2 s.com*/ checkWritten(); File file = new File(PathAdjuster.adjust(vertx, filename)); if (!file.exists()) { if (notFoundResource != null) { setStatusCode(HttpResponseStatus.NOT_FOUND.code()); sendFile(notFoundResource, (String) null, resultHandler); } else { sendNotFound(); } } else { if (!contentLengthSet()) { putHeader(org.vertx.java.core.http.HttpHeaders.CONTENT_LENGTH, String.valueOf(file.length())); } if (!contentTypeSet()) { int li = filename.lastIndexOf('.'); if (li != -1 && li != filename.length() - 1) { String ext = filename.substring(li + 1, filename.length()); String contentType = MimeMapping.getMimeTypeForExtension(ext); if (contentType != null) { putHeader(org.vertx.java.core.http.HttpHeaders.CONTENT_TYPE, contentType); } } } prepareHeaders(); conn.queueForWrite(response); conn.sendFile(file); // write an empty last content to let the http encoder know the response is complete channelFuture = conn.write(LastHttpContent.EMPTY_LAST_CONTENT); headWritten = written = true; if (resultHandler != null) { channelFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { final AsyncResult<Void> res; if (future.isSuccess()) { res = new DefaultFutureResult<>((Void) null); } else { res = new DefaultFutureResult<>(future.cause()); } vertx.runOnContext(new Handler<Void>() { @Override public void handle(Void v) { resultHandler.handle(res); } }); } }); } if (!keepAlive) { closeConnAfterWrite(); } conn.responseComplete(); } }
From source file:org.vertx.java.core.net.impl.DefaultNetClient.java
License:Open Source License
private void connect(final int port, final String host, final Handler<AsyncResult<NetSocket>> connectHandler, final int remainingAttempts) { if (bootstrap == null) { tcpHelper.checkSSL(vertx);//w ww . ja v a2 s. c o m bootstrap = new Bootstrap(); bootstrap.group(actualCtx.getEventLoop()); bootstrap.channel(NioSocketChannel.class); bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (tcpHelper.isSSL()) { SslHandler sslHandler = tcpHelper.createSslHandler(vertx, true); pipeline.addLast("ssl", sslHandler); } if (tcpHelper.isSSL()) { // only add ChunkedWriteHandler when SSL is enabled otherwise it is not needed as FileRegion is used. pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // For large file / sendfile support } pipeline.addLast("handler", new VertxNetHandler(vertx, socketMap)); } }); configurable = false; } tcpHelper.applyConnectionOptions(bootstrap); ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); future.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture channelFuture) throws Exception { final Channel ch = channelFuture.channel(); if (channelFuture.isSuccess()) { if (tcpHelper.isSSL()) { // TCP connected, so now we must do the SSL handshake SslHandler sslHandler = ch.pipeline().get(SslHandler.class); Future<Channel> fut = sslHandler.handshakeFuture(); fut.addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(Future<Channel> future) throws Exception { if (future.isSuccess()) { connected(ch, connectHandler); } else { failed(ch, future.cause(), connectHandler); } } }); } else { connected(ch, connectHandler); } } else { if (remainingAttempts > 0 || remainingAttempts == -1) { actualCtx.execute(ch.eventLoop(), new Runnable() { public void run() { log.debug("Failed to create connection. Will retry in " + reconnectInterval + " milliseconds"); //Set a timer to retry connection vertx.setTimer(reconnectInterval, new Handler<Long>() { public void handle(Long timerID) { connect(port, host, connectHandler, remainingAttempts == -1 ? remainingAttempts : remainingAttempts - 1); } }); } }); } else { failed(ch, channelFuture.cause(), connectHandler); } } } }); }
From source file:org.vertx.java.core.net.impl.DefaultNetSocket.java
License:Open Source License
@Override public NetSocket sendFile(String filename, final Handler<AsyncResult<Void>> resultHandler) { File f = new File(PathAdjuster.adjust(vertx, filename)); ChannelFuture future = super.sendFile(f); if (resultHandler != null) { future.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { final AsyncResult<Void> res; if (future.isSuccess()) { res = new DefaultFutureResult<>((Void) null); } else { res = new DefaultFutureResult<>(future.cause()); }/*from ww w.j a va2 s .com*/ vertx.runOnContext(new Handler<Void>() { @Override public void handle(Void v) { resultHandler.handle(res); } }); } }); } return this; }
From source file:org.waarp.commandexec.client.test.LocalExecClientTest.java
License:Open Source License
/** * Connect to the Server//from w ww . j a v a 2 s . co m */ private boolean connect() { // Start the connection attempt. ChannelFuture future = bootstrap.connect(address); // Wait until the connection attempt succeeds or fails. try { channel = future.await().sync().channel(); } catch (InterruptedException e) { } if (!future.isSuccess()) { System.err.println("Client Not Connected"); future.cause().printStackTrace(); return false; } return true; }
From source file:org.waarp.commandexec.ssl.client.test.LocalExecSslClientTest.java
License:Open Source License
/** * Connect to the Server/* w w w .j a va 2 s .c o m*/ */ private boolean connect() { // Start the connection attempt. ChannelFuture future = bootstrap.connect(address); // Wait until the connection attempt succeeds or fails. channel = WaarpSslUtility.waitforChannelReady(future); if (channel == null) { System.err.println("Client Not Connected"); if (future.cause() != null) { future.cause().printStackTrace(); } return false; } return true; }
From source file:org.waarp.common.crypto.ssl.WaarpSslUtility.java
License:Open Source License
/** * Waiting for the channel to be opened and ready (Client side) (blocking call) * /*from ww w .j a va 2 s . c o m*/ * @param future * a future on connect only * @return the channel if correctly associated, else return null */ public static Channel waitforChannelReady(ChannelFuture future) { // Wait until the connection attempt succeeds or fails. try { future.await(10000); } catch (InterruptedException e1) { } if (!future.isSuccess()) { logger.error("Channel not connected", future.cause()); return null; } Channel channel = future.channel(); if (waitForHandshake(channel)) { return channel; } return null; }
From source file:org.waarp.ftp.core.control.NetworkHandler.java
License:Open Source License
/** * Execute one command and write the following answer */// w w w .j ava 2 s . c om private void messageRunAnswer(final ChannelHandlerContext ctx) { boolean error = false; logger.debug("Code: " + session.getCurrentCommand().getCode()); try { businessHandler.beforeRunCommand(); AbstractCommand command = session.getCurrentCommand(); logger.debug("Run {}", command.getCommand()); command.exec(); businessHandler.afterRunCommandOk(); } catch (CommandAbstractException e) { logger.debug("Command in error", e); error = true; session.setReplyCode(e); businessHandler.afterRunCommandKo(e); } logger.debug("Code: " + session.getCurrentCommand().getCode() + " [" + session.getReplyCode() + "]"); if (error) { if (session.getCurrentCommand().getCode() != FtpCommandCode.INTERNALSHUTDOWN) { writeFinalAnswer(ctx); } // In error so Check that Data is closed if (session.getDataConn().isActive()) { logger.debug("Closing DataChannel while command is in error"); try { session.getDataConn().getCurrentDataChannel().close(); } catch (FtpNoConnectionException e) { // ignore } } return; } if (session.getCurrentCommand().getCode() == FtpCommandCode.AUTH || session.getCurrentCommand().getCode() == FtpCommandCode.CCC) { controlChannel.config().setAutoRead(false); ChannelFuture future = writeIntermediateAnswer(ctx); session.setCurrentCommandFinished(); if (session.getCurrentCommand().getCode() == FtpCommandCode.AUTH) { logger.debug("SSL to be added to pipeline"); ChannelHandler sslHandler = ctx.pipeline().first(); if (sslHandler instanceof SslHandler) { logger.debug("Already got a SslHandler"); } else { logger.debug("Add Explicitely SSL support to Command"); // add the SSL support sslHandler = FtpsInitializer.waarpSslContextFactory.initInitializer(true, FtpsInitializer.waarpSslContextFactory.needClientAuthentication()); session.prepareSsl(); WaarpSslUtility.addSslHandler(future, ctx.pipeline(), sslHandler, new GenericFutureListener<Future<? super Channel>>() { public void operationComplete(Future<? super Channel> future) throws Exception { logger.debug("Handshake: " + future.isSuccess() + ":" + ((Channel) future.get()).toString(), future.cause()); if (!future.isSuccess()) { String error2 = future.cause() != null ? future.cause().getMessage() : "During Handshake"; logger.error("Cannot finalize Ssl Command channel " + error2); callForSnmp("SSL Connection Error", error2); session.setSsl(false); ctx.close(); } else { logger.debug("End of initialization of SSL and command channel: " + ctx.channel()); session.setSsl(true); } } }); } } else if (session.getCurrentCommand().getCode() == FtpCommandCode.CCC) { logger.debug("SSL to be removed from pipeline"); // remove the SSL support session.prepareSsl(); WaarpSslUtility.removingSslHandler(future, controlChannel, false); } } else if (session.getCurrentCommand().getCode() != FtpCommandCode.INTERNALSHUTDOWN) { writeFinalAnswer(ctx); } }