Example usage for io.netty.channel ChannelFuture isSuccess

List of usage examples for io.netty.channel ChannelFuture isSuccess

Introduction

In this page you can find the example usage for io.netty.channel ChannelFuture isSuccess.

Prototype

boolean isSuccess();

Source Link

Document

Returns true if and only if the I/O operation was completed successfully.

Usage

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  ww  .  j  av  a2s . c om
    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 ww . j  a  va  2 s  .  c  o  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 w  w w  .  j  a  va 2 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(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  ww.  j a v a2 s.com*/
    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//www  .  jav a  2s .com
 * @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 closeCleansUpResources() {

    ChannelFuture future = mock(ChannelFuture.class);
    when(future.isSuccess()).thenReturn(true);
    when(channel.close()).thenReturn(future);

    sut.notifyChannelActive(channel);/*from ww w .ja  va  2s .  co  m*/
    sut.registerConnectionWatchdog(connectionWatchdog);

    sut.close();

    verify(channel).close();
    verify(connectionWatchdog).prepareClose();
}

From source file:io.lettuce.core.protocol.DefaultEndpointTest.java

License:Apache License

@Test
public void closeAllowsOnlyOneCall() {

    ChannelFuture future = mock(ChannelFuture.class);
    when(future.isSuccess()).thenReturn(true);
    when(channel.close()).thenReturn(future);

    sut.notifyChannelActive(channel);/*w  ww  .ja v  a 2s . c  o m*/
    sut.registerConnectionWatchdog(connectionWatchdog);

    sut.close();
    sut.close();

    verify(channel).close();
    verify(connectionWatchdog).prepareClose();
}

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 ww. j a  v  a 2 s  . c  o 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.maelstorm.server.ServerInit.java

License:Open Source License

public void start(String configFile, RequestHandler handler) throws Exception {
    LOG.info("Starting.");
    AppendableCharSequenceAddon.configure();
    try {//from ww w. j  a  v a  2s. com
        System.in.close(); // Release a FD we don't need.
    } catch (Exception e) {
        LOG.warn("Failed to close stdin", e);
    }
    Properties prop = getProperties(configFile);
    requestDistributor = handler;
    requestDistributor.setInitializer(this);
    String os = System.getProperty("os.name").toLowerCase(Locale.UK).trim();
    if (os.startsWith("linux")) {
        bossGroup = (null == bossGroup) ? new EpollEventLoopGroup(1) : bossGroup;
        workerGroup = (null == workerGroup) ? new EpollEventLoopGroup(NUM_WORKER_THREADS) : workerGroup;
    } else {
        bossGroup = (null == bossGroup) ? new NioEventLoopGroup(1) : bossGroup;
        workerGroup = (null == workerGroup) ? new NioEventLoopGroup(NUM_WORKER_THREADS) : workerGroup;
    }

    String[] servers = prop.getProperty("servers").split(",");
    for (String server : servers) {

        try {
            controller = new ServerBootstrap();
            controller.group(bossGroup, workerGroup);
            if (os.startsWith("linux")) {
                controller.channel(EpollServerSocketChannel.class);
                controller.option(EpollChannelOption.TCP_CORK, true);
            } else {
                controller.channel(NioServerSocketChannel.class);
            }
            controller.childHandler(new PipelineFactory(handler, getPipelineConfig(prop, server)));
            controller.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            controller.option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT);
            controller.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                    getInt(prop, server, "connectTimeoutMillis"));
            controller.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 64 * 1024);
            controller.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 1 * 1024);
            controller.option(ChannelOption.SO_KEEPALIVE, getBoolean(prop, server, "SOKeepalive"));
            controller.option(ChannelOption.SO_REUSEADDR, true);
            controller.option(ChannelOption.TCP_NODELAY, true);
            controller.option(ChannelOption.SO_LINGER, 0);
            controller.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            controller.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 64 * 1024);
            controller.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 10);
            controller.childOption(ChannelOption.SO_KEEPALIVE, true);
            controller.childOption(ChannelOption.SO_REUSEADDR, true);
            controller.childOption(ChannelOption.TCP_NODELAY, true);
            controller.childOption(ChannelOption.SO_LINGER, 0);
            controller.childOption(ChannelOption.SO_RCVBUF, 6291456);

            final InetSocketAddress addr = new InetSocketAddress(getInt(prop, server, "port"));
            ChannelFuture future = controller.bind(addr).sync();
            if (future.isSuccess())
                LOG.info("Server Ready to serve on " + addr);
            else
                throw new Exception("Address already in use");
        } catch (Throwable t) {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            throw new RuntimeException("Initialization failed", t);
        }
    }
}

From source file:io.pravega.client.netty.impl.ConnectionFactoryImpl.java

License:Open Source License

@Override
public CompletableFuture<ClientConnection> establishConnection(PravegaNodeUri location, ReplyProcessor rp) {
    Preconditions.checkNotNull(location);
    Exceptions.checkNotClosed(closed.get(), this);
    final SslContext sslCtx;
    if (ssl) {/*  w  w  w  . j  a  v  a  2  s. com*/
        try {
            sslCtx = SslContextBuilder.forClient().trustManager(FingerprintTrustManagerFactory
                    .getInstance(FingerprintTrustManagerFactory.getDefaultAlgorithm())).build();
        } catch (SSLException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslCtx = null;
    }
    AppendBatchSizeTracker batchSizeTracker = new AppendBatchSizeTrackerImpl();
    ClientConnectionInboundHandler handler = new ClientConnectionInboundHandler(location.getEndpoint(), rp,
            batchSizeTracker);
    Bootstrap b = new Bootstrap();
    b.group(group).channel(nio ? NioSocketChannel.class : EpollSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    if (sslCtx != null) {
                        p.addLast(sslCtx.newHandler(ch.alloc(), location.getEndpoint(), location.getPort()));
                    }
                    // p.addLast(new LoggingHandler(LogLevel.INFO));
                    p.addLast(new ExceptionLoggingHandler(location.getEndpoint()),
                            new CommandEncoder(batchSizeTracker),
                            new LengthFieldBasedFrameDecoder(WireCommands.MAX_WIRECOMMAND_SIZE, 4, 4),
                            new CommandDecoder(), handler);
                }
            });

    // Start the client.
    CompletableFuture<ClientConnection> result = new CompletableFuture<>();
    try {
        b.connect(location.getEndpoint(), location.getPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    result.complete(handler);
                } else {
                    result.completeExceptionally(future.cause());
                }
            }
        });
    } catch (Exception e) {
        result.completeExceptionally(e);
    }
    return result;
}