List of usage examples for io.netty.util.concurrent Promise setSuccess
Promise<V> setSuccess(V result);
From source file:com.cloudera.livy.rsc.RSCClient.java
License:Apache License
private <T> io.netty.util.concurrent.Future<T> deferredCall(final Object msg, final Class<T> retType) { if (driverRpc.isSuccess()) { try {/*from w ww .j a va 2 s . co m*/ return driverRpc.get().call(msg, retType); } catch (Exception ie) { throw Utils.propagate(ie); } } // No driver RPC yet, so install a listener and return a promise that will be ready when // the driver is up and the message is actually delivered. final Promise<T> promise = eventLoopGroup.next().newPromise(); final FutureListener<T> callListener = new FutureListener<T>() { @Override public void onSuccess(T value) throws Exception { promise.setSuccess(value); } @Override public void onFailure(Throwable error) throws Exception { promise.setFailure(error); } }; Utils.addListener(driverRpc, new FutureListener<Rpc>() { @Override public void onSuccess(Rpc rpc) throws Exception { Utils.addListener(rpc.call(msg, retType), callListener); } @Override public void onFailure(Throwable error) throws Exception { promise.setFailure(error); } }); return promise; }
From source file:com.cloudera.livy.rsc.RSCClientFactory.java
License:Apache License
private static Promise<ContextInfo> createContextInfo(final URI uri) { String[] userInfo = uri.getUserInfo().split(":", 2); ImmediateEventExecutor executor = ImmediateEventExecutor.INSTANCE; Promise<ContextInfo> promise = executor.newPromise(); promise.setSuccess(new ContextInfo(uri.getHost(), uri.getPort(), userInfo[0], userInfo[1])); return promise; }
From source file:com.github.milenkovicm.kafka.KafkaProducer.java
License:Apache License
void completePromise(final Promise<Void> promise, List<ChannelFuture> promises) { if (promises.size() > 0) { final PromiseAggregator<Void, ChannelFuture> promiseAggregator = new PromiseAggregator<Void, ChannelFuture>( promise) {/* w ww .ja v a2 s .c om*/ }; promiseAggregator.add(promises.toArray(new Promise[1])); } else { promise.setSuccess(null); } }
From source file:com.kixeye.kixmpp.server.KixmppServerTest.java
License:Apache License
@Test public void testSimpleUsingKixmppWithHistory() throws Exception { try (KixmppServer server = new KixmppServer(new InetSocketAddress(SocketUtils.findAvailableTcpPort()), "testChat", new InetSocketAddress(SocketUtils.findAvailableTcpPort()), new ConstNodeDiscovery())) { Assert.assertNotNull(server.start().get(2, TimeUnit.SECONDS)); ((InMemoryAuthenticationService) server.module(SaslKixmppServerModule.class).getAuthenticationService()) .addUser("testUser", "testPassword"); server.module(MucKixmppServerModule.class).addService("conference").addRoom("someRoom"); server.module(MucKixmppServerModule.class).setHistoryProvider(new MucHistoryProvider() { public Promise<List<MucHistory>> getHistory(KixmppJid roomJid, KixmppJid userJid, Integer maxChars, Integer maxStanzas, Integer seconds, String since) { Promise<List<MucHistory>> promise = server.createPromise(); List<MucHistory> history = new ArrayList<>(maxStanzas); for (int i = 0; i < maxStanzas; i++) { history.add(new MucHistory( KixmppJid.fromRawJid("user" + i + "@" + server.getDomain() + "/computer"), roomJid, "nick" + i, "message" + i, System.currentTimeMillis())); }/*from ww w . ja v a 2s. c om*/ promise.setSuccess(history); return promise; } }); try (KixmppClient client = new KixmppClient(SslContext.newClientContext(), KixmppClient.Type.TCP)) { final LinkedBlockingQueue<Presence> presences = new LinkedBlockingQueue<>(); final LinkedBlockingQueue<MucJoin> mucJoins = new LinkedBlockingQueue<>(); final LinkedBlockingQueue<MucMessage> mucMessages = new LinkedBlockingQueue<>(); Assert.assertNotNull( client.connect("localhost", server.getBindAddress().getPort(), server.getDomain()).get(2, TimeUnit.SECONDS)); client.module(PresenceKixmppClientModule.class).addPresenceListener(new PresenceListener() { public void handle(Presence presence) { presences.offer(presence); } }); client.module(MucKixmppClientModule.class).addJoinListener(new MucListener<MucJoin>() { public void handle(MucJoin event) { mucJoins.offer(event); } }); client.module(MucKixmppClientModule.class).addMessageListener(new MucListener<MucMessage>() { public void handle(MucMessage event) { mucMessages.offer(event); } }); Assert.assertNotNull( client.login("testUser", "testPassword", "testResource").get(2, TimeUnit.SECONDS)); client.module(PresenceKixmppClientModule.class).updatePresence(new Presence()); Assert.assertNotNull(presences.poll(2, TimeUnit.SECONDS)); client.module(MucKixmppClientModule.class).joinRoom( KixmppJid.fromRawJid("someRoom@conference.testChat"), "testNick", 5, null, null, null); MucJoin mucJoin = mucJoins.poll(2, TimeUnit.SECONDS); Assert.assertNotNull(mucJoin); int count = 0; while (mucMessages.poll(2, TimeUnit.SECONDS) != null) { count++; } Assert.assertEquals(5, count); } } }
From source file:com.kixeye.kixmpp.server.module.auth.InMemoryAuthenticationService.java
License:Apache License
/** * @see com.kixeye.kixmpp.server.module.auth.AuthenticationService#authenticate(java.lang.String, java.lang.String) *//*from w w w . j a v a 2s .c o m*/ public Promise<Boolean> authenticate(String username, String password) { Promise<Boolean> promise = server.createPromise(); promise.setSuccess(password.equals(users.get(username.toLowerCase()))); return promise; }
From source file:com.linecorp.armeria.client.endpoint.dns.DnsEndpointGroup.java
License:Apache License
private void sendQueries() { if (stopped) { return;/*w w w . j a v a 2s . c om*/ } final Future<List<DnsRecord>> future; final int numQuestions = questions.size(); if (numQuestions == 1) { // Simple case of single query final DnsQuestion question = questions.get(0); logger.debug("{} Sending a DNS query", logPrefix); future = resolver.resolveAll(question); } else { // Multiple queries logger.debug("{} Sending DNS queries", logPrefix); @SuppressWarnings("unchecked") final Promise<List<DnsRecord>> aggregatedPromise = eventLoop.newPromise(); final FutureListener<List<DnsRecord>> listener = new FutureListener<List<DnsRecord>>() { private final List<DnsRecord> records = new ArrayList<>(); private int remaining = numQuestions; @Nullable private List<Throwable> causes; @Override public void operationComplete(Future<List<DnsRecord>> future) throws Exception { if (future.isSuccess()) { final List<DnsRecord> records = future.getNow(); this.records.addAll(records); } else { if (causes == null) { causes = new ArrayList<>(numQuestions); } causes.add(future.cause()); } if (--remaining == 0) { if (!records.isEmpty()) { aggregatedPromise.setSuccess(records); } else { final Throwable aggregatedCause; if (causes == null) { aggregatedCause = new EndpointGroupException("empty result returned by DNS server"); } else { aggregatedCause = new EndpointGroupException("failed to receive DNS records"); for (Throwable c : causes) { aggregatedCause.addSuppressed(c); } } aggregatedPromise.setFailure(aggregatedCause); } } } }; questions.forEach(q -> resolver.resolveAll(q).addListener(listener)); future = aggregatedPromise; } attemptsSoFar++; future.addListener(this::onDnsRecords); }
From source file:com.linecorp.armeria.client.http.DefaultSimpleHttpClient.java
License:Apache License
@Override public Future<SimpleHttpResponse> execute(SimpleHttpRequest sReq) { final EventLoop eventLoop = client.eventLoop0(); final Promise<SimpleHttpResponse> promise = eventLoop.newPromise(); try {/*from w w w. j av a 2 s.c o m*/ URI uri = sReq.uri(); StringBuilder uriBuilder = new StringBuilder(uri.getPath()); if (uri.getQuery() != null) { uriBuilder.append('?'); uriBuilder.append(uri.getQuery()); } if (uri.getFragment() != null) { uriBuilder.append('#'); uriBuilder.append(uri.getFragment()); } final AggregatedHttpMessage aReq = AggregatedHttpMessage.of(HttpMethod.valueOf(sReq.method().name()), uriBuilder.toString(), HttpData.of(sReq.content())); // Convert the headers. ArmeriaHttpUtil.toArmeria(sReq.headers(), aReq.headers()); final HttpResponse res = client.execute(eventLoop, aReq); res.aggregate().handle(voidFunction((aRes, cause) -> { if (cause != null) { promise.setFailure(cause); } else { try { final HttpData aContent = aRes.content(); final byte[] content; if (aContent.offset() == 0 && aContent.length() == aContent.array().length) { content = aContent.array(); } else { content = Arrays.copyOfRange(aContent.array(), aContent.offset(), aContent.length()); } final SimpleHttpResponse sRes = new SimpleHttpResponse( HttpResponseStatus.valueOf(aRes.status().code()), ArmeriaHttpUtil.toNettyHttp1(aRes.headers()), content); promise.setSuccess(sRes); } catch (Throwable t) { promise.setFailure(t); } } })).exceptionally(CompletionActions::log); } catch (Throwable t) { promise.setFailure(t); } return promise; }
From source file:com.linecorp.armeria.client.pool.DefaultKeyedChannelPool.java
License:Apache License
private void notifyConnect(K key, Future<Channel> future, Promise<Channel> promise) { assert future.isDone(); try {//from ww w . j ava 2 s . co m if (future.isSuccess()) { Channel channel = future.getNow(); channel.attr(KeyedChannelPoolUtil.POOL).set(this); channelPoolHandler.channelCreated(key, channel); channel.closeFuture().addListener(f -> channelPoolHandler.channelClosed(key, channel)); promise.setSuccess(channel); } else { promise.setFailure(future.cause()); } } catch (Exception e) { promise.setFailure(e); } }
From source file:com.linecorp.armeria.client.pool.DefaultKeyedChannelPool.java
License:Apache License
private void notifyHealthCheck(final K key, Future<Boolean> future, Channel ch, Promise<Channel> promise) { assert ch.eventLoop().inEventLoop(); if (future.isSuccess()) { if (future.getNow() == Boolean.TRUE) { try { ch.attr(KeyedChannelPoolUtil.POOL).set(this); channelPoolHandler.channelAcquired(key, ch); promise.setSuccess(ch); } catch (Throwable cause) { closeAndFail(ch, cause, promise); }// w w w . j ava 2s .c o m } else { closeChannel(ch); acquireHealthyFromPoolOrNew(key, promise); } } else { closeChannel(ch); acquireHealthyFromPoolOrNew(key, promise); } }
From source file:com.linecorp.armeria.client.pool.DefaultKeyedChannelPool.java
License:Apache License
private void releaseAndOffer(K key, Channel channel, Promise<Void> promise) throws Exception { if (offerChannel(key, channel)) { channelPoolHandler.channelReleased(key, channel); promise.setSuccess(null); } else {//ww w .j a v a 2 s. c o m closeAndFail(channel, FULL_EXCEPTION, promise); } }