Example usage for io.netty.util.concurrent Future cancel

List of usage examples for io.netty.util.concurrent Future cancel

Introduction

In this page you can find the example usage for io.netty.util.concurrent Future 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:io.vertx.core.dns.impl.fix.DnsNameResolverContext.java

License:Apache License

private void finishResolve() {
    if (!queriesInProgress.isEmpty()) {
        // If there are queries in progress, we should cancel it because we already finished the resolution.
        for (Iterator<Future<AddressedEnvelope<DnsResponse, InetSocketAddress>>> i = queriesInProgress
                .iterator(); i.hasNext();) {
            Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> f = i.next();
            i.remove();//  w w  w.ja  v  a  2  s .  com

            if (!f.cancel(false)) {
                f.addListener(RELEASE_RESPONSE);
            }
        }
    }

    if (resolvedEntries != null) {
        // Found at least one resolved address.
        for (InternetProtocolFamily f : resolveAddressTypes) {
            if (finishResolve(f.addressType(), resolvedEntries)) {
                return;
            }
        }
    }

    // No resolved address found.
    final int tries = maxAllowedQueries - allowedQueries;
    final StringBuilder buf = new StringBuilder(64);

    buf.append("failed to resolve '").append(hostname).append('\'');
    if (tries > 1) {
        if (tries < maxAllowedQueries) {
            buf.append(" after ").append(tries).append(" queries ");
        } else {
            buf.append(". Exceeded max queries per resolve ").append(maxAllowedQueries).append(' ');
        }
    }
    if (trace != null) {
        buf.append(':').append(trace);
    }
    final UnknownHostException cause = new UnknownHostException(buf.toString());

    resolveCache.cache(hostname, cause, parent.ch.eventLoop());
    promise.tryFailure(cause);
}

From source file:org.apache.hive.spark.client.rpc.TestRpc.java

License:Apache License

@Test
public void testBadHello() throws Exception {
    RpcServer server = autoClose(new RpcServer(emptyConfig));

    Future<Rpc> serverRpcFuture = server.registerClient("client", "newClient", new TestDispatcher());
    NioEventLoopGroup eloop = new NioEventLoopGroup();

    Future<Rpc> clientRpcFuture = Rpc.createClient(emptyConfig, eloop, "localhost", server.getPort(), "client",
            "wrongClient", new TestDispatcher());

    try {/*from   www.j  av a 2  s.  c  om*/
        autoClose(clientRpcFuture.get(10, TimeUnit.SECONDS));
        fail("Should have failed to create client with wrong secret.");
    } catch (ExecutionException ee) {
        // On failure, the SASL handler will throw an exception indicating that the SASL
        // negotiation failed.
        assertTrue("Unexpected exception: " + ee.getCause(), ee.getCause() instanceof SaslException);
    }

    serverRpcFuture.cancel(true);
}

From source file:org.apache.jackrabbit.oak.plugins.segment.standby.server.StandbyServer.java

License:Apache License

private void start(boolean wait) {
    if (running)//from   www  .j a va2s .co  m
        return;

    this.handler.state = STATUS_STARTING;

    final Thread close = new Thread() {
        @Override
        public void run() {
            try {
                running = true;
                handler.state = STATUS_RUNNING;
                channelFuture.sync().channel().closeFuture().sync();
            } catch (InterruptedException e) {
                StandbyServer.this.stop();
            }
        }
    };
    final ChannelFutureListener bindListener = new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                close.start();
            } else {
                log.error("Server failed to start on port " + port + ", will be canceled", future.cause());
                future.channel().close();
                new Thread() {
                    @Override
                    public void run() {
                        close();
                    }
                }.start();
            }
        }
    };
    Future<?> startup = bossGroup.submit(new Runnable() {
        @Override
        public void run() {
            //netty 4.0.20 has a race condition issue with
            //asynchronous channel registration. As a workaround
            //we bind asynchronously from the boss event group to make
            //the channel registration synchronous.
            //Note that now this method will return immediately.
            channelFuture = b.bind(port);
            channelFuture.addListener(bindListener);
        }
    });
    if (!startup.awaitUninterruptibly(10000)) {
        log.error("Server failed to start within 10 seconds and will be canceled");
        startup.cancel(true);
    } else if (wait) {
        try {
            close.join();
        } catch (InterruptedException ignored) {
        }
    }
}

From source file:org.opendaylight.protocol.bgp.rib.impl.BGPDispatcherImplTest.java

License:Open Source License

@Test
public void testCreateReconnectingClient() throws Exception {
    final InetSocketAddress serverAddress = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress();
    final Future<Void> future = this.clientDispatcher.createReconnectingClient(serverAddress, this.registry,
            RETRY_TIMER, Optional.absent());
    waitFutureSuccess(future);/*from ww  w .j a  v a 2s  .  c o  m*/
    final Channel serverChannel = createServer(serverAddress);
    Assert.assertEquals(BGPSessionImpl.State.UP, this.serverListener.getState());
    Assert.assertTrue(serverChannel.isWritable());
    future.cancel(true);
    this.serverListener.releaseConnection();
    checkIdleState(this.serverListener);
}

From source file:org.ow2.petals.bc.gateway.outbound.TransportClient.java

License:Open Source License

/**
 * Disconnect from the provider partner//w w w.ja v  a  2 s .  c  om
 */
public void disconnect() {
    mainLock.lock();
    try {
        final Channel _channel = channel;
        channel = null;
        authenticationFuture = null;

        final Future<Void> _connectOrNext = connectOrNext;
        if (_connectOrNext != null) {
            connectOrNext = null;
            _connectOrNext.cancel(true);
        }

        if (_channel != null && _channel.isOpen()) {
            // Note: this should trigger a call to ProviderDomain.close() as defined in DomainHandler!
            _channel.close();
        }
    } finally {
        mainLock.unlock();
    }
}

From source file:org.redisson.RedissonRemoteService.java

License:Apache License

private <T> void executeMethod(final Class<T> remoteInterface,
        final RBlockingQueue<RemoteServiceRequest> requestQueue, final ExecutorService executor,
        final RemoteServiceRequest request) {
    final RemoteServiceMethod method = beans
            .get(new RemoteServiceKey(remoteInterface, request.getMethodName(), request.getSignatures()));
    final String responseName = getResponseQueueName(remoteInterface, request.getRequestId());

    RBlockingQueue<RemoteServiceCancelRequest> cancelRequestQueue = redisson
            .getBlockingQueue(getCancelRequestQueueName(remoteInterface, request.getRequestId()), getCodec());
    final RFuture<RemoteServiceCancelRequest> cancelRequestFuture = cancelRequestQueue.takeAsync();

    final AtomicReference<RRemoteServiceResponse> responseHolder = new AtomicReference<RRemoteServiceResponse>();

    final java.util.concurrent.Future<?> submitFuture = executor.submit(new Runnable() {
        @Override/*from   ww w .j ava 2s  . com*/
        public void run() {
            invokeMethod(remoteInterface, requestQueue, request, method, responseName, executor,
                    cancelRequestFuture, responseHolder);
        }
    });

    cancelRequestFuture.addListener(new FutureListener<RemoteServiceCancelRequest>() {
        @Override
        public void operationComplete(Future<RemoteServiceCancelRequest> future) throws Exception {
            if (!future.isSuccess()) {
                return;
            }

            boolean res = submitFuture.cancel(future.getNow().isMayInterruptIfRunning());
            if (res) {
                RemoteServiceCancelResponse response = new RemoteServiceCancelResponse();
                if (!responseHolder.compareAndSet(null, response)) {
                    response = new RemoteServiceCancelResponse(false);
                }
                // could be removed not from future object
                if (future.getNow().getResponseId() != null) {
                    String cancelResponseName = getResponseQueueName(remoteInterface,
                            future.getNow().getResponseId());
                    send(60 * 1000, cancelResponseName, response);
                }
            }
        }
    });
}

From source file:org.thingsboard.rule.engine.mqtt.TbMqttNode.java

License:Apache License

private MqttClient initClient() throws Exception {
    Optional<SslContext> sslContextOpt = initSslContext();
    MqttClientConfig config = sslContextOpt.isPresent() ? new MqttClientConfig(sslContextOpt.get())
            : new MqttClientConfig();
    if (!StringUtils.isEmpty(this.config.getClientId())) {
        config.setClientId(this.config.getClientId());
    }/*  w  w w. j ava2  s. c o m*/
    config.setCleanSession(this.config.isCleanSession());
    this.config.getCredentials().configure(config);
    MqttClient client = MqttClient.create(config, null);
    client.setEventLoop(this.eventLoopGroup);
    Future<MqttConnectResult> connectFuture = client.connect(this.config.getHost(), this.config.getPort());
    MqttConnectResult result;
    try {
        result = connectFuture.get(this.config.getConnectTimeoutSec(), TimeUnit.SECONDS);
    } catch (TimeoutException ex) {
        connectFuture.cancel(true);
        client.disconnect();
        String hostPort = this.config.getHost() + ":" + this.config.getPort();
        throw new RuntimeException(String.format("Failed to connect to MQTT broker at %s.", hostPort));
    }
    if (!result.isSuccess()) {
        connectFuture.cancel(true);
        client.disconnect();
        String hostPort = this.config.getHost() + ":" + this.config.getPort();
        throw new RuntimeException(String.format("Failed to connect to MQTT broker at %s. Result code is: %s",
                hostPort, result.getReturnCode()));
    }
    return client;
}

From source file:reactor.ipc.netty.channel.CloseableContextHandler.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public final void setFuture(Future<?> future) {
    Objects.requireNonNull(future, "future");
    if (this.f != null) {
        future.cancel(true);
        return;/*from   w w w  .  j ava  2  s . co  m*/
    }
    if (log.isDebugEnabled()) {
        log.debug("Connecting new channel: {}", future.toString());
    }
    this.f = (ChannelFuture) future;
    f.addListener(this);
    sink.setCancellation(this);
}

From source file:reactor.ipc.netty.channel.PooledClientContextHandler.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public void setFuture(Future<?> future) {
    Objects.requireNonNull(future, "future");
    if (this.f != null) {
        future.cancel(true);
        return;//from ww w.  j a v  a  2 s  .com
    }
    if (log.isDebugEnabled()) {
        log.debug("Acquiring existing channel from pool: {}", pool.toString());
    }
    this.f = (Future<CHANNEL>) future;
    f.addListener(this);
}