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

The following examples show how to use io.vertx.core.Future#future() . 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: HttpKafkaConsumer.java    From client-examples with Apache License 2.0 6 votes vote down vote up
private Future<Void> deleteConsumer() {
    Future<Void> fut = Future.future();

    this.client.delete(this.consumer.getBaseUri())
        .putHeader(HttpHeaderNames.CONTENT_TYPE.toString(), "application/vnd.kafka.v2+json")
        .as(BodyCodec.jsonObject())
        .send(ar -> {
            if (ar.succeeded()) {
                HttpResponse<JsonObject> response = ar.result();
                if (response.statusCode() == HttpResponseStatus.NO_CONTENT.code()) {
                    log.info("Consumer {} deleted", this.consumer.getInstanceId());
                    fut.complete();
                } else {
                    fut.fail(new RuntimeException("Got HTTP status code " + response.statusCode()));
                } 
            } else {
                fut.fail(ar.cause());
            }
        });
    return fut;
}
 
Example 2
Source File: BaseMicroserviceVerticle.java    From vertx-blueprint-microservice with Apache License 2.0 6 votes vote down vote up
/**
 * Publish a service with record.
 *
 * @param record service record
 * @return async result
 */
private Future<Void> publish(Record record) {
  if (discovery == null) {
    try {
      start();
    } catch (Exception e) {
      throw new IllegalStateException("Cannot create discovery service");
    }
  }

  Future<Void> future = Future.future();
  // publish the service
  discovery.publish(record, ar -> {
    if (ar.succeeded()) {
      registeredRecords.add(record);
      logger.info("Service <" + ar.result().getName() + "> published");
      future.complete();
    } else {
      future.fail(ar.cause());
    }
  });

  return future;
}
 
Example 3
Source File: MyFirstVerticle.java    From introduction-to-eclipse-vertx with Apache License 2.0 6 votes vote down vote up
private Future<Article> queryOne(SQLConnection connection, String id) {
    Future<Article> future = Future.future();
    String sql = "SELECT * FROM articles WHERE id = ?";
    connection.queryWithParams(sql, new JsonArray().add(Integer.valueOf(id)), result -> {
        connection.close();
        future.handle(
            result.map(rs -> {
                List<JsonObject> rows = rs.getRows();
                if (rows.size() == 0) {
                    throw new NoSuchElementException("No article with id " + id);
                } else {
                    JsonObject row = rows.get(0);
                    return new Article(row);
                }
            })
        );
    });
    return future;
}
 
Example 4
Source File: WarmupVerticle.java    From quarantyne with Apache License 2.0 6 votes vote down vote up
private Future<Void> warmup(String host, int port) {
  Future<Void> f = Future.future();
  httpClient
      .request(HttpMethod.GET, port, host, "/")
      .exceptionHandler(ex -> {
        log.error("error while warming up to {}, reason: {}. Retrying...", host, ex.getMessage());
      }).handler(r -> {
    if (isSuccess(r.statusCode())) {
      log.info("warmup of {}:{} complete", host, port);
      f.complete();
    } else {
      log.error("warmup to {}:{} failed", host, port);
      f.fail("warmup failed");
    }
  }).end();
  return f;
}
 
Example 5
Source File: LogService.java    From gushici with GNU General Public License v3.0 6 votes vote down vote up
private void getHistoryFromRedis(Message<JsonObject> message) {
    Future<String> total = Future.future(f -> redisClient.hget(Key.REDIS_CLICKS_TOTAL_HASH, "total", f));
    // 7天的历史点击量
    LocalDate localDate = LocalDate.now();
    List<String> keys = new ArrayList<>();
    for (int i = 0; i < 7; i++) {
        keys.add(localDate.toString());
        localDate = localDate.minusDays(1);
    }
    Future<JsonArray> history = Future.future(f -> redisClient.hmget(Key.REDIS_CLICKS_HISTORY_HASH, keys, f));
    CompositeFuture.all(Arrays.asList(total, history)).setHandler(v -> {
        if (v.succeeded()) {
            JsonObject result = new JsonObject();
            result.put("总点击量", total.result());
            result.put("最近七天点击量", history.result());
            message.reply(result);
        } else {
            log.error("日志获取异常", v.cause());
            message.fail(500, v.cause().getMessage());
        }
    });
}
 
Example 6
Source File: StoreVerticle.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
private Future<Void> deployRestVerticle(StoreCRUDService service) {
  Future<String> future = Future.future();
  vertx.deployVerticle(new RestStoreAPIVerticle(service),
    new DeploymentOptions().setConfig(config()),
    future.completer());
  return future.map(r -> null);
}
 
Example 7
Source File: DashboardVerticle.java    From vertx-microservices-workshop with Apache License 2.0 5 votes vote down vote up
private Future<Void> retrieveAuditService() {
  return Future.future(future -> {
    HttpEndpoint.getWebClient(discovery, new JsonObject().put("name", "audit"), client -> {
      this.client = client.result();
      future.handle(client.map((Void)null));
    });
  });
}
 
Example 8
Source File: JWTAuthenticatorVerticle.java    From vertx-mqtt-broker with Apache License 2.0 5 votes vote down vote up
private Future<String> login(HttpClient httpClient,
                             String identityURL,
                             String app_key,
                             String app_secret,
                             String username,
                             String password) {
    Future<String> ret = Future.future();

    HttpClientRequest loginReq = httpClient.postAbs(identityURL, resp -> {
        resp.exceptionHandler(e -> {
            logger.fatal(e.getMessage(), e);
            ret.fail(e);
        });
        resp.bodyHandler(totalBuffer -> {
            String jsonResponse = totalBuffer.toString("UTF-8");
            logger.info(jsonResponse);

            if(resp.statusCode() == 200) {
                JsonObject j = new JsonObject(jsonResponse);
                String access_token = j.getString("access_token");
                ret.complete(access_token);
            } else {
                logger.fatal(resp.statusMessage());
                ret.fail(resp.statusMessage());
            }
        });
    });

    String data = "grant_type=password"
            + "&username=" + username
            + "&password=" + password
            + "&client_id=" + app_key
            + "&client_secret=" + app_secret
            + "";

    loginReq.putHeader("Content-Type", "application/x-www-form-urlencoded");
    loginReq.end(data, "UTF-8");

    return ret;
}
 
Example 9
Source File: VertxHttp11ClientReconnectTest.java    From feign-vertx with Apache License 2.0 5 votes vote down vote up
/**
 * Close the server connection
 * @return future for close completion
 */
public Future<Void> closeServer() {
  // Close server
  Future<Void> fut = Future.future();
  httpServer.close(fut.completer());
  return fut;
}
 
Example 10
Source File: CheckoutServiceImpl.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
private Future<ShoppingCart> getCurrentCart(String userId) {
  Future<ShoppingCartService> future = Future.future();
  EventBusService.getProxy(discovery, ShoppingCartService.class, future.completer());
  return future.compose(service -> {
    Future<ShoppingCart> cartFuture = Future.future();
    service.getShoppingCart(userId, cartFuture.completer());
    return cartFuture.compose(c -> {
      if (c == null || c.isEmpty())
        return Future.failedFuture(new IllegalStateException("Invalid shopping cart"));
      else
        return Future.succeededFuture(c);
    });
  });
}
 
Example 11
Source File: CheckoutServiceImpl.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
/**
 * Save checkout cart event for current user.
 *
 * @param userId user id
 * @return async result
 */
private Future<Void> saveCheckoutEvent(String userId) {
  Future<ShoppingCartService> future = Future.future();
  EventBusService.getProxy(discovery, ShoppingCartService.class, future.completer());
  return future.compose(service -> {
    Future<Void> resFuture = Future.future();
    CartEvent event = CartEvent.createCheckoutEvent(userId);
    service.addCartEvent(event, resFuture.completer());
    return resFuture;
  });
}
 
Example 12
Source File: RawOrderDispatcher.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
/**
 * Apply inventory decrease changes according to the order.
 *
 * @param order order data object
 * @return async result
 */
private Future<Void> applyInventoryChanges(Order order) {
  Future<Void> future = Future.future();
  // get REST endpoint
  Future<HttpClient> clientFuture = Future.future();
  HttpEndpoint.getClient(discovery,
    new JsonObject().put("name", "inventory-rest-api"),
    clientFuture.completer());
  // modify the inventory changes via REST API
  return clientFuture.compose(client -> {
    List<Future> futures = order.getProducts()
      .stream()
      .map(item -> {
        Future<Void> resultFuture = Future.future();
        String url = String.format("/%s/decrease?n=%d", item.getProductId(), item.getAmount());
        client.put(url, response -> {
          if (response.statusCode() == 200) {
            resultFuture.complete(); // need to check result?
          } else {
            resultFuture.fail(response.statusMessage());
          }
        })
          .exceptionHandler(resultFuture::fail)
          .end();
        return resultFuture;
      })
      .collect(Collectors.toList());
    // composite async results, all must be complete
    CompositeFuture.all(futures).setHandler(ar -> {
      if (ar.succeeded()) {
        future.complete();
      } else {
        future.fail(ar.cause());
      }
      ServiceDiscovery.releaseServiceObject(discovery, client); // Release the resources.
    });
    return future;
  });
}
 
Example 13
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()));
		}
	});
}
 
Example 14
Source File: JdbcRepositoryWrapper.java    From vertx-blueprint-microservice with Apache License 2.0 4 votes vote down vote up
protected Future<SQLConnection> getConnection() {
  Future<SQLConnection> future = Future.future();
  client.getConnection(future.completer());
  return future;
}
 
Example 15
Source File: VxApiApplication.java    From VX-API-Gateway with MIT License 4 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {
	try {
		if (LOG.isDebugEnabled()) {
			LOG.debug("加载应用配置信息...");
		}
		thisVertxName = System.getProperty("thisVertxName", "VX-API");
		VxApiApplicationDTO app = VxApiApplicationDTO.fromJson(config().getJsonObject("appConfig"));
		if (app.getWebClientCustom() != null) {
			JsonObject custom = new JsonObject(app.getWebClientCustom());
			this.appOption = new VxApiApplicationOptions(app, custom);
		} else {
			this.appOption = new VxApiApplicationOptions(app);
		}
		appName = appOption.getAppName();
		this.serverOptions = appOption.getServerOptions();
		if (LOG.isDebugEnabled()) {
			LOG.debug("加载全局黑名单");
		}
		config().getJsonArray("blackIpSet").forEach(ip -> {
			if (ip instanceof String) {
				blackIpSet.add(ip.toString());
			}
		});
		if (LOG.isDebugEnabled()) {
			LOG.debug("加载跨域处理信息");
		}
		this.corsOptions = appOption.getCorsOptions();
		if (appOption == null) {
			LOG.error("创建应用程序-->失败:配置信息为空");
			startFuture.fail("创建应用程序失败:配置信息为空");
			return;
		} else {
			this.httpClient = vertx.createHttpClient(appOption);
			Future<Void> httpFuture = Future.future(future -> {
				if (serverOptions.isCreateHttp()) {
					createHttpServer(res -> {
						if (res.succeeded()) {
							if (LOG.isDebugEnabled()) {
								LOG.debug("实例化应用程序->创建HTTP服务器-->成功!");
							}
							future.complete();
						} else {
							LOG.error("实例化应用程序->创建HTTP服务器-->失败:" + res.cause());
							future.fail(res.cause());
						}
					});
				} else {
					future.complete();
				}
			});
			Future<Void> httpsFuture = Future.future(future -> {
				if (serverOptions.isCreateHttps()) {
					createHttpsServer(res -> {
						if (res.succeeded()) {
							if (LOG.isDebugEnabled()) {
								LOG.debug("实例化应用程序->创建HTTPS服务器-->成功!");
							}
							future.complete();
						} else {
							LOG.error("实例化应用程序->创建HTTPS服务器-->失败:" + res.cause());
							future.fail(res.cause());
						}
					});
				} else {
					future.complete();
				}
			});
			Future<Void> eventFutrue = Future.future(future -> {
				// 注册操作地址
				vertx.eventBus().consumer(thisVertxName + appOption.getAppName() + VxApiEventBusAddressConstant.APPLICATION_ADD_API_SUFFIX,
						this::addRoute);
				vertx.eventBus().consumer(thisVertxName + appOption.getAppName() + VxApiEventBusAddressConstant.APPLICATION_DEL_API_SUFFIX,
						this::delRoute);
				vertx.eventBus().consumer(VxApiEventBusAddressConstant.SYSTEM_PUBLISH_BLACK_IP_LIST, this::updateIpBlackList);
				future.complete();
			});
			CompositeFuture.all(httpFuture, httpsFuture, eventFutrue).setHandler(res -> {
				if (res.succeeded()) {
					LOG.info("实例化应用程序-->成功");
					startFuture.complete();
				} else {
					LOG.error("实例化应用程序-->失败:", res.cause());
					startFuture.fail(res.cause());
				}
			});
		}
	} catch (Exception e) {
		LOG.error("实例化应用程序-->失败:", e);
		startFuture.fail(e);
	}
}
 
Example 16
Source File: Kue.java    From vertx-kue with Apache License 2.0 4 votes vote down vote up
/**
 * Get queue work time in milliseconds.
 *
 * @return async result
 */
public Future<Long> getWorkTime() {
  Future<Long> future = Future.future();
  jobService.getWorkTime(future.completer());
  return future;
}
 
Example 17
Source File: HttpKafkaProducer.java    From client-examples with Apache License 2.0 4 votes vote down vote up
private Future <List<OffsetRecordSent>> send(String topic, Span span) {
    Future<List<OffsetRecordSent>> fut = Future.future();        

    JsonObject records = new JsonObject();
    records.put("records", new JsonArray().add(new JsonObject().put("value", "message-" + this.messagesSent++)));

    HttpRequest<Buffer> httpRequest = this.client.post(this.config.getEndpointPrefix() + "/topics/" + topic);

    Tracer tracer = GlobalTracer.get();
    tracer.inject(span.context(), Format.Builtin.HTTP_HEADERS, new TextMap() {
        @Override
        public Iterator<Map.Entry<String, String>> iterator() {
            throw new UnsupportedOperationException("TextMapInjectAdapter should only be used with Tracer.inject()");
        }

        @Override
        public void put(String key, String value) {
            httpRequest.putHeader(key, value);
        }
    });

    httpRequest
            .putHeader(HttpHeaderNames.CONTENT_LENGTH.toString(), String.valueOf(records.toBuffer().length()))
            .putHeader(HttpHeaderNames.CONTENT_TYPE.toString(), "application/vnd.kafka.json.v2+json")
            .as(BodyCodec.jsonObject())
            .sendJsonObject(records, ar -> {
                if (ar.succeeded()) {
                    HttpResponse<JsonObject> response = ar.result();
                    if (response.statusCode() == HttpResponseStatus.OK.code()) {
                        List<OffsetRecordSent> list = new ArrayList<>();
                        response.body().getJsonArray("offsets").forEach(obj -> {
                            JsonObject json = (JsonObject) obj;
                            list.add(new OffsetRecordSent(
                                json.getInteger("partition"),
                                json.getLong("offset"))
                                );
                        });
                        fut.complete(list);
                    } else {
                        fut.fail(new RuntimeException("Got HTTP status code " + response.statusCode()));
                    }
                } else {
                    fut.fail(ar.cause());
                }

                if (this.config.getMessageCount().isPresent() &&
                    this.messagesSent >= this.config.getMessageCount().get()) {
                        this.vertx.close(done -> System.exit(0));
                }
            });
    return fut;
}
 
Example 18
Source File: Kue.java    From vertx-kue with Apache License 2.0 4 votes vote down vote up
/**
 * Get cardinality of failed jobs.
 *
 * @param type job type; if null, then return global metrics.
 */
public Future<Long> failedCount(String type) {
  Future<Long> future = Future.future();
  jobService.failedCount(type, future.completer());
  return future;
}
 
Example 19
Source File: Kue.java    From vertx-kue with Apache License 2.0 2 votes vote down vote up
/**
 * Get cardinality by job type and state.
 *
 * @param type  job type
 * @param state job state
 * @return corresponding cardinality (Future)
 */
public Future<Long> cardByType(String type, JobState state) {
  Future<Long> future = Future.future();
  jobService.cardByType(type, state, future.completer());
  return future;
}
 
Example 20
Source File: Kue.java    From vertx-kue with Apache License 2.0 2 votes vote down vote up
/**
 * Get a list of job in certain state and type in range (from, to) with order.
 *
 * @return async result
 * @see JobService#jobRangeByType(String, String, long, long, String, Handler)
 */
public Future<List<Job>> jobRangeByType(String type, String state, long from, long to, String order) {
  Future<List<Job>> future = Future.future();
  jobService.jobRangeByType(type, state, from, to, order, future.completer());
  return future;
}