Exemple #1
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");
 }
  @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();
  }
  /** This is slower but does not use any internal APIs. */
  private static Raster convertInvertedYCCKToCMYK_bySamples(Raster ycckRaster) {
    buildYCCtoRGBtable();
    int w = ycckRaster.getWidth(), h = ycckRaster.getHeight();

    try {
      CompletableFuture<int[]> cfY =
          CompletableFuture.supplyAsync(() -> ycckRaster.getSamples(0, 0, w, h, 0, (int[]) null));
      CompletableFuture<int[]> cfCb =
          CompletableFuture.supplyAsync(() -> ycckRaster.getSamples(0, 0, w, h, 1, (int[]) null));
      CompletableFuture<int[]> cfCr =
          CompletableFuture.supplyAsync(() -> ycckRaster.getSamples(0, 0, w, h, 2, (int[]) null));
      CompletableFuture<int[]> cfK =
          CompletableFuture.supplyAsync(() -> ycckRaster.getSamples(0, 0, w, h, 3, (int[]) null));
      int[] cmyk = new int[w * h];
      int[] ycckY = cfY.get();
      int[] ycckCb = cfCb.get();
      int[] ycckCr = cfCr.get();
      int[] ycckK = cfK.get();

      // Split the cmyk array into bands and process each band in parallel.
      // for (int i=0;i<cmyk.length;i++) {
      RangeStream.range(0, cmyk.length)
          .parallel()
          .forEach(
              (lo, hi) -> {
                for (int i = lo; i < hi; i++) {
                  int y = 255 - ycckY[i];
                  int cb = 255 - ycckCb[i];
                  int cr = 255 - ycckCr[i];
                  int cmykC, cmykM, cmykY;
                  // Range-limiting is essential due to noise introduced by DCT losses.
                  cmykC = MAXJSAMPLE - (y + Cr_r_tab[cr]); // red
                  cmykM =
                      MAXJSAMPLE
                          - (y
                              + // green
                              (Cb_g_tab[cb] + Cr_g_tab[cr] >> SCALEBITS));
                  cmykY = MAXJSAMPLE - (y + Cb_b_tab[cb]); // blue
                  // K passes through unchanged
                  cmyk[i] =
                      (cmykC < 0 ? 0 : (cmykC > 255) ? 255 : cmykC) << 24
                          | (cmykM < 0 ? 0 : (cmykM > 255) ? 255 : cmykM) << 16
                          | (cmykY < 0 ? 0 : (cmykY > 255) ? 255 : cmykY) << 8
                          | 255 - ycckK[i];
                }
              });

      Raster cmykRaster =
          Raster.createPackedRaster(
              new DataBufferInt(cmyk, cmyk.length),
              w,
              h,
              w,
              new int[] {0xff000000, 0xff0000, 0xff00, 0xff},
              null);
      return cmykRaster;
    } catch (InterruptedException | ExecutionException ex) {
      throw new InternalError(ex);
    }
  }
  @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 #5
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 static BufferedImage createImageFromRGB(Raster rgbRaster, ICC_Profile rgbProfile) {
    if (rgbProfile != null) {
      return createImageFromICCProfile(rgbRaster, rgbProfile);
    } else {
      BufferedImage image;
      int w = rgbRaster.getWidth();
      int h = rgbRaster.getHeight();

      try {
        CompletableFuture<int[]> cfR =
            CompletableFuture.supplyAsync(() -> rgbRaster.getSamples(0, 0, w, h, 0, (int[]) null));
        CompletableFuture<int[]> cfG =
            CompletableFuture.supplyAsync(() -> rgbRaster.getSamples(0, 0, w, h, 1, (int[]) null));
        CompletableFuture<int[]> cfB =
            CompletableFuture.supplyAsync(() -> rgbRaster.getSamples(0, 0, w, h, 2, (int[]) null));
        int[] rgb = new int[w * h];
        int[] R = cfR.get();
        int[] G = cfG.get();
        int[] B = cfB.get();

        // Split the rgb array into bands and process each band in parallel.
        // for (int i=0;i<rgb.length;i++) {
        RangeStream.range(0, rgb.length)
            .parallel()
            .forEach(
                (lo, hi) -> {
                  for (int i = lo; i < hi; i++) {
                    rgb[i] = 0xff << 24 | R[i] << 16 | G[i] << 8 | B[i];
                  }
                });

        WritableRaster packedRaster =
            Raster.createPackedRaster(
                new DataBufferInt(rgb, rgb.length),
                w,
                h,
                w,
                new int[] {0xff0000, 0xff00, 0xff, 0xff000000},
                null);
        ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
        ColorModel cm =
            ColorModel
                .getRGBdefault(); // new DirectColorModel(cs, 32, 0xff0000, 0xff00, 0xff,
                                  // 0x0ff000000, false, DataBuffer.TYPE_INT);
        Hashtable<Object, Object> properties = new Hashtable<Object, Object>();
        return new BufferedImage(cm, packedRaster, cm.isAlphaPremultiplied(), properties);
      } catch (ExecutionException | InterruptedException e) {
        throw new InternalError(e);
      }
    }
  }
  /**
   * Creates a buffered image from a raster in the RGBW color space.
   *
   * <p>As seen from a comment made by 'phelps' at
   * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4799903
   *
   * @param rgbwRaster A raster with inverted CMYK values (=RGBW).
   * @param cmykProfile An ICC_Profile. If this parameter is null, a default profile is used.
   * @return a BufferedImage in the RGB color space.
   */
  public static BufferedImage createImageFromInvertedCMYK(
      Raster rgbwRaster, ICC_Profile cmykProfile) {
    int w = rgbwRaster.getWidth();
    int h = rgbwRaster.getHeight();

    try {
      CompletableFuture<int[]> cfR =
          CompletableFuture.supplyAsync(() -> rgbwRaster.getSamples(0, 0, w, h, 0, (int[]) null));
      CompletableFuture<int[]> cfG =
          CompletableFuture.supplyAsync(() -> rgbwRaster.getSamples(0, 0, w, h, 1, (int[]) null));
      CompletableFuture<int[]> cfB =
          CompletableFuture.supplyAsync(() -> rgbwRaster.getSamples(0, 0, w, h, 2, (int[]) null));
      CompletableFuture<int[]> cfW =
          CompletableFuture.supplyAsync(() -> rgbwRaster.getSamples(0, 0, w, h, 3, (int[]) null));
      int[] rgb = new int[w * h];
      int[] R = cfR.get();
      int[] G = cfG.get();
      int[] B = cfB.get();
      int[] W = cfW.get();

      // Split the rgb array into bands and process each band in parallel.
      // for (int i=0;i<rgb.length;i++) {
      RangeStream.range(0, rgb.length)
          .parallel()
          .forEach(
              (lo, hi) -> {
                for (int i = lo; i < hi; i++) {
                  rgb[i] =
                      (255 - W[i]) << 24
                          | (255 - R[i]) << 16
                          | (255 - G[i]) << 8
                          | (255 - B[i]) << 0;
                }
              });

      Raster packedRaster =
          Raster.createPackedRaster(
              new DataBufferInt(rgb, rgb.length),
              w,
              h,
              w,
              new int[] {0xff0000, 0xff00, 0xff, 0xff000000},
              null);
      return createImageFromCMYK(packedRaster, cmykProfile);
    } catch (ExecutionException | InterruptedException e) {
      throw new InternalError(e);
    }
  }
  @Before
  public void setUp() throws Exception {
    final InputStream stream = getSettingsInputStream();
    final Settings settings = Settings.read(stream);
    final CompletableFuture<Void> serverReadyFuture = new CompletableFuture<>();

    thread =
        new Thread(
            () -> {
              try {
                final Settings overridenSettings = overrideSettings(settings);
                new GremlinServer(overridenSettings, serverReadyFuture).run();
              } catch (InterruptedException ie) {
                logger.info("Shutting down Gremlin Server");
              } catch (Exception ex) {
                logger.error("Could not start Gremlin Server for integration tests", ex);
              }
            });
    thread.start();

    // make sure gremlin server gets off the ground - longer than 30 seconds means that this didn't
    // work somehow
    try {
      serverReadyFuture.get(30000, TimeUnit.MILLISECONDS);
    } catch (Exception ex) {
      logger.error("Server did not start in the expected time or was otherwise interrupted.", ex);
      return;
    }

    host = System.getProperty("host", "localhost");
    port = System.getProperty("port", "8182");
  }
  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];
  }
 /**
  * Returns the aggregate result of the calculations, blocking until it is available.
  *
  * @return the aggregate result of the calculations, blocking until it is available
  */
 public T result() {
   try {
     return future.get();
   } catch (InterruptedException | ExecutionException e) {
     throw new RuntimeException("Exception getting result", e);
   }
 }
  @Test
  public void testOnConnected() throws Exception {
    String password = "******";

    when(userService.getPassword()).thenReturn(password);
    instance.connect();

    botStartedFuture.get(TIMEOUT, TIMEOUT_UNIT);

    CountDownLatch latch = new CountDownLatch(1);
    doAnswer(
            invocation -> {
              latch.countDown();
              return null;
            })
        .when(outputIrc)
        .joinChannel(DEFAULT_CHANNEL_NAME);

    mockTaskService();
    instance.connectionStateProperty().set(ConnectionState.CONNECTED);

    String md5Password = Hashing.md5().hashString(password, StandardCharsets.UTF_8).toString();
    verify(outputIrc).message("NICKSERV", String.format("IDENTIFY %s", md5Password));

    assertTrue("Channel has not been joined within timeout", latch.await(TIMEOUT, TIMEOUT_UNIT));
  }
  public static void main(String[] args)
      throws InterruptedException, ExecutionException, TimeoutException {
    ExecutorService executor = Executors.newFixedThreadPool(5);
    CompletableFuture<String> task1 =
        CompletableFuture.supplyAsync(
            () -> {
              try {
                System.out.println(Thread.currentThread().getName() + ": firstTask");
                TimeUnit.SECONDS.sleep(2);
              } catch (Exception e) {
              }
              return "1";
            });
    CompletableFuture<String> task2 =
        CompletableFuture.supplyAsync(
            () -> {
              try {
                System.out.println(Thread.currentThread().getName() + ": secondTask");
                TimeUnit.SECONDS.sleep(3);
              } catch (Exception e) {
              }
              return "2";
            });
    // a new thread from the supplied executor will execute third task
    task1.acceptEitherAsync(
        task2,
        (x) -> {
          System.out.println(Thread.currentThread().getName() + ": thirdTask " + x);
        },
        executor);

    TimeUnit.SECONDS.sleep(5);
    System.out.println(Thread.currentThread().getName() + ": " + task1.get());
    executor.shutdown();
  }
Exemple #13
0
  private static TestResponse callTestService(TestService.AsyncIface client) throws Exception {
    final CompletableFuture<TestResponse> result = new CompletableFuture<>();

    client.process(
        request(),
        new AsyncMethodCallback<TestService.AsyncClient.process_call>() {
          @Override
          public void onComplete(TestService.AsyncClient.process_call response) {
            extract(response);
          }

          @Override
          public void onError(Exception e) {
            logger.error("RPC call failed ", e);
          }

          private void extract(TestService.AsyncClient.process_call response) {
            try {
              result.complete(response.getResult());
            } catch (Exception e) {
              logger.error("Failed to extract response from: " + response, e);
            }
          }
        });

    return result.get(5, TimeUnit.SECONDS);
  }
  @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));
  }
  @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));
  }
  @Test
  public void service_client_e2e() throws Exception {
    if (Tools.isNullOrEmpty(connectionString)) {
      throw new IllegalArgumentException(
          "Environment variable is not set: " + connectionStringEnvVarName);
    }

    // Arrange

    // We remove and recreate the device for a clean start
    RegistryManager registryManager = RegistryManager.createFromConnectionString(connectionString);

    try {
      registryManager.removeDevice(deviceId);
    } catch (IOException | IotHubException e) {
    }

    Device deviceAdded = Device.createFromId(deviceId);
    registryManager.addDevice(deviceAdded);

    Device deviceGetBefore = registryManager.getDevice(deviceId);

    // Act

    // Create service client
    ServiceClient serviceClient = ServiceClient.createFromConnectionString(connectionString);
    CompletableFuture<Void> futureOpen = serviceClient.openAsync();
    futureOpen.get();

    CompletableFuture<Void> completableFuture = serviceClient.sendAsync(deviceId, message);
    completableFuture.get();

    Device deviceGetAfter = registryManager.getDevice(deviceId);

    CompletableFuture<Void> futureClose = serviceClient.closeAsync();
    futureClose.get();

    registryManager.removeDevice(deviceId);

    // Assert
    assertEquals(deviceGetBefore.getDeviceId(), deviceGetAfter.getDeviceId());
    assertEquals(0, deviceGetBefore.getCloudToDeviceMessageCount());
    assertEquals(1, deviceGetAfter.getCloudToDeviceMessageCount());
  }
  /**
   * This blocking function attempts to send the message passed in as a parameter. This {@link
   * AmqpsIotHubConnection} handles all calls to this method.
   *
   * <p>Only the first call to this method will result in an attempt to send. Until the message has
   * been sent, all other calls to this method will block. Once a message has been sent and this
   * method notified that it has been sent, this method will be invoked again if was previously
   * another call to send a message.
   *
   * <p>If a message has been passed down to the handler for sending but the message isn't sent
   * after a default constant number of seconds, the {@link AmqpsTransport} will set an ERROR status
   * code on the message and it will placed back onto the queue.
   *
   * @throws IOException If {@link AmqpsIotHubConnectionBaseHandler} has not been initialized.
   */
  protected synchronized void send(Tuple<CompletableFuture<Boolean>, byte[], Object> message)
      throws IOException {
    if (this.state == ReactorState.CLOSED) {
      throw new IllegalStateException(
          "The AMQPS IotHub Connection is currently closed. Call open() before attempting to send a message.");
    }
    if (message != null) {
      if (this.inProgressMessageMap.size() >= this.maxQueueSize * 0.9) {
        message.V1.completeExceptionally(
            new Throwable("Insufficient link credit to send message."));
      } else {
        try {
          // Use the content and ID fields of the input message to have the handler create and send
          // the message
          CompletableFuture<Integer> deliveryFuture =
              amqpsHandler.createBinaryMessage((byte[]) message.V2, message.V3);

          // Wait for a period of time before rejecting the message
          new Thread(
                  () -> {
                    try {
                      Thread.sleep(DEFAULT_DELIVERY_WAIT_TIME_SECONDS * 1000);
                      deliveryFuture.completeExceptionally(
                          new Throwable("Default timeout exceeded before this message was sent."));
                    } catch (InterruptedException e) {
                      e.printStackTrace();
                    }
                  })
              .start();

          // Wait for the deliveryFuture to be completed, providing the delivery hash code.
          // When this future completes, the message has been SENT
          Integer deliveryHash = deliveryFuture.get();
          inProgressMessageMap.put(deliveryHash, message);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        // The message was unable to be sent, exceptionally complete that future causing the message
        // to be put back on the queue.
        catch (ExecutionException e) {
          message.V1.completeExceptionally(e.getCause());
          this.fail(e.getCause());
        }
        // There was some other problem sending, exceptionally complete that future causing the
        // message to be put back on the queue.
        catch (Exception e) {
          if (message != null) {
            message.V1.completeExceptionally(e);
          }
          this.fail(e);
        }
      }
    } else {
      throw new IOException("Cannot send an unitialized message.");
    }
  }
  @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()));
  }
  @Test
  public void testFailedThrowsCorrectException() throws InterruptedException {
    IOException e = new IOException();
    CompletableFuture<Void> f = CompletableFutures.failed(e);

    try {
      f.get();
      fail("expected exception");
    } catch (ExecutionException ex) {
      assertSame(e, ex.getCause());
    }
  }
Exemple #20
0
 private static <T> T complete(CompletableFuture<T> future) {
   try {
     return future.get(DATABASE_OPERATION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
   } catch (InterruptedException e) {
     Thread.currentThread().interrupt();
     throw new ConsistentMapException.Interrupted();
   } catch (TimeoutException e) {
     throw new ConsistentMapException.Timeout();
   } catch (ExecutionException e) {
     throw new ConsistentMapException(e.getCause());
   }
 }
  @Test
  public void shouldUnwrapUserFutureAndReturnIt() throws Exception {
    // given
    final RetryExecutor executor = new AsyncRetryExecutor(schedulerMock);
    given(serviceMock.safeAsync()).willReturn(CompletableFuture.completedFuture("42"));

    // when
    final CompletableFuture<String> future =
        executor.getFutureWithRetry(ctx -> serviceMock.safeAsync());

    // then
    assertThat(future.get()).isEqualTo("42");
  }
  @Test
  public void testNewThrowsCorrectInterruptedException() throws Throwable {
    InterruptedException e = new InterruptedException();

    ThrowingSupplier<Void, ?> s = mock(ThrowingSupplier.class);
    when(s.get()).thenThrow(e);

    CompletableFuture<Void> cf = CompletableFutures.newCompletableFuture(s);
    try {
      cf.get();
      fail("expected exception");
    } catch (ExecutionException ex) {
      assertSame(e, ex.getCause());
    }
  }
Exemple #23
0
  public JsPromise then(Consumer onSuccessCallBack) {
    // future.thenAccept(onSuccessCallBack);
    onSuccess = onSuccessCallBack;
    executor.submit(
        () -> {
          try {
            onSuccessCallBack.accept(future.get());
          } catch (InterruptedException e) {
            throw new RuntimeException(e);
          } catch (ExecutionException e) {
            onError.accept(e);
          }
        });

    return this;
  }
  @Test
  public void testSendActionInBackground() throws Exception {
    instance.connect();

    String action = "test action";

    when(taskService.submitTask(any())).thenReturn(CompletableFuture.completedFuture(action));
    mockTaskService();

    CompletableFuture<String> future =
        instance.sendActionInBackground(DEFAULT_CHANNEL_NAME, action);

    verify(pircBotX).sendIRC();
    verify(outputIrc).action(DEFAULT_CHANNEL_NAME, action);
    assertThat(future.get(TIMEOUT, TIMEOUT_UNIT), is(action));
  }
  @Test
  @SuppressWarnings("unchecked")
  public void testSendMessageInBackground() throws Exception {
    instance.connect();

    String message = "test message";

    mockTaskService();

    CompletableFuture<String> future =
        instance.sendMessageInBackground(DEFAULT_CHANNEL_NAME, message);

    assertThat(future.get(TIMEOUT, TIMEOUT_UNIT), is(message));
    verify(pircBotX).sendIRC();
    verify(outputIrc).message(DEFAULT_CHANNEL_NAME, message);
  }
 private <T> T complete(CompletableFuture<T> future) {
   try {
     return future.get(operationTimeoutMillis, TimeUnit.MILLISECONDS);
   } catch (InterruptedException e) {
     Thread.currentThread().interrupt();
     throw new StorageException.Interrupted();
   } catch (TimeoutException e) {
     throw new StorageException.Timeout();
   } catch (ExecutionException e) {
     if (e.getCause() instanceof StorageException) {
       throw (StorageException) e.getCause();
     } else {
       throw new StorageException(e.getCause());
     }
   }
 }
  @Test
  public void shouldSucceedAfterFewAsynchronousRetries() throws Exception {
    // given
    final RetryExecutor executor = new AsyncRetryExecutor(schedulerMock);
    given(serviceMock.safeAsync())
        .willReturn(
            failedAsync(new SocketException("First")),
            failedAsync(new IOException("Second")),
            CompletableFuture.completedFuture("42"));

    // when
    final CompletableFuture<String> future =
        executor.getFutureWithRetry(ctx -> serviceMock.safeAsync());

    // then
    assertThat(future.get()).isEqualTo("42");
  }
  public static void main(String[] args) throws Exception {
    CreateFunctionalMaps.main(args);
    FunctionalMap.ReadOnlyMap<String, String> readOnlyMap = CreateFunctionalMaps.ro;
    FunctionalMap.WriteOnlyMap<String, String> writeOnlyMap = CreateFunctionalMaps.wo;
    FunctionalMap.ReadWriteMap<String, String> readWriteMap = CreateFunctionalMaps.rw;

    CompletableFuture<Void> f0 =
        writeOnlyMap.eval(
            "key",
            "value1",
            (v, writeView) ->
                writeView.set(
                    v, new MetaParam.MetaEntryVersion<>(new EntryVersion.NumericEntryVersion(1))));
    CompletableFuture<Boolean> f1 =
        f0.thenCompose(
            x ->
                readWriteMap.eval(
                    "key",
                    "value2",
                    (v, readWriteView) -> {
                      // .class does not give generics, so use a helper type() method
                      Class<MetaParam.MetaEntryVersion<Long>> clazz =
                          MetaParam.MetaEntryVersion.type();
                      Optional<MetaParam.MetaEntryVersion<Long>> metaParam =
                          readWriteView.findMetaParam(clazz);
                      return metaParam
                          .map(
                              metaVersion -> {
                                if (metaVersion
                                        .get()
                                        .compareTo(new EntryVersion.NumericEntryVersion(1))
                                    == EQUAL) {
                                  readWriteView.set(
                                      "uno",
                                      new MetaParam.MetaEntryVersion<>(
                                          new EntryVersion.NumericEntryVersion(200)));
                                  return true; // version matches
                                }
                                return false; // version does not match
                              })
                          .orElse(false); // version not present
                    }));

    System.out.println(f1.get());
  }
  @NotNull
  private Response sendBlockingStunRequest(Request request) {
    try {
      CompletableFuture<Response> responseFuture = new CompletableFuture<>();
      stunStack.sendRequest(
          request, serverAddress, localAddress, blockingResponseCollector(responseFuture));
      Response response = responseFuture.get();

      if (response.isErrorResponse()) {
        logger.warn(
            "STUN error: {}",
            ((ErrorCodeAttribute) response.getAttribute(ERROR_CODE)).getReasonPhrase());
      }
      return response;
    } catch (IOException | InterruptedException | ExecutionException e) {
      throw new RuntimeException(e);
    }
  }
  @Test
  public void testAddOnChatDisconnectedListener() throws Exception {
    CompletableFuture<Void> onChatDisconnectedFuture = new CompletableFuture<>();
    instance
        .connectionStateProperty()
        .addListener(
            (observable, oldValue, newValue) -> {
              switch (newValue) {
                case DISCONNECTED:
                  onChatDisconnectedFuture.complete(null);
                  break;
              }
            });

    instance.onEvent(new DisconnectEvent(pircBotX, daoSnapshot, null));

    onChatDisconnectedFuture.get(TIMEOUT, TIMEOUT_UNIT);
  }