public CompletableFuture<ClientSecureChannel> getChannel() {
    State currentState = state.get();

    logger.trace("getChannel(), currentState={}", currentState.getClass().getSimpleName());

    if (currentState instanceof Idle) {
      Connecting nextState = new Connecting();

      if (state.compareAndSet(currentState, nextState)) {
        CompletableFuture<ClientSecureChannel> connected = nextState.connected;

        connect(true, connected);

        return connected.whenCompleteAsync(
            (sc, ex) -> {
              if (sc != null) {
                if (state.compareAndSet(nextState, new Connected(connected))) {
                  sc.getChannel().pipeline().addLast(new InactivityHandler());
                }
              } else {
                state.compareAndSet(nextState, new Idle());
              }
            });
      } else {
        return getChannel();
      }
    } else if (currentState instanceof Connecting) {
      return ((Connecting) currentState).connected;
    } else if (currentState instanceof Connected) {
      return ((Connected) currentState).connected;
    } else if (currentState instanceof Reconnecting) {
      return ((Reconnecting) currentState).reconnected;
    } else if (currentState instanceof Disconnecting) {
      CompletableFuture<ClientSecureChannel> future = new CompletableFuture<>();

      CompletableFuture<Unit> disconnectFuture = ((Disconnecting) currentState).disconnectFuture;

      disconnectFuture.whenCompleteAsync(
          (u, ex) ->
              getChannel()
                  .whenCompleteAsync(
                      (sc, ex2) -> {
                        if (sc != null) future.complete(sc);
                        else future.completeExceptionally(ex2);
                      }),
          client.getExecutorService());

      return future;
    } else {
      throw new IllegalStateException(currentState.getClass().getSimpleName());
    }
  }
  @Test
  public void testAddOnPrivateChatMessageListener() throws Exception {
    CompletableFuture<String> usernameFuture = new CompletableFuture<>();
    CompletableFuture<ChatMessage> chatMessageFuture = new CompletableFuture<>();
    instance.addOnPrivateChatMessageListener(
        (username, chatMessage) -> {
          usernameFuture.complete(username);
          chatMessageFuture.complete(chatMessage);
        });

    String message = "private message";

    User user = mock(User.class);
    when(user.getNick()).thenReturn(chatUser1.getUsername());

    Channel channel = mock(Channel.class);
    when(channel.getName()).thenReturn(DEFAULT_CHANNEL_NAME);

    UserHostmask userHostMask = mock(UserHostmask.class);
    instance.onEvent(new PrivateMessageEvent(pircBotX, userHostMask, user, message));

    assertThat(chatMessageFuture.get().getMessage(), is(message));
    assertThat(chatMessageFuture.get().getUsername(), is(chatUser1.getUsername()));
    assertThat(
        chatMessageFuture.get().getTime(),
        is(greaterThan(Instant.ofEpochMilli(System.currentTimeMillis() - 1000))));
    assertThat(chatMessageFuture.get().isAction(), is(false));
  }
Exemple #3
0
  @Override
  public CompletionStage<com.zeroc.Ice.Object.Ice_invokeResult> ice_invokeAsync(
      byte[] inEncaps, Current current) {
    boolean twoway = current.requestId > 0;
    ObjectPrx obj = current.con.createProxy(current.id);
    if (!twoway) {
      if (_startBatch) {
        _startBatch = false;
        _batchProxy = obj.ice_batchOneway();
      }
      if (_batchProxy != null) {
        obj = _batchProxy;
      }

      if (!current.facet.isEmpty()) {
        obj = obj.ice_facet(current.facet);
      }

      final com.zeroc.Ice.Object.Ice_invokeResult success =
          new com.zeroc.Ice.Object.Ice_invokeResult(true, new byte[0]);

      if (_batchProxy != null) {
        obj.ice_invoke(current.operation, current.mode, inEncaps, current.ctx);
        return CompletableFuture.completedFuture(success);
      } else {
        final CompletableFuture<com.zeroc.Ice.Object.Ice_invokeResult> future =
            new CompletableFuture<com.zeroc.Ice.Object.Ice_invokeResult>();
        CompletableFuture<com.zeroc.Ice.Object.Ice_invokeResult> r =
            obj.ice_oneway()
                .ice_invokeAsync(current.operation, current.mode, inEncaps, current.ctx);
        com.zeroc.Ice.Util.getInvocationFuture(r)
            .whenSent(
                (sentSynchronously, ex) -> {
                  if (ex != null) {
                    future.completeExceptionally(ex);
                  } else {
                    future.complete(success);
                  }
                });
        return future;
      }
    } else {
      if (!current.facet.isEmpty()) {
        obj = obj.ice_facet(current.facet);
      }

      final CompletableFuture<com.zeroc.Ice.Object.Ice_invokeResult> future =
          new CompletableFuture<com.zeroc.Ice.Object.Ice_invokeResult>();
      obj.ice_invokeAsync(current.operation, current.mode, inEncaps, current.ctx)
          .whenComplete(
              (result, ex) -> {
                if (ex != null) {
                  future.completeExceptionally(ex);
                } else {
                  future.complete(result);
                }
              });
      return future;
    }
  }
  @Test
  public void testReconnect() throws Exception {
    CompletableFuture<Boolean> firstStartFuture = new CompletableFuture<>();
    CompletableFuture<Boolean> secondStartFuture = new CompletableFuture<>();
    doAnswer(
            invocation -> {
              if (!firstStartFuture.isDone()) {
                firstStartFuture.complete(true);
                throw new IOException("test exception");
              }

              secondStartFuture.complete(true);
              botShutdownLatch.await();
              return null;
            })
        .when(pircBotX)
        .startBot();

    instance.connect();
    firstStartFuture.get(TIMEOUT, TIMEOUT_UNIT);

    secondStartFuture.get(TIMEOUT, TIMEOUT_UNIT);

    verify(pircBotX, times(2)).startBot();
  }
 @BeforeTest
 public void setup() {
   MockitoAnnotations.initMocks(this);
   CompletableFuture<User> eric = new CompletableFuture<>();
   eric.complete(new User("eric", "3r1c", Arrays.asList("USER")));
   when(userService.getByUsername("eric")).thenReturn(eric);
   CompletableFuture<User> michel = new CompletableFuture<>();
   michel.complete(new User("michel", "m1ch3l", Arrays.asList("USER", "ADMIN")));
   when(userService.getByUsername("michel")).thenReturn(michel);
   this.interceptor = new SecurityChannelInterceptor(this.userService);
   this.interceptor.loadConfiguration("test-security.yml");
 }
  private byte[] getFromCache(int site) {

    int blockNumber = site / myNumLinesPerInterval;

    byte[][] result = myGenoCache.getIfPresent(blockNumber);

    if (result == null) {

      CompletableFuture<byte[]> future = new CompletableFuture<>();
      CompletableFuture<byte[]> temp = myFutureQueue.putIfAbsent(site, future);
      if (temp != null) {
        future = temp;
      }
      if (myCurrentlyProcessingBlocks.add(blockNumber)) {
        myThreadPool.submit(new ProcessLines(site));
      }

      try {
        result = myGenoCache.getIfPresent(blockNumber);
        if (result != null) {
          myFutureQueue.remove(site);
          future.complete(result[site % myNumLinesPerInterval]);
          return result[site % myNumLinesPerInterval];
        } else {
          return future.get();
        }
      } catch (Exception e) {
        myLogger.error(e.getMessage(), e);
      }
    }

    return result[site % myNumLinesPerInterval];
  }
Exemple #7
0
 @Override
 public CompletableFuture<Void> close() {
   CompletableFuture<Void> future = new CompletableFuture<>();
   lock.lock()
       .thenCompose(v -> balancer.replace(server.server().cluster()))
       .whenComplete(
           (r1, e1) -> {
             balancer.close();
             lock.unlock()
                 .whenComplete(
                     (r2, e2) -> {
                       super.close()
                           .whenComplete(
                               (r3, e3) -> {
                                 server
                                     .close()
                                     .whenComplete(
                                         (r4, e4) -> {
                                           if (e4 == null) {
                                             future.complete(null);
                                           } else {
                                             future.completeExceptionally(e4);
                                           }
                                         });
                               });
                     });
           });
   return future;
 }
  /** Registers the session. */
  private CompletableFuture<Void> register() {
    context.checkThread();

    CompletableFuture<Void> future = new CompletableFuture<>();

    RegisterRequest request = RegisterRequest.builder().withClient(clientId).build();

    this.<RegisterRequest, RegisterResponse>request(request, new CompletableFuture<>(), false, true)
        .whenComplete(
            (response, error) -> {
              if (error == null) {
                if (response.status() == Response.Status.OK) {
                  setMembers(response.members());
                  setTimeout(response.timeout());
                  onOpen(response.session());
                  setupConnection(connection)
                      .whenComplete((setupResult, setupError) -> future.complete(null));
                  resetMembers()
                      .keepAlive(
                          Duration.ofMillis(Math.round(response.timeout() * KEEP_ALIVE_RATIO)));
                } else {
                  future.completeExceptionally(response.error().createException());
                }
              } else {
                future.completeExceptionally(error);
              }
            });
    return future;
  }
  @Override
  public void notifyTransactionDataReceived(int topologyId) {
    if (topologyId < transactionDataTopologyId) {
      throw new IllegalStateException(
          "Cannot set a topology id ("
              + topologyId
              + ") that is lower than the current one ("
              + transactionDataTopologyId
              + ")");
    }
    if (trace) {
      log.tracef("Signalling transaction data received for topology %d", topologyId);
    }
    transactionDataTopologyId = topologyId;

    CompletableFuture<Void> oldFuture = null;
    try {
      synchronized (this) {
        oldFuture = transactionDataFuture;
        transactionDataFuture = new CompletableFuture<>();
      }
    } finally {
      if (oldFuture != null) {
        oldFuture.complete(null);
      }
    }
  }
 @Override
 public void notifyTopologyInstalled(int topologyId) {
   if (topologyId < this.topologyId) {
     throw new IllegalStateException(
         "Cannot set a topology id ("
             + topologyId
             + ") that is lower than the current one ("
             + this.topologyId
             + ")");
   }
   if (trace) {
     log.tracef("Signalling topology %d is installed", topologyId);
   }
   this.topologyId = topologyId;
   CompletableFuture<Void> oldFuture = null;
   try {
     synchronized (this) {
       oldFuture = topologyFuture;
       topologyFuture = new CompletableFuture();
     }
   } finally {
     if (oldFuture != null) {
       oldFuture.complete(null);
     }
   }
 }
  /*
   *	@param t Result type
   * @see java.util.function.Consumer#accept(java.lang.Object)
   */
  @Override
  public void accept(FastFuture<T> t) {

    active.add(t);

    if (active.size() > maxActive.getMaxActive()) {

      while (active.size() > maxActive.getReduceTo()) {

        List<FastFuture> toRemove =
            active
                .stream()
                .filter(cf -> cf.isDone())
                .peek(this::handleExceptions)
                .collect(Collectors.toList());

        active.removeAll(toRemove);
        if (active.size() > maxActive.getReduceTo()) {
          CompletableFuture promise = new CompletableFuture();
          FastFuture.xOf(
              active.size() - maxActive.getReduceTo(),
              () -> promise.complete(true),
              active.toArray(new FastFuture[0]));

          promise.join();
        }
      }
    }
  }
Exemple #12
0
 static void checkCompletedNormally(CompletableFuture<?> cf, Object[] values) {
   try {
     equalAnyOf(cf.join(), values);
   } catch (Throwable x) {
     unexpected(x);
   }
   try {
     equalAnyOf(cf.getNow(null), values);
   } catch (Throwable x) {
     unexpected(x);
   }
   try {
     equalAnyOf(cf.get(), values);
   } catch (Throwable x) {
     unexpected(x);
   }
   try {
     equalAnyOf(cf.get(0L, SECONDS), values);
   } catch (Throwable x) {
     unexpected(x);
   }
   check(cf.isDone(), "Expected isDone to be true, got:" + cf);
   check(!cf.isCancelled(), "Expected isCancelled to be false");
   check(!cf.cancel(true), "Expected cancel to return false");
   check(cf.toString().contains("[Completed normally]"));
   check(cf.complete(null) == false, "Expected complete() to fail");
   check(
       cf.completeExceptionally(new Throwable()) == false,
       "Expected completeExceptionally() to fail");
 }
  private CompletableFuture<Void> waitForEnvironmentInitialization(
      BuildExecutionSession buildExecutionSession, StartedEnvironment startedEnvironment) {
    CompletableFuture<Void> waitToCompleteFuture = new CompletableFuture<>();
    try {
      Consumer<RunningEnvironment> onComplete =
          (runningEnvironment) -> {
            buildExecutionSession.setRunningEnvironment(runningEnvironment);
            buildExecutionSession.setStatus(BuildExecutionStatus.BUILD_ENV_SETUP_COMPLETE_SUCCESS);
            waitToCompleteFuture.complete(null);
          };
      Consumer<Exception> onError =
          (e) -> {
            buildExecutionSession.setStatus(
                BuildExecutionStatus.BUILD_ENV_SETUP_COMPLETE_WITH_ERROR);
            waitToCompleteFuture.completeExceptionally(
                new BuildProcessException(e, startedEnvironment));
          };
      buildExecutionSession.setStatus(BuildExecutionStatus.BUILD_ENV_WAITING);

      startedEnvironment.monitorInitialization(onComplete, onError);
    } catch (Throwable e) {
      waitToCompleteFuture.completeExceptionally(new BuildProcessException(e, startedEnvironment));
    }
    return waitToCompleteFuture;
  }
  public void receiveResponse(UaResponseMessage response) {
    ResponseHeader header = response.getResponseHeader();
    UInteger requestHandle = header.getRequestHandle();

    CompletableFuture<UaResponseMessage> future = pending.remove(requestHandle);

    if (future != null) {
      if (header.getServiceResult().isGood()) {
        future.complete(response);
      } else {
        ServiceFault serviceFault;

        if (response instanceof ServiceFault) {
          serviceFault = (ServiceFault) response;
        } else {
          serviceFault = new ServiceFault(header);
        }

        future.completeExceptionally(new UaServiceFaultException(serviceFault));
      }

      Timeout timeout = timeouts.remove(requestHandle);
      if (timeout != null) timeout.cancel();
    } else {
      logger.debug(
          "Received {} for unknown requestHandle: {}",
          response.getClass().getSimpleName(),
          requestHandle);
    }
  }
  private void connect(boolean initialAttempt, CompletableFuture<ClientSecureChannel> future) {
    UaTcpStackClient.bootstrap(client, Optional.empty())
        .whenCompleteAsync(
            (sc, ex) -> {
              if (sc != null) {
                logger.debug(
                    "Channel bootstrap succeeded: localAddress={}, remoteAddress={}",
                    sc.getChannel().localAddress(),
                    sc.getChannel().remoteAddress());

                future.complete(sc);
              } else {
                logger.debug("Channel bootstrap failed: {}", ex.getMessage(), ex);

                StatusCode statusCode =
                    UaException.extract(ex).map(UaException::getStatusCode).orElse(StatusCode.BAD);

                boolean secureChannelError =
                    statusCode.getValue() == StatusCodes.Bad_SecureChannelIdInvalid
                        || statusCode.getValue() == StatusCodes.Bad_SecurityChecksFailed
                        || statusCode.getValue() == StatusCodes.Bad_TcpSecureChannelUnknown;

                if (initialAttempt && secureChannelError) {
                  // Try again if bootstrapping failed because we couldn't re-open the previous
                  // channel.
                  logger.debug("Previous channel unusable, retrying...");

                  connect(false, future);
                } else {
                  future.completeExceptionally(ex);
                }
              }
            });
  }
  /**
   * Connects to an RS world.
   *
   * @param world the world, as a string. For RS3, use a numeric string. For oldschool, use
   *     "oldschool[world]".
   * @return A future for the connection task.
   */
  public CompletableFuture<Void> connect(String world) {
    if (connectionTask != null && !connectionTask.isDone()) {
      connectionTask.cancel(true);
    }

    disconnect();

    String host;
    int port;
    if (world.startsWith("oldschool")) {
      host = world + HOST_SUFFIX;
      port = OLDSCHOOL_PORT;
    } else {
      host = "world" + world + HOST_SUFFIX;
      port = RS3_PORT;
    }

    connectionTask = new CompletableFuture<>();
    CompletableFuture.runAsync(
        () -> {
          try {
            synchronized (this) {
              socket = new Socket(host, port);
            }
            connectionTask.complete(null);
          } catch (IOException e) {
            connectionTask.completeExceptionally(e);
          }
        });
    return connectionTask;
  }
  @Test
  public void testAddOnChatUserJoinedChannelListener() throws Exception {
    when(chatPrefs.getChatColorMode()).thenReturn(chatColorMode.get());
    when(chatPrefs.getUserToColor()).thenReturn(userToColorProperty);

    CompletableFuture<String> channelNameFuture = new CompletableFuture<>();
    CompletableFuture<ChatUser> userFuture = new CompletableFuture<>();
    instance.addOnChatUserJoinedChannelListener(
        (channelName, chatUser) -> {
          channelNameFuture.complete(channelName);
          userFuture.complete(chatUser);
        });

    instance.onEvent(new JoinEvent(pircBotX, defaultChannel, userHostMask, user1));

    assertThat(channelNameFuture.get(TIMEOUT, TIMEOUT_UNIT), is(DEFAULT_CHANNEL_NAME));
    assertThat(userFuture.get(TIMEOUT, TIMEOUT_UNIT), is(chatUser1));
  }
Exemple #18
0
  @Test
  public void testLongParam() throws IllegalAccessException, InstantiationException {
    PrimitiveUser2 a = new PrimitiveUser2();

    CompletableFuture<String> blocker = new CompletableFuture<>();
    final CompletableFuture<Object> res = a.longTest(blocker, 10000000000L);
    blocker.complete("x");
    assertEquals(":10000000000:x", res.join());
  }
 /** Completes the given operation response. */
 @SuppressWarnings("unchecked")
 private void completeResponse(OperationResponse response, CompletableFuture future) {
   if (response.status() == Response.Status.OK) {
     future.complete(response.result());
     resetMembers();
   } else {
     future.completeExceptionally(response.error().createException());
   }
 }
 public static <T> CompletableFuture<T> toCompletableFuture(final Supplier<T> supplier) {
   CompletableFuture<T> future = new CompletableFuture<T>();
   try {
     future.complete(supplier.get());
   } catch (RuntimeException e) {
     future.completeExceptionally(e);
   }
   return future;
 }
  @Test
  public void testAddOnChatUserQuitListener() throws Exception {
    CompletableFuture<Boolean> quitFuture = new CompletableFuture<>();
    instance.addOnChatUserQuitListener((username) -> quitFuture.complete(true));

    instance.onEvent(new QuitEvent(pircBotX, daoSnapshot, userHostMask, userSnapshot, "reason"));

    assertThat(quitFuture.get(TIMEOUT, TIMEOUT_UNIT), is(true));
  }
Exemple #22
0
 private CompletableFuture<Void> requestFiltersAsync(HttpRequestImpl r) {
   CompletableFuture<Void> cf = new CompletableFuture<>();
   try {
     requestFilters(r);
     cf.complete(null);
   } catch (Throwable e) {
     cf.completeExceptionally(e);
   }
   return cf;
 }
 public static CompletableFuture<Void> toCompletableFuture(final Runnable task) {
   CompletableFuture<Void> future = new CompletableFuture<>();
   try {
     task.run();
     future.complete(null);
   } catch (RuntimeException e) {
     future.completeExceptionally(e);
   }
   return future;
 }
Exemple #24
0
 // Fail 3 times then succeed
 CompletableFuture<Boolean> connect() {
   CompletableFuture<Boolean> future = new CompletableFuture<>();
   executor.submit(
       () -> {
         if (failures.getAndIncrement() < 3)
           future.completeExceptionally(new RuntimeException());
         else future.complete(true);
       });
   return future;
 }
Exemple #25
0
 @SuppressWarnings("unchecked")
 static <T> void checkCompletedExceptionally(CompletableFuture<T> cf, boolean cancelled)
     throws Exception {
   try {
     cf.join();
     fail("Excepted exception to be thrown");
   } catch (CompletionException x) {
     if (cancelled) fail();
     else pass();
   } catch (CancellationException x) {
     if (cancelled) pass();
     else fail();
   }
   try {
     cf.getNow(null);
     fail("Excepted exception to be thrown");
   } catch (CompletionException x) {
     if (cancelled) fail();
     else pass();
   } catch (CancellationException x) {
     if (cancelled) pass();
     else fail();
   }
   try {
     cf.get();
     fail("Excepted exception to be thrown");
   } catch (CancellationException x) {
     if (cancelled) pass();
     else fail();
   } catch (ExecutionException x) {
     if (cancelled) check(x.getCause() instanceof CancellationException);
     else pass();
   }
   try {
     cf.get(0L, SECONDS);
     fail("Excepted exception to be thrown");
   } catch (CancellationException x) {
     if (cancelled) pass();
     else fail();
   } catch (ExecutionException x) {
     if (cancelled) check(x.getCause() instanceof CancellationException);
     else pass();
   }
   check(cf.isDone(), "Expected isDone to be true, got:" + cf);
   check(
       cf.isCancelled() == cancelled,
       "Expected isCancelled: " + cancelled + ", got:" + cf.isCancelled());
   check(
       cf.cancel(true) == cancelled, "Expected cancel: " + cancelled + ", got:" + cf.cancel(true));
   check(cf.toString().contains("[Completed exceptionally]")); // ## TODO: 'E'xceptionally
   check(cf.complete((T) new Object()) == false, "Expected complete() to fail");
   check(
       cf.completeExceptionally(new Throwable()) == false,
       "Expected completeExceptionally() to fail, already completed");
 }
 public CompletableFuture<T> toCompletableFuture() {
   CompletableFuture<T> f = new CompletableFuture<>();
   AtomicInteger count = new AtomicInteger(0);
   this.onComplete(
       c -> {
         if (!count.compareAndSet(0, 1)) return;
         if (c.exceptionally) f.completeExceptionally(c.exception);
         else f.complete((T) c.result);
       });
   return f;
 }
  @Test
  public void testAddOnChatUserLeftChannelListener() throws Exception {
    CompletableFuture<String> usernameFuture = new CompletableFuture<>();
    CompletableFuture<String> channelNameFuture = new CompletableFuture<>();
    instance.addOnChatUserLeftChannelListener(
        (username, channelName) -> {
          usernameFuture.complete(username);
          channelNameFuture.complete(channelName);
        });

    when(channelSnapshot.getName()).thenReturn(DEFAULT_CHANNEL_NAME);
    when(userSnapshot.getNick()).thenReturn(chatUser1.getUsername());

    String reason = "Part reason";
    instance.onEvent(
        new PartEvent(pircBotX, daoSnapshot, channelSnapshot, userHostMask, userSnapshot, reason));

    assertThat(channelNameFuture.get(TIMEOUT, TIMEOUT_UNIT), is(DEFAULT_CHANNEL_NAME));
    assertThat(usernameFuture.get(TIMEOUT, TIMEOUT_UNIT), is(chatUser1.getUsername()));
  }
Exemple #28
0
  @Override
  public CompletableFuture<Void> close() {
    CompletableFuture<Void> future = new CompletableFuture<>();

    Context context = getContext();
    CompletableFuture[] futures = new CompletableFuture[connections.size()];
    int i = 0;
    for (LocalConnection connection : connections) {
      futures[i++] = connection.close();
    }
    CompletableFuture.allOf(futures).thenRunAsync(() -> future.complete(null), context.executor());
    return future;
  }
 /** Close this {@link Publisher}. This will also close the underlying {@link Pubsub} client. */
 @Override
 public void close() {
   // TODO (dano): fail outstanding futures
   scheduler.shutdownNow();
   try {
     scheduler.awaitTermination(30, SECONDS);
   } catch (InterruptedException e) {
     Thread.currentThread().interrupt();
   }
   pubsub.close();
   closeFuture.complete(null);
   listener.publisherClosed(Publisher.this);
 }
  @Override
  public CompletableFuture<UaStackClient> connect() {
    CompletableFuture<UaStackClient> future = new CompletableFuture<>();

    channelManager
        .getChannel()
        .whenComplete(
            (ch, ex) -> {
              if (ch != null) future.complete(this);
              else future.completeExceptionally(ex);
            });

    return future;
  }