Example usage for io.netty.channel ChannelFuture cancel

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

Introduction

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

Prototype

@Override
boolean cancel(boolean mayInterruptIfRunning);

Source Link

Document

If the cancellation was successful it will fail the future with a CancellationException .

Usage

From source file:com.addthis.hydra.query.loadbalance.NextQueryTask.java

License:Apache License

@Override
public void run() {
    QueryRequest request;/*from   w ww  .  j  a  va 2  s  .  c  o  m*/
    try {
        request = queryQueue.takeQuery();
    } catch (InterruptedException ignored) {
        log.info("Frame reader thread interrupted -- halting query processing");
        return;
    }
    try {
        final ChannelFuture queryFuture = HttpQueryCallHandler.handleQuery(request.querySource, request.kv,
                request.request, request.ctx, executor);
        queryFuture.addListener(this);
        queryFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (queryFuture.cancel(false)) {
                    log.warn("cancelling query due to closed output channel");
                }
            }
        });
    } catch (Exception e) {
        log.warn("Exception caught before mesh query master added to pipeline", e);
        if (request.ctx.channel().isActive()) {
            HttpUtils.sendError(request.ctx, new HttpResponseStatus(500, e.getMessage()));
        }
    }
}

From source file:com.cloudera.livy.client.local.rpc.Rpc.java

License:Apache License

/**
 * Creates an RPC client for a server running on the given remote host and port.
 *
 * @param config RPC configuration data.
 * @param eloop Event loop for managing the connection.
 * @param host Host name or IP address to connect to.
 * @param port Port where server is listening.
 * @param clientId The client ID that identifies the connection.
 * @param secret Secret for authenticating the client with the server.
 * @param dispatcher Dispatcher used to handle RPC calls.
 * @return A future that can be used to monitor the creation of the RPC object.
 *//*from   w  ww. jav  a  2  s.c o m*/
public static Promise<Rpc> createClient(final LocalConf config, final EventLoopGroup eloop, String host,
        int port, final String clientId, final String secret, final RpcDispatcher dispatcher) throws Exception {
    int connectTimeoutMs = (int) config.getTimeAsMs(RPC_CLIENT_CONNECT_TIMEOUT);

    final ChannelFuture cf = new Bootstrap().group(eloop).handler(new ChannelInboundHandlerAdapter() {
    }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs).connect(host, port);

    final Promise<Rpc> promise = eloop.next().newPromise();
    final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>();

    // Set up a timeout to undo everything.
    final Runnable timeoutTask = new Runnable() {
        @Override
        public void run() {
            promise.setFailure(new TimeoutException("Timed out waiting for RPC server connection."));
        }
    };
    final ScheduledFuture<?> timeoutFuture = eloop.schedule(timeoutTask,
            config.getTimeAsMs(RPC_CLIENT_HANDSHAKE_TIMEOUT), TimeUnit.MILLISECONDS);

    // The channel listener instantiates the Rpc instance when the connection is established,
    // and initiates the SASL handshake.
    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            if (cf.isSuccess()) {
                SaslClientHandler saslHandler = new SaslClientHandler(config, clientId, promise, timeoutFuture,
                        secret, dispatcher);
                Rpc rpc = createRpc(config, saslHandler, (SocketChannel) cf.channel(), eloop);
                saslHandler.rpc = rpc;
                saslHandler.sendHello(cf.channel());
            } else {
                promise.setFailure(cf.cause());
            }
        }
    });

    // Handle cancellation of the promise.
    promise.addListener(new GenericFutureListener<Promise<Rpc>>() {
        @Override
        public void operationComplete(Promise<Rpc> p) {
            if (p.isCancelled()) {
                cf.cancel(true);
            }
        }
    });

    return promise;
}

From source file:com.cloudera.livy.rsc.rpc.Rpc.java

License:Apache License

/**
 * Creates an RPC client for a server running on the given remote host and port.
 *
 * @param config RPC configuration data.
 * @param eloop Event loop for managing the connection.
 * @param host Host name or IP address to connect to.
 * @param port Port where server is listening.
 * @param clientId The client ID that identifies the connection.
 * @param secret Secret for authenticating the client with the server.
 * @param dispatcher Dispatcher used to handle RPC calls.
 * @return A future that can be used to monitor the creation of the RPC object.
 *///from   w ww .j  av a2  s .  com
public static Promise<Rpc> createClient(final RSCConf config, final EventLoopGroup eloop, String host, int port,
        final String clientId, final String secret, final RpcDispatcher dispatcher) throws Exception {
    int connectTimeoutMs = (int) config.getTimeAsMs(RPC_CLIENT_CONNECT_TIMEOUT);

    final ChannelFuture cf = new Bootstrap().group(eloop).handler(new ChannelInboundHandlerAdapter() {
    }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs).connect(host, port);

    final Promise<Rpc> promise = eloop.next().newPromise();
    final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>();

    // Set up a timeout to undo everything.
    final Runnable timeoutTask = new Runnable() {
        @Override
        public void run() {
            promise.setFailure(new TimeoutException("Timed out waiting for RPC server connection."));
        }
    };
    final ScheduledFuture<?> timeoutFuture = eloop.schedule(timeoutTask,
            config.getTimeAsMs(RPC_CLIENT_HANDSHAKE_TIMEOUT), TimeUnit.MILLISECONDS);

    // The channel listener instantiates the Rpc instance when the connection is established,
    // and initiates the SASL handshake.
    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            if (cf.isSuccess()) {
                SaslClientHandler saslHandler = new SaslClientHandler(config, clientId, promise, timeoutFuture,
                        secret, dispatcher);
                Rpc rpc = createRpc(config, saslHandler, (SocketChannel) cf.channel(), eloop);
                saslHandler.rpc = rpc;
                saslHandler.sendHello(cf.channel());
            } else {
                promise.setFailure(cf.cause());
            }
        }
    });

    // Handle cancellation of the promise.
    promise.addListener(new GenericFutureListener<Promise<Rpc>>() {
        @Override
        public void operationComplete(Promise<Rpc> p) {
            if (p.isCancelled()) {
                cf.cancel(true);
            }
        }
    });

    return promise;
}

From source file:com.kixeye.kixmpp.server.KixmppServer.java

License:Apache License

/**
 * Stops the server.//from   ww w .  j  av a2  s. c  o m
 * 
 * @return
 */
public ListenableFuture<KixmppServer> stop() {
    checkAndSetState(State.STOPPING, State.STARTED, State.STARTING);

    logger.info("Stopping Kixmpp Server...");

    // shutdown clustering
    cluster.shutdown();

    for (Entry<String, KixmppServerModule> entry : modules.entrySet()) {
        entry.getValue().uninstall(this);
    }

    final SettableFuture<KixmppServer> responseFuture = SettableFuture.create();

    ChannelFuture serverChannelFuture = channelFuture.get();

    if (serverChannelFuture != null) {
        serverChannelFuture.cancel(true);
    }

    ChannelFuture webSocketServerChannelFuture = webSocketChannelFuture.get();

    if (webSocketServerChannelFuture != null) {
        webSocketServerChannelFuture.cancel(true);
    }

    final Channel serverChannel = channel.get();
    final Channel webSocketServerChannel = webSocketChannel.get();

    if (serverChannel == null && webSocketServerChannel == null) {
        logger.info("Stopped Kixmpp Server");

        state.set(State.STOPPED);

        responseFuture.set(KixmppServer.this);
    } else {
        final GenericFutureListener<Future<? super Void>> channelFutureListener = new GenericFutureListener<Future<? super Void>>() {
            public synchronized void operationComplete(Future<? super Void> future) throws Exception {
                if ((serverChannel != null && !serverChannel.isActive())
                        && (webSocketServerChannel != null && !webSocketServerChannel.isActive())) {
                    logger.info("Stopped Kixmpp Server");

                    state.set(State.STOPPED);

                    eventEngine.unregisterAll();

                    responseFuture.set(KixmppServer.this);
                }
            }
        };

        if (serverChannel != null) {
            serverChannel.disconnect().addListener(channelFutureListener);
        }

        if (webSocketServerChannel != null) {
            webSocketServerChannel.disconnect().addListener(channelFutureListener);
        }
    }

    return responseFuture;
}

From source file:com.lambdaworks.redis.protocol.ReconnectionHandler.java

License:Apache License

protected boolean reconnect(InternalLogLevel infoLevel) throws Exception {

    SocketAddress remoteAddress = socketAddressSupplier.get();

    try {// w ww .j ava2  s.c o m
        long timeLeft = timeoutUnit.toNanos(timeout);
        long start = System.nanoTime();

        logger.debug("Reconnecting to Redis at {}", remoteAddress);
        ChannelFuture currentFuture = this.currentFuture = bootstrap.connect(remoteAddress);
        if (!currentFuture.await(timeLeft, TimeUnit.NANOSECONDS)) {
            if (currentFuture.isCancellable()) {
                currentFuture.cancel(true);
            }

            throw new TimeoutException(
                    "Reconnection attempt exceeded timeout of " + timeout + " " + timeoutUnit);
        }

        currentFuture.sync();

        Channel channel = currentFuture.channel();

        RedisChannelInitializer channelInitializer = channel.pipeline().get(RedisChannelInitializer.class);
        CommandHandler<?, ?> commandHandler = channel.pipeline().get(CommandHandler.class);

        if (channelInitializer == null) {
            logger.warn("Reconnection attempt without a RedisChannelInitializer in the channel pipeline");
            close(channel);
            return false;
        }

        if (commandHandler == null) {
            logger.warn("Reconnection attempt without a CommandHandler in the channel pipeline");
            close(channel);
            return false;
        }

        try {
            timeLeft -= System.nanoTime() - start;
            channelInitializer.channelInitialized().get(Math.max(0, timeLeft), TimeUnit.NANOSECONDS);
            if (logger.isDebugEnabled()) {
                logger.log(infoLevel, "Reconnected to {}, Channel {}", remoteAddress,
                        ChannelLogDescriptor.logDescriptor(channel));
            } else {
                logger.log(infoLevel, "Reconnected to {}", remoteAddress);
            }
            return true;
        } catch (TimeoutException e) {
            channelInitializer.channelInitialized().cancel(true);
        } catch (Exception e) {
            if (clientOptions.isCancelCommandsOnReconnectFailure()) {
                commandHandler.reset();
            }

            if (clientOptions.isSuspendReconnectOnProtocolFailure()) {
                logger.error("Cannot initialize channel. Disabling autoReconnect", e);
                setReconnectSuspended(true);
            } else {
                logger.error("Cannot initialize channel.", e);
                throw e;
            }
        }
    } finally {
        this.currentFuture = null;
    }

    return false;
}

From source file:com.lambdaworks.redis.protocol.ReconnectionHandler.java

License:Apache License

public void prepareClose() {

    ChannelFuture currentFuture = this.currentFuture;
    if (currentFuture != null && !currentFuture.isDone()) {
        currentFuture.cancel(true);
    }//from   w  ww . j  ava 2  s .c om
}

From source file:com.mastfrog.netty.http.client.HttpClient.java

License:Open Source License

private void submit(final URL url, HttpRequest rq, final AtomicBoolean cancelled, final ResponseFuture handle,
        final ResponseHandler<?> r, RequestInfo info, Duration timeout, boolean noAggregate) {
    if (info != null && info.isExpired()) {
        cancelled.set(true);//w  w  w.  j  a  v  a2  s.c o  m
    }
    if (cancelled.get()) {
        handle.event(new State.Cancelled());
        return;
    }
    try {
        for (RequestInterceptor i : interceptors) {
            rq = i.intercept(rq);
        }
        final HttpRequest req = rq;
        Bootstrap bootstrap;
        if (url.getProtocol().isSecure()) {
            bootstrap = startSsl(url.getHostAndPort());
        } else {
            bootstrap = start(url.getHostAndPort());
        }
        if (!url.isValid()) {
            throw new IllegalArgumentException(url.getProblems() + "");
        }
        TimeoutTimerTask tt = null;
        if (info == null) {
            info = new RequestInfo(url, req, cancelled, handle, r, timeout, tt, noAggregate);
            if (timeout != null) {
                tt = new TimeoutTimerTask(cancelled, handle, r, info);
                timer.schedule(tt, timeout.getMillis());
            }
            info.timer = tt;
        }
        if (info.isExpired()) {
            handle.event(new State.Timeout(info.age()));
            return;
        }
        handle.event(new State.Connecting());
        //XXX who is escaping this?
        req.setUri(req.getUri().replaceAll("%5f", "_"));
        ChannelFuture fut = bootstrap.connect(url.getHost().toString(), url.getPort().intValue());
        if (tt != null) {
            fut.channel().closeFuture().addListener(tt);
        }
        fut.channel().attr(KEY).set(info);
        handle.setFuture(fut);
        if (!monitors.isEmpty()) {
            for (ActivityMonitor m : monitors) {
                m.onStartRequest(url);
            }
            fut.channel().closeFuture().addListener(new AdapterCloseNotifier(url));
        }

        fut.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    Throwable cause = future.cause();
                    if (cause == null) {
                        cause = new ConnectException(url.getHost().toString());
                    }
                    handle.event(new State.Error(cause));
                    if (r != null) {
                        r.onError(cause);
                    }
                    cancelled.set(true);
                }
                if (cancelled.get()) {
                    future.cancel(true);
                    if (future.channel().isOpen()) {
                        future.channel().close();
                    }
                    for (ActivityMonitor m : monitors) {
                        m.onEndRequest(url);
                    }
                    return;
                }
                handle.event(new State.Connected(future.channel()));
                handle.event(new State.SendRequest(req));
                future = future.channel().writeAndFlush(req);
                future.addListener(new ChannelFutureListener() {

                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (cancelled.get()) {
                            future.cancel(true);
                            future.channel().close();
                        }
                        handle.event(new State.AwaitingResponse());
                    }

                });
            }

        });
    } catch (Exception ex) {
        Exceptions.chuck(ex);
    }
}

From source file:com.mastfrog.netty.http.client.ResponseFuture.java

License:Open Source License

boolean cancel(Duration forTimeout) {
    // We need to send the timeout event before setting the cancelled flag
    if (forTimeout != null && !cancelled.get()) {
        event(new State.Timeout(forTimeout));
    }//from w w w. ja  va2s  .  c  o  m
    boolean result = cancelled.compareAndSet(false, true);
    if (result) {
        try {
            ChannelFuture fut = future;
            if (fut != null) {
                fut.cancel(true);
            }
            if (fut != null && fut.channel() != null && fut.channel().isOpen()) {
                fut.channel().close();
            }
        } finally {
            if (forTimeout == null) {
                event(new State.Cancelled());
            }
        }
        latch.countDown();
    }
    return result;
}

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  w w  w.j  av  a2  s . c o m*/
    }
    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.udp.UDPConsumingServer.java

License:Apache License

public void destroy() {
    LOG.info("Destorying server on address(es) {}", addresses);
    for (ChannelFuture channelFuture : channelFutures) {
        if (channelFuture != null && channelFuture.isCancellable()) {
            channelFuture.cancel(true);
        }/*ww  w .  j av  a  2s . c  om*/
    }
    if (group != null && !group.isShutdown() && !group.isShuttingDown()) {
        try {
            group.shutdownGracefully().get();
        } catch (InterruptedException ex) {
            // ignore
        } catch (Exception ex) {
            LOG.error("Unexpected error shutting down: " + ex, ex);
        }
    }
    group = null;
    channelFutures.clear();
}