Java Code Examples for io.vertx.core.Future#setHandler()

The following examples show how to use io.vertx.core.Future#setHandler() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AsyncUtils.java    From nubes with Apache License 2.0 6 votes vote down vote up
static <T, U> Future<Void> chainOnSuccess(Handler<AsyncResult<T>> globalHandler, Future<U> future, List<Handler<Future<Void>>> list) {
  List<Future<Void>> futures = new ArrayList<>(list.size());
  int i = 0;
  Future<Void> firstFuture = Future.future();
  for (Handler<Future<Void>> handler : list) {
    Future<Void> fut = i == 0 ? firstFuture : futures.get(i - 1);
    futures.add(chainOnSuccess(globalHandler, fut, handler));
    i++;
  }
  future.setHandler(res -> {
    if (res.failed()) {
      globalHandler.handle(Future.failedFuture(res.cause()));
    } else {
      list.get(0).handle(firstFuture);
    }
  });
  return futures.get(futures.size() - 1);
}
 
Example 2
Source File: JdbcApplicationSettingsTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void getAccountByIdShouldReturnAccountWithAllFieldsPopulated(TestContext context) {
    // when
    final Future<Account> future = jdbcApplicationSettings.getAccountById("accountId", timeout);

    // then
    final Async async = context.async();
    future.setHandler(context.asyncAssertSuccess(account -> {
        assertThat(account).isEqualTo(Account.builder()
                .id("accountId")
                .priceGranularity("med")
                .bannerCacheTtl(100)
                .videoCacheTtl(100)
                .analyticsSamplingFactor(1)
                .eventsEnabled(true)
                .enforceCcpa(true)
                .gdpr(AccountGdprConfig.builder()
                        .enabled(true)
                        .build())
                .truncateTargetAttr(0)
                .build());
        async.complete();
    }));
}
 
Example 3
Source File: AsyncUtils.java    From nubes with Apache License 2.0 6 votes vote down vote up
static <T> void chainHandlers(Handler<AsyncResult<T>> global, List<Handler<Future<T>>> handlers) {
  if (handlers == null || handlers.isEmpty()) {
    global.handle(Future.succeededFuture());
    return;
  }
  int nbHandlers = handlers.size();
  Future<T> firstFuture = Future.future();
  if (nbHandlers == 1) {
    firstFuture.setHandler(global);
    handlers.get(0).handle(firstFuture);
    return;
  }
  List<Future<T>> futures = new ArrayList<>(handlers.size());
  futures.add(firstFuture);
  int i = 0;
  for (Handler<Future<T>> handler : handlers) {
    if (i > 0) {
      Future<T> fut = futures.get(i - 1);
      futures.add(chainOnSuccess(global, fut, handler));
    }
    i++;
  }
  futures.get(futures.size() - 1).setHandler(global);
  handlers.get(0).handle(firstFuture);
}
 
Example 4
Source File: BasicHttpClientTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void requestShouldFailIfHttpResponseTimedOut(TestContext context) {
    // given
    final Vertx vertx = Vertx.vertx();
    final BasicHttpClient httpClient = new BasicHttpClient(vertx, vertx.createHttpClient());
    final int serverPort = 8888;

    startServer(serverPort, 0L, 2000L);

    // when
    final Async async = context.async();
    final Future<?> future = httpClient.get("http://localhost:" + serverPort, 1000L);
    future.setHandler(ar -> async.complete());
    async.await();

    // then
    assertThat(future.failed()).isTrue();
    assertThat(future.cause())
            .isInstanceOf(TimeoutException.class)
            .hasMessage("Timeout period of 1000ms has been exceeded");
}
 
Example 5
Source File: BasicHttpClientTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void requestShouldFailIfHttpRequestTimedOut(TestContext context) {
    // given
    final Vertx vertx = Vertx.vertx();
    final BasicHttpClient httpClient = new BasicHttpClient(vertx, vertx.createHttpClient());
    final int serverPort = 7777;

    startServer(serverPort, 2000L, 0L);

    // when
    final Async async = context.async();
    final Future<?> future = httpClient.get("http://localhost:" + serverPort, 1000L);
    future.setHandler(ar -> async.complete());
    async.await();

    // then
    assertThat(future.failed()).isTrue();
    assertThat(future.cause())
            .isInstanceOf(TimeoutException.class)
            .hasMessageStartingWith("Timeout period of 1000ms has been exceeded");
}
 
Example 6
Source File: CircuitBreakerSecuredJdbcClientTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void executeQueryShouldReportMetricsOnCircuitClosed(TestContext context) {
    // given
    givenExecuteQueryReturning(asList(
            Future.failedFuture(new RuntimeException("exception1")),
            Future.succeededFuture()));

    // when
    final Async async = context.async();
    jdbcClient.executeQuery("query", emptyList(), identity(), timeout) // 1 call
            .recover(ignored -> jdbcClient.executeQuery("query", emptyList(), identity(), timeout)) // 2 call
            .setHandler(ignored -> vertx.setTimer(201L, id -> async.complete()));
    async.await();

    final Future<?> future = jdbcClient.executeQuery("query", emptyList(),
            resultSet -> resultSet.getResults().get(0).getString(0), timeout); // 3 call

    // then
    future.setHandler(context.asyncAssertSuccess(result ->
            verify(metrics).updateDatabaseCircuitBreakerMetric(eq(false))));
}
 
Example 7
Source File: QOTDLambdaTest.java    From aws-lambda-native-vertx with MIT License 6 votes vote down vote up
@Test
public void shouldGetAQOTD(TestContext should) {
  final Async test = should.async();

  Future<Buffer> fut = fn.call(rule.vertx(), MultiMap.caseInsensitiveMultiMap(), null);

  fut.setHandler(call -> {
    if (call.failed()) {
      should.fail(call.cause());
    } else {
      should.assertNotNull(call.result());
      should.assertTrue(call.result().length() > 0);
      test.complete();
    }
  });
}
 
Example 8
Source File: DataLoaderTest.java    From vertx-dataloader with Apache License 2.0 6 votes vote down vote up
@Test
public void should_Build_a_really_really_simple_data_loader() {
    AtomicBoolean success = new AtomicBoolean();
    DataLoader<Integer, Integer> identityLoader = new DataLoader<>(keys ->
        CompositeFuture.join(keys.stream()
                .map(Future::succeededFuture)
                .collect(Collectors.toCollection(ArrayList::new))));

    Future<Integer> future1 = identityLoader.load(1);
    future1.setHandler(rh -> {
        assertThat(rh.result(), equalTo(1));
        success.set(rh.succeeded());
    });
    identityLoader.dispatch();
    await().untilAtomic(success, is(true));
}
 
Example 9
Source File: JdbcApplicationSettingsTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void getStoredResponseShouldReturnErrorIfResultContainsLessColumnsThanExpected(TestContext context) {
    // given
    jdbcApplicationSettings = new JdbcApplicationSettings(jdbcClient(), jacksonMapper, SELECT_QUERY, SELECT_QUERY,
            SELECT_ONE_COLUMN_RESPONSE_QUERY);

    // when
    final Future<StoredResponseDataResult> storedResponseDataResultFuture =
            jdbcApplicationSettings.getStoredResponses(new HashSet<>(asList("1", "2", "3")), timeout);

    // then
    final Async async = context.async();
    storedResponseDataResultFuture.setHandler(context.asyncAssertSuccess(storedResponseDataResult -> {
        assertThat(storedResponseDataResult).isEqualTo(StoredResponseDataResult.of(emptyMap(),
                singletonList("Result set column number is less than expected")));
        async.complete();
    }));
}
 
Example 10
Source File: JdbcApplicationSettingsTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void getStoredDataShouldReturnResultWithErrorIfNoStoredRequestFound(TestContext context) {
    // when
    final Future<StoredDataResult> storedRequestResultFuture =
            jdbcApplicationSettings.getStoredData(new HashSet<>(asList("1", "3")), emptySet(), timeout);

    // then
    final Async async = context.async();
    storedRequestResultFuture.setHandler(context.asyncAssertSuccess(storedRequestResult -> {
        assertThat(storedRequestResult).isEqualTo(StoredDataResult.of(singletonMap("1", "value1"), emptyMap(),
                singletonList("No stored request found for id: 3")));
        async.complete();
    }));
}
 
Example 11
Source File: JdbcApplicationSettingsTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void getAdUnitConfigByIdShouldFailIfConfigNotFound(TestContext context) {
    // when
    final Future<String> future = jdbcApplicationSettings.getAdUnitConfigById("non-existing", timeout);

    // then
    final Async async = context.async();
    future.setHandler(context.asyncAssertFailure(exception -> {
        assertThat(exception).isInstanceOf(PreBidException.class)
                .hasMessage("AdUnitConfig not found: non-existing");
        async.complete();
    }));
}
 
Example 12
Source File: CheckoutServiceImpl.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
@Override
public void checkout(String userId, Handler<AsyncResult<CheckoutResult>> resultHandler) {
  if (userId == null) {
    resultHandler.handle(Future.failedFuture(new IllegalStateException("Invalid user")));
    return;
  }
  Future<ShoppingCart> cartFuture = getCurrentCart(userId);
  Future<CheckoutResult> orderFuture = cartFuture.compose(cart ->
    checkAvailableInventory(cart).compose(checkResult -> {
      if (checkResult.getBoolean("res")) {
        double totalPrice = calculateTotalPrice(cart);
        // create order instance
        Order order = new Order().setBuyerId(userId)
          .setPayId("TEST") // reserved field
          .setProducts(cart.getProductItems())
          .setTotalPrice(totalPrice);
        // set id and then send order, wait for reply
        return retrieveCounter("order")
          .compose(id -> sendOrderAwaitResult(order.setOrderId(id)))
          .compose(result -> saveCheckoutEvent(userId).map(v -> result));
      } else {
        // has insufficient inventory, fail
        return Future.succeededFuture(new CheckoutResult()
          .setMessage(checkResult.getString("message")));
      }
    })
  );

  orderFuture.setHandler(resultHandler);
}
 
Example 13
Source File: JdbcApplicationSettingsTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void getAmpStoredDataShouldReturnResultWithErrorIfNoStoredRequestFound(TestContext context) {
    // when
    final Future<StoredDataResult> storedRequestResultFuture =
            jdbcApplicationSettings.getAmpStoredData(new HashSet<>(asList("1", "3")), emptySet(), timeout);

    // then
    final Async async = context.async();
    storedRequestResultFuture.setHandler(context.asyncAssertSuccess(storedRequestResult -> {
        assertThat(storedRequestResult).isEqualTo(StoredDataResult.of(singletonMap("1", "value1"), emptyMap(),
                singletonList("No stored request found for id: 3")));
        async.complete();
    }));
}
 
Example 14
Source File: JdbcApplicationSettingsTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void getStoredDataUnionSelectByIdShouldReturnStoredRequests(TestContext context) {
    // given
    jdbcApplicationSettings = new JdbcApplicationSettings(jdbcClient(), jacksonMapper, SELECT_UNION_QUERY,
            SELECT_UNION_QUERY, SELECT_RESPONSE_QUERY);

    // when
    final Future<StoredDataResult> storedRequestResultFuture =
            jdbcApplicationSettings.getStoredData(new HashSet<>(asList("1", "2", "3")),
                    new HashSet<>(asList("4", "5", "6")), timeout);

    // then
    final Async async = context.async();
    storedRequestResultFuture.setHandler(context.asyncAssertSuccess(storedRequestResult -> {
        final Map<String, String> expectedRequests = new HashMap<>();
        expectedRequests.put("1", "value1");
        expectedRequests.put("2", "value2");
        expectedRequests.put("3", "value3");
        final Map<String, String> expectedImps = new HashMap<>();
        expectedImps.put("4", "value4");
        expectedImps.put("5", "value5");
        expectedImps.put("6", "value6");
        assertThat(storedRequestResult).isEqualTo(
                StoredDataResult.of(expectedRequests, expectedImps, emptyList()));
        async.complete();
    }));
}
 
Example 15
Source File: JdbcApplicationSettingsTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void getVideoStoredDataShouldReturnStoredRequests(TestContext context) {
    // given
    jdbcApplicationSettings = new JdbcApplicationSettings(jdbcClient(), jacksonMapper, SELECT_UNION_QUERY,
            SELECT_UNION_QUERY, SELECT_RESPONSE_QUERY);

    // when
    final Future<StoredDataResult> storedRequestResultFuture =
            jdbcApplicationSettings.getVideoStoredData(new HashSet<>(asList("1", "2", "3")),
                    new HashSet<>(asList("4", "5", "6")), timeout);

    // then
    final Async async = context.async();
    storedRequestResultFuture.setHandler(context.asyncAssertSuccess(storedRequestResult -> {
        final Map<String, String> expectedRequests = new HashMap<>();
        expectedRequests.put("1", "value1");
        expectedRequests.put("2", "value2");
        expectedRequests.put("3", "value3");
        final Map<String, String> expectedImps = new HashMap<>();
        expectedImps.put("4", "value4");
        expectedImps.put("5", "value5");
        expectedImps.put("6", "value6");
        assertThat(storedRequestResult).isEqualTo(
                StoredDataResult.of(expectedRequests, expectedImps, emptyList()));
        async.complete();
    }));
}
 
Example 16
Source File: CircuitBreakerSecuredHttpClientTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
private Future<HttpClientResponse> doRequest(String url, TestContext context) {
    final Future<HttpClientResponse> future = httpClient.request(HttpMethod.GET, url, null, null, 0L);

    final Async async = context.async();
    future.setHandler(ar -> async.complete());
    async.await();

    return future;
}
 
Example 17
Source File: VaadinVerticle.java    From vertx-vaadin with MIT License 5 votes vote down vote up
private Future<Router> startupHttpServer(VertxVaadin vertxVaadin) {
    String mountPoint = vertxVaadin.config().mountPoint();
    HttpServerOptions serverOptions = new HttpServerOptions().setCompressionSupported(true);

    Router router = Router.router(vertx);
    router.mountSubRouter(mountPoint, vertxVaadin.router());

    httpServer = vertx.createHttpServer(serverOptions).requestHandler(router);
    Promise<HttpServer> promise = Promise.promise();
    Future<HttpServer> future = promise.future();
    future.setHandler(event -> {
        if (event.succeeded()) {
            log.info("Started vaadin verticle " + getClass().getName() + " on port " + event.result().actualPort());
        } else {
            log.error("Cannot start http server", event.cause());
        }
    });

    httpPort().setHandler(event -> {
        if (event.succeeded()) {
            httpServer.listen(event.result(), promise);
        } else {
            promise.fail(event.cause());
        }
    });

    return future.map(router);
}
 
Example 18
Source File: EchoLambdaTest.java    From aws-lambda-native-vertx with MIT License 5 votes vote down vote up
@Test
public void shouldGetAnEchoMessage(TestContext should) {
  final Async test = should.async();

  Future<Buffer> fut = fn.call(rule.vertx(), MultiMap.caseInsensitiveMultiMap(), Buffer.buffer("Hello World"));

  fut.setHandler(call -> {
    if (call.failed()) {
      should.fail(call.cause());
    } else {
      should.assertEquals(Buffer.buffer("Hello World"), call.result());
      test.complete();
    }
  });
}
 
Example 19
Source File: VertxCompletableFutureTest.java    From vertx-completable-future with Apache License 2.0 4 votes vote down vote up
@Test
public void testToVertxFuture(TestContext tc) {
  Async async1 = tc.async();
  Async async2 = tc.async();
  Async async3 = tc.async();
  Async async4 = tc.async();
  Async async5 = tc.async();

  VertxCompletableFuture<Integer> future = new VertxCompletableFuture<>(vertx);
  Future<Integer> success = future.thenApply(i -> i + 1).thenApplyAsync(i -> i + 1).toFuture();
  Future<Void> success2 = future.thenApply(i -> i + 1).thenApplyAsync(i -> i + 1).thenRunAsync(() -> {
    // Do nothing
  }).toFuture();
  success.setHandler(ar -> {
    assertThat(ar.failed(), is(false));
    assertThat(ar.succeeded(), is(true));
    assertThat(ar.result(), is(44));
    async1.complete();
  });
  success2.setHandler(ar -> {
    assertThat(ar.failed(), is(false));
    assertThat(ar.succeeded(), is(true));
    assertThat(ar.result(), is(nullValue()));
    async2.complete();
  });

  VertxCompletableFuture<Integer> failingFuture = new VertxCompletableFuture<>(vertx);
  Future<Integer> failure = failingFuture.thenApply(i -> i + 1).thenApplyAsync(i -> i + i + 1).toFuture();
  failure.setHandler(ar -> {
    assertThat(ar.failed(), is(true));
    assertThat(ar.succeeded(), is(false));
    assertThat(ar.result(), is(nullValue()));
    assertThat(ar.cause(), is(notNullValue()));
    assertThat(ar.cause().getMessage(), containsString("My bad"));
    async3.complete();
  });

  // test that `VertxCompletableFuture` receives callbacks from the Vert.x Future
  VertxCompletableFuture<Integer> awaitedFuture = new VertxCompletableFuture<>(vertx);

  awaitedFuture.handle((val, except) -> {
    assertThat(val, is(42));
    assertThat(except, is(nullValue()));
    async4.complete();

    return (Void) null;
  });

  VertxCompletableFuture<Integer> awaitedFailingFuture = new VertxCompletableFuture<>(vertx);

  awaitedFailingFuture.handle((val, except) -> {
    assertThat(val, is(nullValue()));
    assertThat(except, is(notNullValue()));
    assertThat(except.getMessage(), containsString("My bad again"));
    async5.complete();

    return (Void) null;
  });

  future.complete(42);
  failingFuture.completeExceptionally(new Exception("My bad"));
  awaitedFuture.toFuture().complete(42);
  awaitedFailingFuture.completeExceptionally(new Exception("My bad again"));
}
 
Example 20
Source File: VxApiApplication.java    From VX-API-Gateway with MIT License 4 votes vote down vote up
/**
 * 创建https服务器
 * 
 * @param createHttp
 */
public void createHttpsServer(Handler<AsyncResult<Void>> createHttps) {
	this.httpsRouter = Router.router(vertx);
	httpsRouter.route().handler(this::filterBlackIP);
	httpsRouter.route().handler(CookieHandler.create());
	SessionStore sessionStore = null;
	if (vertx.isClustered()) {
		sessionStore = ClusteredSessionStore.create(vertx);
	} else {
		sessionStore = LocalSessionStore.create(vertx);
	}
	SessionHandler sessionHandler = SessionHandler.create(sessionStore);
	sessionHandler.setSessionCookieName(appOption.getSessionCookieName());
	sessionHandler.setSessionTimeout(appOption.getSessionTimeOut());
	httpsRouter.route().handler(sessionHandler);
	// 跨域处理
	if (corsOptions != null) {
		CorsHandler corsHandler = CorsHandler.create(corsOptions.getAllowedOrigin());
		if (corsOptions.getAllowedHeaders() != null) {
			corsHandler.allowedHeaders(corsOptions.getAllowedHeaders());
		}
		corsHandler.allowCredentials(corsOptions.isAllowCredentials());
		if (corsOptions.getExposedHeaders() != null) {
			corsHandler.exposedHeaders(corsOptions.getExposedHeaders());
		}
		if (corsOptions.getAllowedMethods() != null) {
			corsHandler.allowedMethods(corsOptions.getAllowedMethods());
		}
		corsHandler.maxAgeSeconds(corsOptions.getMaxAgeSeconds());
		httpsRouter.route().handler(corsHandler);
	}
	// 创建https服务器
	serverOptions.setSsl(true);
	VxApiCertOptions certOptions = serverOptions.getCertOptions();
	if (certOptions.getCertType().equalsIgnoreCase("pem")) {
		serverOptions
				.setPemKeyCertOptions(new PemKeyCertOptions().setCertPath(certOptions.getCertPath()).setKeyPath(certOptions.getCertKey()));
	} else if (certOptions.getCertType().equalsIgnoreCase("pfx")) {
		serverOptions.setPfxKeyCertOptions(new PfxOptions().setPath(certOptions.getCertPath()).setPassword(certOptions.getCertKey()));
	} else {
		LOG.error("创建https服务器-->失败:无效的证书类型,只支持pem/pfx格式的证书");
		createHttps.handle(Future.failedFuture("创建https服务器-->失败:无效的证书类型,只支持pem/pfx格式的证书"));
		return;
	}
	Future<Boolean> createFuture = Future.future();
	vertx.fileSystem().exists(certOptions.getCertPath(), createFuture);
	createFuture.setHandler(check -> {
		if (check.succeeded()) {
			if (check.result()) {
				// 404页面
				httpsRouter.route().order(999999).handler(rct -> {
					if (LOG.isDebugEnabled()) {
						LOG.debug(
								"用户: " + rct.request().remoteAddress().host() + "请求的了不存的路径: " + rct.request().method() + ":" + rct.request().path());
					}
					HttpServerResponse response = rct.response();
					if (appOption.getNotFoundContentType() != null) {
						response.putHeader("Content-Type", appOption.getNotFoundContentType());
					}
					response.end(appOption.getNotFoundResult());
				});
				// 如果在linux系统开启epoll
				if (vertx.isNativeTransportEnabled()) {
					serverOptions.setTcpFastOpen(true).setTcpCork(true).setTcpQuickAck(true).setReusePort(true);
				}
				vertx.createHttpServer(serverOptions).requestHandler(httpsRouter::accept).listen(serverOptions.getHttpsPort(), res -> {
					if (res.succeeded()) {
						System.out.println(appOption.getAppName() + " Running on port " + serverOptions.getHttpsPort() + " by HTTPS");
						createHttps.handle(Future.succeededFuture());
					} else {
						System.out.println("create HTTPS Server failed : " + res.cause());
						createHttps.handle(Future.failedFuture(res.cause()));
					}
				});
			} else {
				LOG.error("执行创建https服务器-->失败:无效的证书或者错误的路径:如果证书存放在conf/cert中,路径可以从cert/开始,示例:cert/XXX.XXX");
				createHttps.handle(Future.failedFuture("无效的证书或者错误的路径"));
			}
		} else {
			LOG.error("执行创建https服务器-->失败:无效的证书或者错误的路径:如果证书存放在conf/cert中,路径可以从cert/开始,示例:cert/XXX.XXX", check.cause());
			createHttps.handle(Future.failedFuture(check.cause()));
		}
	});
}