List of usage examples for io.netty.channel ChannelFuture cause
Throwable cause();
From source file:io.jsync.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"); }/*w w w . ja v a2 s . c o m*/ if (listening) { throw new IllegalStateException("Listen already called"); } listening = true; synchronized (async.sharedHttpServers()) { id = new ServerID(port, host); serverOrigin = (isSSL() ? "https" : "http") + "://" + host + ":" + port; DefaultHttpServer shared = async.sharedHttpServers().get(id); if (shared == null || port == 0) { serverChannelGroup = new DefaultChannelGroup("async-acceptor-channels", GlobalEventExecutor.INSTANCE); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(availableWorkers); bootstrap.channel(NioServerSocketChannel.class); tcpHelper.applyConnectionOptions(bootstrap); tcpHelper.checkSSL(async); bootstrap.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (tcpHelper.isSSL()) { pipeline.addLast("ssl", tcpHelper.createSslHandler(async, false)); } pipeline.addLast("flashpolicy", new FlashPolicyHandler()); pipeline.addLast("httpDecoder", new HttpRequestDecoder(4096, 8192, 8192, false)); pipeline.addLast("httpEncoder", new AsyncHttpResponseEncoder()); 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)); bindFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { if (!channelFuture.isSuccess()) { async.sharedHttpServers().remove(id); } else { Channel channel = channelFuture.channel(); InetSocketAddress address = (InetSocketAddress) channel.localAddress(); DefaultHttpServer.this.actualPort = address.getPort(); serverChannelGroup.add(channel); } } }); } catch (final Throwable t) { // Make sure we send the exception back through the handler (if any) if (listenHandler != null) { async.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; } async.sharedHttpServers().put(id, this); actualServer = this; } else { // Server already exists with that host/port - we will use that actualServer = shared; this.actualPort = shared.actualPort; 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:io.jsync.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"); }/*from w w w . ja v a 2s . c o m*/ checkWritten(); File file = new File(PathAdjuster.adjust(async, filename)); if (!file.exists()) { if (notFoundResource != null) { setStatusCode(HttpResponseStatus.NOT_FOUND.code()); sendFile(notFoundResource, (String) null, resultHandler); } else { sendNotFound(); } } else if (file.isDirectory()) { // send over a 403 Forbidden sendForbidden(); } else { if (!contentLengthSet()) { putHeader(io.jsync.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 = MimeUtils.getMimeTypeForExtension(ext); if (contentType != null) { putHeader(io.jsync.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()); } async.runOnContext(new Handler<Void>() { @Override public void handle(Void v) { resultHandler.handle(res); } }); } }); } if (!keepAlive) { closeConnAfterWrite(); } conn.responseComplete(); } }
From source file:io.jsync.net.impl.ConnectionBase.java
License:Open Source License
protected void addFuture(final Handler<AsyncResult<Void>> doneHandler, final ChannelFuture future) { if (future != null) { future.addListener(new ChannelFutureListener() { public void operationComplete(final ChannelFuture channelFuture) throws Exception { if (doneHandler != null) { context.execute(new Runnable() { public void run() { if (channelFuture.isSuccess()) { doneHandler.handle(new DefaultFutureResult<>((Void) null)); } else { doneHandler.handle(new DefaultFutureResult<Void>(channelFuture.cause())); }//from w w w . jav a2 s . co m } }); } else if (!channelFuture.isSuccess()) { handleException(channelFuture.cause()); } } }); } }
From source file:io.jsync.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(async);/*from ww w .j av a 2 s. co 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(async, 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 AsyncNetHandler(async, 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 async.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:io.jsync.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(async, filename)); if (f.isDirectory()) { throw new IllegalArgumentException("filename must point to a file and not to a directory"); }//from w w w .j av a2 s . c o m 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()); } async.runOnContext(new Handler<Void>() { @Override public void handle(Void v) { resultHandler.handle(res); } }); } }); } return this; }
From source file:io.lettuce.core.internal.Futures.java
License:Apache License
/** * Adapt Netty's {@link ChannelFuture} emitting a {@link Void} result into a {@link CompletableFuture}. * * @param future/*w w w . ja va2 s . c o m*/ * @return the {@link CompletableFuture}. */ public static void adapt(ChannelFuture future, CompletableFuture<Void> target) { future.addListener(f -> { if (f.isSuccess()) { target.complete(null); } else { target.completeExceptionally(f.cause()); } }); if (future.isSuccess()) { target.complete(null); } else if (future.isCancelled()) { target.cancel(false); } else if (future.isDone() && !future.isSuccess()) { target.completeExceptionally(future.cause()); } }
From source file:io.lettuce.core.protocol.DefaultEndpointTest.java
License:Apache License
@Test public void retryListenerCompletesSuccessfullyAfterDeferredRequeue() { DefaultEndpoint.RetryListener listener = DefaultEndpoint.RetryListener.newInstance(sut, command); ChannelFuture future = mock(ChannelFuture.class); EventLoop eventLoopGroup = mock(EventLoop.class); when(future.isSuccess()).thenReturn(false); when(future.cause()).thenReturn(new ClosedChannelException()); when(channel.eventLoop()).thenReturn(eventLoopGroup); when(channel.close()).thenReturn(mock(ChannelFuture.class)); sut.notifyChannelActive(channel);//from w w w .j a va 2 s. co m sut.closeAsync(); listener.operationComplete(future); ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); verify(eventLoopGroup).submit(runnableCaptor.capture()); runnableCaptor.getValue().run(); assertThat(command.exception).isInstanceOf(RedisException.class); }
From source file:io.lettuce.core.protocol.ReconnectionHandler.java
License:Apache License
private void reconnect0(CompletableFuture<Channel> result, SocketAddress remoteAddress) { ChannelFuture connectFuture = bootstrap.connect(remoteAddress); ChannelPromise initFuture = connectFuture.channel().newPromise(); logger.debug("Reconnecting to Redis at {}", remoteAddress); result.whenComplete((c, t) -> {//from ww w . j a va2 s . com if (t instanceof CancellationException) { connectFuture.cancel(true); initFuture.cancel(true); } }); initFuture.addListener((ChannelFuture it) -> { if (it.cause() != null) { connectFuture.cancel(true); close(it.channel()); result.completeExceptionally(it.cause()); } else { result.complete(connectFuture.channel()); } }); connectFuture.addListener((ChannelFuture it) -> { if (it.cause() != null) { initFuture.tryFailure(it.cause()); return; } ChannelPipeline pipeline = it.channel().pipeline(); RedisChannelInitializer channelInitializer = pipeline.get(RedisChannelInitializer.class); if (channelInitializer == null) { initFuture.tryFailure(new IllegalStateException( "Reconnection attempt without a RedisChannelInitializer in the channel pipeline")); return; } channelInitializer.channelInitialized().whenComplete((state, throwable) -> { if (throwable != null) { if (isExecutionException(throwable)) { initFuture.tryFailure(throwable); return; } if (clientOptions.isCancelCommandsOnReconnectFailure()) { connectionFacade.reset(); } if (clientOptions.isSuspendReconnectOnProtocolFailure()) { logger.error("Disabling autoReconnect due to initialization failure", throwable); setReconnectSuspended(true); } initFuture.tryFailure(throwable); return; } if (logger.isDebugEnabled()) { logger.info("Reconnected to {}, Channel {}", remoteAddress, ChannelLogDescriptor.logDescriptor(it.channel())); } else { logger.info("Reconnected to {}", remoteAddress); } initFuture.trySuccess(); }); }); Runnable timeoutAction = () -> { initFuture.tryFailure(new TimeoutException( String.format("Reconnection attempt exceeded timeout of %d %s ", timeout, timeoutUnit))); }; Timeout timeoutHandle = timer.newTimeout(it -> { if (connectFuture.isDone() && initFuture.isDone()) { return; } if (reconnectWorkers.isShutdown()) { timeoutAction.run(); return; } reconnectWorkers.submit(timeoutAction); }, this.timeout, timeoutUnit); initFuture.addListener(it -> timeoutHandle.cancel()); }
From source file:io.nebo.container.NettyEmbeddedServletContainer.java
License:Apache License
@Override public void start() throws EmbeddedServletContainerException { ServerBootstrap b = new ServerBootstrap(); groups(b);//from w w w .j ava 2s.c o m // servletExecutor = new DefaultEventExecutorGroup(50); // b.childHandler(new NettyEmbeddedServletInitializer(servletExecutor, context)); b.childHandler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new DispatcherInbound(address, context)); } }); // Don't yet need the complexity of lifecycle state, listeners etc, so tell the context it's initialised here ChannelFuture future = b.bind(address).awaitUninterruptibly(); //noinspection ThrowableResultOfMethodCallIgnored Throwable cause = future.cause(); if (null != cause) { throw new EmbeddedServletContainerException("Could not start Netty server", cause); } logger.info(context.getServerInfo() + " started on port: " + getPort()); context.setInitialised(true); context.addFilter(HessianConstant.HESSIAN_PATH, new HessianFilter(context)); ServletNettyHttpSessionManager.start(); }
From source file:io.netty.example.uptime.UptimeClient.java
License:Apache License
static void connect() { bs.connect().addListener(new ChannelFutureListener() { @Override/*from w w w . ja v a 2 s .c o m*/ public void operationComplete(ChannelFuture future) throws Exception { if (future.cause() != null) { handler.startTime = -1; handler.println("Failed to connect: " + future.cause()); } } }); }