List of usage examples for io.netty.util.concurrent Future isSuccess
boolean isSuccess();
From source file:com.kixeye.kixmpp.server.module.muc.MucRoom.java
License:Apache License
/** * A user requests to join the room./*from www .j a va 2 s .c o m*/ * * @param channel * @param nickname * @param mucStanza */ public void join(final Channel channel, String nickname, Element mucStanza) { KixmppJid jid = channel.attr(BindKixmppServerModule.JID).get(); if (settings.isOpen() && !jidRoles.containsKey(jid.withoutResource())) { addUser(jid, nickname, MucRole.Participant, MucAffiliation.Member); } verifyMembership(jid.withoutResource()); checkForNicknameInUse(nickname, jid); User user = usersByNickname.get(nickname); boolean existingUser = true; if (user == null) { user = new User(nickname, jid.withoutResource()); usersByNickname.put(nickname, user); MucRoomEventHandler handler = service.getServer().getMucRoomEventHandler(); if (handler != null) { handler.userAdded(this, user); } existingUser = false; } Client client = user.addClient(new Client(jid, nickname, channel)); // xep-0045 7.2.3 begin // self presence KixmppJid fromRoomJid = roomJid.withResource(nickname); channel.writeAndFlush(createPresence(fromRoomJid, jid, MucRole.Participant, null)); if (settings.isPresenceEnabled() && !existingUser) { // Send presence from existing occupants to new occupant sendExistingOccupantsPresenceToNewOccupant(user, channel); // Send new occupant's presence to all occupants broadcastPresence(fromRoomJid, MucRole.Participant, null); } // xep-0045 7.2.3 end if (settings.getSubject() != null) { Element message = new Element("message"); message.setAttribute("id", UUID.randomUUID().toString()); message.setAttribute("from", roomJid.withResource(nickname).toString()); message.setAttribute("to", channel.attr(BindKixmppServerModule.JID).get().toString()); message.setAttribute("type", "groupchat"); message.addContent(new Element("subject").setText(settings.getSubject())); channel.writeAndFlush(message); } if (mucStanza != null) { Element history = mucStanza.getChild("history", mucStanza.getNamespace()); if (history != null) { MucHistoryProvider historyProvider = mucModule.getHistoryProvider(); if (historyProvider != null) { Integer maxChars = null; Integer maxStanzas = null; Integer seconds = null; String parsableString = history.getAttributeValue("maxchars"); if (parsableString != null) { try { maxChars = Integer.parseInt(parsableString); } catch (Exception e) { } } parsableString = history.getAttributeValue("maxstanzas"); if (parsableString != null) { try { maxStanzas = Integer.parseInt(parsableString); } catch (Exception e) { } } parsableString = history.getAttributeValue("seconds"); if (parsableString != null) { try { seconds = Integer.parseInt(parsableString); } catch (Exception e) { } } String since = history.getAttributeValue("since"); historyProvider.getHistory(roomJid, user.getBareJid(), maxChars, maxStanzas, seconds, since) .addListener(new GenericFutureListener<Future<List<MucHistory>>>() { @Override public void operationComplete(Future<List<MucHistory>> future) throws Exception { if (future.isSuccess()) { List<MucHistory> historyItems = future.get(); if (historyItems != null) { for (MucHistory historyItem : historyItems) { Element message = new Element("message") .setAttribute("id", UUID.randomUUID().toString()) .setAttribute("from", roomJid.withResource(historyItem.getNickname()) .toString()) .setAttribute("to", channel.attr(BindKixmppServerModule.JID).get() .toString()) .setAttribute("type", "groupchat"); message.addContent( new Element("body").setText(historyItem.getBody())); Element addresses = new Element("addresses", Namespace .getNamespace("http://jabber.org/protocol/address")); addresses .addContent(new Element("address", addresses.getNamespace()) .setAttribute("type", "ofrom").setAttribute("jid", historyItem.getFrom().toString())); message.addContent(addresses); message.addContent(new Element("delay", Namespace.getNamespace("urn:xmpp:delay")) .setAttribute("from", roomJid.toString()) .setAttribute("stamp", XmppDateUtils .format(historyItem.getTimestamp()))); channel.write(message); } channel.flush(); } } } }); } } } channel.closeFuture().addListener(new CloseChannelListener(client)); }
From source file:com.kixeye.kixmpp.server.module.muc.MucRoom.java
License:Apache License
private void sendExistingOccupantsPresenceToNewOccupant(final User newUser, final Channel channel) { final KixmppJid jid = channel.attr(BindKixmppServerModule.JID).get(); final MucRole role = jidRoles.get(jid.withoutResource()); Promise<Set<String>> promise = service.getServer().createPromise(); promise.addListener(new GenericFutureListener<Future<Set<String>>>() { @Override// www .j ava2 s . co m public void operationComplete(Future<Set<String>> future) throws Exception { if (future.isSuccess()) { Set<String> nicknames = future.get(); for (String nickname : nicknames) { if (newUser.getNickname().equals(nickname)) { continue; } Element presence = createPresence(roomJid.withResource(nickname), jid, role, null); channel.write(presence); } if (!nicknames.isEmpty()) { channel.flush(); } } } }); service.getServer() .sendMapReduceRequest(new GetMucRoomNicknamesRequest(service.getSubDomain(), roomId, jid, promise)); }
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} * //from w w w. jav 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.CircuitBreakerRemoteInvokerTest.java
License:Apache License
@SuppressWarnings("unchecked") private static <T> Future<T> successFuture() { Future<T> future = mockFuture(); when(future.isSuccess()).thenReturn(true); return future; }
From source file:com.linecorp.armeria.client.circuitbreaker.CircuitBreakerRemoteInvokerTest.java
License:Apache License
@SuppressWarnings("unchecked") private static <T> Future<T> failedFuture() { Future<T> future = mockFuture(); when(future.isSuccess()).thenReturn(false); when(future.cause()).thenReturn(new Exception()); return future; }
From source file:com.linecorp.armeria.client.circuitbreaker.CircuitBreakerRemoteInvokerTest.java
License:Apache License
@Test public void testStateTransition() throws Exception { FakeTicker ticker = new FakeTicker(); int minimumRequestThreshold = 2; Duration circuitOpenWindow = Duration.ofSeconds(60); Duration counterSlidingWindow = Duration.ofSeconds(180); Duration counterUpdateInterval = Duration.ofMillis(1); Future<Object> successFuture = successFuture(); Future<Object> failedFuture = failedFuture(); CircuitBreaker circuitBreaker = new CircuitBreakerBuilder(remoteServiceName) .minimumRequestThreshold(minimumRequestThreshold).circuitOpenWindow(circuitOpenWindow) .counterSlidingWindow(counterSlidingWindow).counterUpdateInterval(counterUpdateInterval) .ticker(ticker).build();//from www . java 2 s.com RemoteInvoker remoteInvoker = mock(RemoteInvoker.class); // return failed future when(remoteInvoker.invoke(any(), any(), any(), any(), any(), any())).thenReturn(failedFuture); CircuitBreakerMapping mapping = (eventLoop1, uri, options1, codec1, method, args1) -> circuitBreaker; CircuitBreakerRemoteInvoker stub = new CircuitBreakerRemoteInvoker(remoteInvoker, mapping); // CLOSED for (int i = 0; i < minimumRequestThreshold + 1; i++) { Future<Object> future = stub.invoke(eventLoop, uri, options, codec, methodA(), args); // The future is `failedFuture` itself assertThat(future.isSuccess(), is(false)); // This is not a CircuitBreakerException assertThat(future.cause(), is(not(instanceOf(FailFastException.class)))); ticker.advance(Duration.ofMillis(1).toNanos()); } // OPEN Future<Object> future1 = stub.invoke(eventLoop, uri, options, codec, methodA(), args); // The circuit is OPEN assertThat(future1.isSuccess(), is(false)); assertThat(future1.cause(), instanceOf(FailFastException.class)); assertThat(((FailFastException) future1.cause()).getCircuitBreaker(), is(circuitBreaker)); ticker.advance(circuitOpenWindow.toNanos()); // return success future when(remoteInvoker.invoke(any(), any(), any(), any(), any(), any())).thenReturn(successFuture); // HALF OPEN Future<Object> future2 = stub.invoke(eventLoop, uri, options, codec, methodA(), args); assertThat(future2.isSuccess(), is(true)); // CLOSED Future<Object> future3 = stub.invoke(eventLoop, uri, options, codec, methodA(), args); assertThat(future3.isSuccess(), is(true)); }
From source file:com.linecorp.armeria.client.circuitbreaker.CircuitBreakerRemoteInvokerTest.java
License:Apache License
@Test public void testServiceScope() throws Exception { FakeTicker ticker = new FakeTicker(); int minimumRequestThreshold = 2; Duration circuitOpenWindow = Duration.ofSeconds(60); Duration counterSlidingWindow = Duration.ofSeconds(180); Duration counterUpdateInterval = Duration.ofMillis(1); Future<Object> successFuture = successFuture(); Future<Object> failedFuture = failedFuture(); CircuitBreaker circuitBreaker = new CircuitBreakerBuilder(remoteServiceName) .minimumRequestThreshold(minimumRequestThreshold).circuitOpenWindow(circuitOpenWindow) .counterSlidingWindow(counterSlidingWindow).counterUpdateInterval(counterUpdateInterval) .ticker(ticker).build();/*from www . j a v a 2 s . com*/ RemoteInvoker remoteInvoker = mock(RemoteInvoker.class); // Always return failed future for methodA when(remoteInvoker.invoke(any(), any(), any(), any(), eq(methodA()), any())).thenReturn(failedFuture); // Always return success future for methodB when(remoteInvoker.invoke(any(), any(), any(), any(), eq(methodB()), any())).thenReturn(successFuture); CircuitBreakerMapping mapping = (eventLoop1, uri, options1, codec1, method, args1) -> circuitBreaker; CircuitBreakerRemoteInvoker stub = new CircuitBreakerRemoteInvoker(remoteInvoker, mapping); // CLOSED for (int i = 0; i < minimumRequestThreshold + 1; i++) { stub.invoke(eventLoop, uri, options, codec, methodA(), args); ticker.advance(Duration.ofMillis(1).toNanos()); } // OPEN (methodA) Future<Object> future1 = stub.invoke(eventLoop, uri, options, codec, methodA(), args); assertThat(future1.isSuccess(), is(false)); assertThat(future1.cause(), instanceOf(FailFastException.class)); // OPEN (methodB) Future<Object> future2 = stub.invoke(eventLoop, uri, options, codec, methodB(), args); assertThat(future2.isSuccess(), is(false)); assertThat(future2.cause(), instanceOf(FailFastException.class)); }
From source file:com.linecorp.armeria.client.circuitbreaker.CircuitBreakerRemoteInvokerTest.java
License:Apache License
@Test public void testPerMethodScope() throws Exception { FakeTicker ticker = new FakeTicker(); int minimumRequestThreshold = 2; Duration circuitOpenWindow = Duration.ofSeconds(60); Duration counterSlidingWindow = Duration.ofSeconds(180); Duration counterUpdateInterval = Duration.ofMillis(1); Future<Object> successFuture = successFuture(); Future<Object> failedFuture = failedFuture(); Function<String, CircuitBreaker> factory = method -> new CircuitBreakerBuilder(remoteServiceName) .minimumRequestThreshold(minimumRequestThreshold).circuitOpenWindow(circuitOpenWindow) .counterSlidingWindow(counterSlidingWindow).counterUpdateInterval(counterUpdateInterval) .ticker(ticker).build();/*from w w w .j ava 2 s .c o m*/ RemoteInvoker remoteInvoker = mock(RemoteInvoker.class); // Always return failed future for methodA when(remoteInvoker.invoke(any(), any(), any(), any(), eq(methodA()), any())).thenReturn(failedFuture); // Always return success future for methodB when(remoteInvoker.invoke(any(), any(), any(), any(), eq(methodB()), any())).thenReturn(successFuture); CircuitBreakerMapping mapping = new KeyedCircuitBreakerMapping<>(KeySelector.METHOD, factory::apply); CircuitBreakerRemoteInvoker stub = new CircuitBreakerRemoteInvoker(remoteInvoker, mapping); // CLOSED (methodA) for (int i = 0; i < minimumRequestThreshold + 1; i++) { stub.invoke(eventLoop, uri, options, codec, methodA(), args); ticker.advance(Duration.ofMillis(1).toNanos()); } // OPEN (methodA) Future<Object> future1 = stub.invoke(eventLoop, uri, options, codec, methodA(), args); assertThat(future1.isSuccess(), is(false)); assertThat(future1.cause(), instanceOf(FailFastException.class)); // CLOSED (methodB) Future<Object> future2 = stub.invoke(eventLoop, uri, options, codec, methodB(), args); assertThat(future2.isSuccess(), is(true)); }
From source file:com.linecorp.armeria.client.circuitbreaker.CircuitBreakerRemoteInvokerTest.java
License:Apache License
@Test public void testExceptionFilter() throws Exception { FakeTicker ticker = new FakeTicker(); int minimumRequestThreshold = 2; Duration circuitOpenWindow = Duration.ofSeconds(60); Duration counterSlidingWindow = Duration.ofSeconds(180); Duration counterUpdateInterval = Duration.ofMillis(1); Future<Object> failedFuture = failedFuture(); // a filter that ignores all exception ExceptionFilter exceptionFilter = (cause) -> false; CircuitBreaker circuitBreaker = new CircuitBreakerBuilder(remoteServiceName) .minimumRequestThreshold(minimumRequestThreshold).circuitOpenWindow(circuitOpenWindow) .counterSlidingWindow(counterSlidingWindow).counterUpdateInterval(counterUpdateInterval) .exceptionFilter(exceptionFilter).ticker(ticker).build(); RemoteInvoker remoteInvoker = mock(RemoteInvoker.class); // return failed future when(remoteInvoker.invoke(any(), any(), any(), any(), any(), any())).thenReturn(failedFuture); CircuitBreakerMapping mapping = (eventLoop1, uri, options1, codec1, method, args1) -> circuitBreaker; CircuitBreakerRemoteInvoker stub = new CircuitBreakerRemoteInvoker(remoteInvoker, mapping); // CLOSED/*from w w w . j av a2 s .c om*/ for (int i = 0; i < minimumRequestThreshold + 1; i++) { Future<Object> future = stub.invoke(eventLoop, uri, options, codec, methodA(), args); // The future is `failedFuture` itself assertThat(future.isSuccess(), is(false)); // This is not a CircuitBreakerException assertThat(future.cause(), is(not(instanceOf(FailFastException.class)))); ticker.advance(Duration.ofMillis(1).toNanos()); } // OPEN Future<Object> future1 = stub.invoke(eventLoop, uri, options, codec, methodA(), args); // The circuit is still CLOSED assertThat(future1.isSuccess(), is(false)); assertThat(future1.cause(), is(not(instanceOf(FailFastException.class)))); }
From source file:com.linecorp.armeria.client.endpoint.dns.DnsEndpointGroup.java
License:Apache License
private void sendQueries() { if (stopped) { return;//from ww w. jav a 2 s . 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); }