List of usage examples for io.netty.util.concurrent Future addListener
Future<V> addListener(GenericFutureListener<? extends Future<? super V>> listener);
From source file:at.yawk.dbus.protocol.DbusChannelImpl.java
private static <V> CompletableFuture<V> nettyFutureToStage(Future<V> future) { CompletableFuture<V> stage = new CompletableFuture<>(); future.addListener(new GenericFutureListener<Future<V>>() { @Override/*w w w . j av a 2 s .c om*/ public void operationComplete(Future<V> future) throws Exception { try { stage.complete(future.get()); } catch (ExecutionException e) { stage.completeExceptionally(e.getCause()); } } }); return stage; }
From source file:com.basho.riak.client.core.netty.RiakSecurityDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext chc, ByteBuf in, List<Object> out) throws Exception { // Make sure we have 4 bytes if (in.readableBytes() >= 4) { in.markReaderIndex();//from w ww . jav a 2 s . co m int length = in.readInt(); // See if we have the full frame. if (in.readableBytes() < length) { in.resetReaderIndex(); } else { byte code = in.readByte(); byte[] protobuf = new byte[length - 1]; in.readBytes(protobuf); switch (state) { case TLS_WAIT: switch (code) { case RiakMessageCodes.MSG_StartTls: logger.debug("Received MSG_RpbStartTls reply"); // change state this.state = State.SSL_WAIT; // insert SSLHandler SslHandler sslHandler = new SslHandler(sslEngine); // get promise Future<Channel> hsFuture = sslHandler.handshakeFuture(); // register callback hsFuture.addListener(new SslListener()); // Add handler chc.channel().pipeline().addFirst(Constants.SSL_HANDLER, sslHandler); break; case RiakMessageCodes.MSG_ErrorResp: logger.debug("Received MSG_ErrorResp reply to startTls"); promise.tryFailure((riakErrorToException(protobuf))); break; default: promise.tryFailure( new RiakResponseException(0, "Invalid return code during StartTLS; " + code)); } break; case AUTH_WAIT: chc.channel().pipeline().remove(this); switch (code) { case RiakMessageCodes.MSG_AuthResp: logger.debug("Received MSG_RpbAuthResp reply"); promise.trySuccess(null); break; case RiakMessageCodes.MSG_ErrorResp: logger.debug("Received MSG_ErrorResp reply to auth"); promise.tryFailure(riakErrorToException(protobuf)); break; default: promise.tryFailure( new RiakResponseException(0, "Invalid return code during Auth; " + code)); } break; default: // WTF? logger.error("Received message while not in TLS_WAIT or AUTH_WAIT"); promise.tryFailure( new IllegalStateException("Received message while not in TLS_WAIT or AUTH_WAIT")); } } } }
From source file:com.cloudera.livy.rsc.Utils.java
License:Apache License
public static <T> void addListener(Future<T> future, final FutureListener<T> lsnr) { future.addListener(new GenericFutureListener<Future<T>>() { @Override//ww w. ja va2 s .com public void operationComplete(Future<T> f) throws Exception { if (f.isSuccess()) { lsnr.onSuccess(f.get()); } else { lsnr.onFailure(f.cause()); } } }); }
From source file:com.github.milenkovicm.kafka.ListenerTest.java
License:Apache License
@Test public void test_success() throws Exception { String topic = "test_success"; createTopic(topic, 1);//w ww. ja v a 2s. co m ProducerProperties properties = new ProducerProperties(); properties.override(ProducerProperties.NETTY_DEBUG_PIPELINE, true); KafkaProducer producer = new KafkaProducer("localhost", START_PORT, topic, properties); producer.connect().sync(); KafkaTopic kafkaTopic = producer.topic(); final CountDownLatch latch = new CountDownLatch(1); final Future send = kafkaTopic.send(null, freeLaterBuffer(TEST_MESSAGE.getBytes())); send.addListener(new FutureListener() { @Override public void operationComplete(Future future) throws Exception { if (future.isSuccess()) { latch.countDown(); } } }); final List<KafkaStream<byte[], byte[]>> consume = consume(topic); final KafkaStream<byte[], byte[]> stream = consume.get(0); final ConsumerIterator<byte[], byte[]> messages = stream.iterator(); Assert.assertThat(TEST_MESSAGE, is(new String(messages.next().message()))); Assert.assertTrue(latch.await(2, TimeUnit.SECONDS)); producer.disconnect().sync(); }
From source file:com.github.milenkovicm.kafka.ListenerTest.java
License:Apache License
@Test @Ignore("not sure how to test this one") public void test_fail() throws Exception { String topic = "doesnotexist"; ProducerProperties properties = new ProducerProperties(); properties.override(ProducerProperties.NETTY_DEBUG_PIPELINE, true); KafkaProducer producer = new KafkaProducer("localhost", START_PORT, topic, properties); producer.connect().sync();// w ww . j a va 2s .c om KafkaTopic kafkaTopic = producer.topic(); final CountDownLatch latch = new CountDownLatch(1); final Future<Void> send = kafkaTopic.send(null, freeLaterBuffer(TEST_MESSAGE.getBytes())); send.addListener(new FutureListener<Void>() { @Override public void operationComplete(Future<Void> future) throws Exception { if (!future.isSuccess()) { latch.countDown(); } } }); Assert.assertTrue(latch.await(2, TimeUnit.SECONDS)); producer.disconnect().sync(); }
From source file:com.github.milenkovicm.kafka.ListenerTest.java
License:Apache License
@Test(expected = Exception.class) public void test_no_acks_register_listener() throws Exception { String topic = "test_no_acks_register_listener"; createTopic(topic, 1);//from ww w .j a v a 2 s. c o m ProducerProperties properties = new ProducerProperties(); properties.override(ProducerProperties.NETTY_DEBUG_PIPELINE, true); properties.override(ProducerProperties.DATA_ACK, Acknowledgment.WAIT_FOR_NO_ONE); KafkaProducer producer = new KafkaProducer("localhost", START_PORT, topic, properties); producer.connect().sync(); KafkaTopic kafkaTopic = producer.topic(); final Future send = kafkaTopic.send(null, freeLaterBuffer(TEST_MESSAGE.getBytes())); send.addListener(new FutureListener() { @Override public void operationComplete(Future future) throws Exception { Assert.fail("shouldn't get here"); } }); final List<KafkaStream<byte[], byte[]>> consume = consume(topic); final KafkaStream<byte[], byte[]> stream = consume.get(0); final ConsumerIterator<byte[], byte[]> messages = stream.iterator(); Assert.assertThat(TEST_MESSAGE, is(new String(messages.next().message()))); producer.disconnect().sync(); }
From source file:com.github.milenkovicm.kafka.NoTopicTest.java
License:Apache License
@Test public void test_producer_no_topic_async() throws Exception { final CountDownLatch latch = new CountDownLatch(1); String topic = "test_producer_no_topic__async"; ProducerProperties properties = new ProducerProperties(); properties.override(ProducerProperties.NETTY_DEBUG_PIPELINE, true); //createTopic(topic); KafkaProducer producer = new KafkaProducer("localhost", START_PORT, topic, properties); final Future<Void> connect = producer.connect(); connect.addListener(new GenericFutureListener<Future<? super Void>>() { @Override//from ww w . j a va 2 s .c om public void operationComplete(Future<? super Void> future) throws Exception { latch.countDown(); } }); latch.await(5, TimeUnit.SECONDS); Assert.assertThat(connect.isDone(), is(true)); Assert.assertThat(connect.isSuccess(), is(false)); Assert.assertThat(connect.cause(), notNullValue()); Assert.assertThat(((KafkaException) connect.cause()).error, is(Error.LEADER_NOT_AVAILABLE)); producer.disconnect(); }
From source file:com.kixeye.kixmpp.client.KixmppClient.java
License:Apache License
/** * Connects to the hostname and port./* ww w . ja v a 2 s . c om*/ * * @param hostname * @param port */ public ListenableFuture<KixmppClient> connect(String hostname, int port, String domain) { checkAndSetState(State.CONNECTING, State.DISCONNECTED); this.jid = new KixmppJid(domain); try { this.handshaker = WebSocketClientHandshakerFactory.newHandshaker( new URI("ws://" + hostname + ":" + port), WebSocketVersion.V13, null, false, new DefaultHttpHeaders()); } catch (Exception e) { throw new RuntimeException("Unable to set up handshaker.", e); } setUp(); // set this in case we get disconnected deferredDisconnect = SettableFuture.create(); deferredLogin = SettableFuture.create(); final SettableFuture<KixmppClient> responseFuture = SettableFuture.create(); connectListener.set(new GenericFutureListener<Future<? super Void>>() { public void operationComplete(Future<? super Void> future) throws Exception { if (future.isSuccess()) { if (state.compareAndSet(State.CONNECTING, State.CONNECTED)) { logger.info("Kixmpp Client connected to [{}]", ((ChannelFuture) future).channel().remoteAddress()); channel.set(((ChannelFuture) future).channel()); responseFuture.set(KixmppClient.this); } } else { state.set(State.DISCONNECTED); responseFuture.setException(future.cause()); } } }); ChannelFuture future = bootstrap.connect(hostname, port); switch (type) { case TCP: future.addListener(connectListener.get()); break; case WEBSOCKET: future.addListener(new GenericFutureListener<Future<? super Void>>() { public void operationComplete(Future<? super Void> future) throws Exception { if (!future.isSuccess()) { state.set(State.DISCONNECTED); responseFuture.setException(future.cause()); } } }); break; } return responseFuture; }
From source file:com.lambdaworks.redis.resource.Futures.java
License:Apache License
/** * Create a promise that emits a {@code Boolean} value on completion of the {@code future} * /*www . j a v a 2 s. c o m*/ * @param future the future. * @return Promise emitting a {@code Boolean} value. {@literal true} if the {@code future} completed successfully, otherwise * the cause wil be transported. */ static Promise<Boolean> toBooleanPromise(Future<?> future) { final DefaultPromise<Boolean> result = new DefaultPromise<>(GlobalEventExecutor.INSTANCE); future.addListener(new GenericFutureListener<Future<Object>>() { @Override public void operationComplete(Future<Object> future) throws Exception { if (future.isSuccess()) { result.setSuccess(true); } else { result.setFailure(future.cause()); } } }); return result; }
From source file:com.linecorp.armeria.client.circuitbreaker.CircuitBreakerRemoteInvoker.java
License:Apache License
@Override public <T> Future<T> invoke(EventLoop eventLoop, URI uri, ClientOptions options, ClientCodec codec, Method method, Object[] args) throws Exception { final CircuitBreaker circuitBreaker; try {//w ww . j a va 2s . c om circuitBreaker = mapping.get(eventLoop, uri, options, codec, method, args); } catch (Throwable t) { logger.warn("Failed to get a circuit breaker from mapping", t); return delegate().invoke(eventLoop, uri, options, codec, method, args); } if (circuitBreaker.canRequest()) { final Future<T> resultFut = delegate().invoke(eventLoop, uri, options, codec, method, args); resultFut.addListener(future -> { if (future.isSuccess()) { // reports success event circuitBreaker.onSuccess(); } else { circuitBreaker.onFailure(future.cause()); } }); return resultFut; } else { // the circuit is tripped // prepares a failed resultPromise final Promise<T> resultPromise = eventLoop.newPromise(); resultPromise.setFailure(new FailFastException(circuitBreaker)); codec.prepareRequest(method, args, resultPromise); // returns immediately without calling succeeding remote invokers return resultPromise; } }