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

The following examples show how to use io.vertx.core.Future#fail() . 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: HttpServerService.java    From ethsigner with Apache License 2.0 6 votes vote down vote up
@Override
public void start(final Future<Void> startFuture) {
  httpServer = vertx.createHttpServer(serverOptions);
  try {
    httpServer
        .requestHandler(routes)
        .listen(
            result -> {
              if (result.succeeded()) {
                LOG.info("HTTP server service started on {}", httpServer.actualPort());
                startFuture.complete();
              } else {
                LOG.error("HTTP server service failed to listen", result.cause());
                startFuture.fail(result.cause());
              }
            });
  } catch (final Exception e) {
    startFuture.fail(e);
    throw e;
  }
}
 
Example 2
Source File: FixtureLoader.java    From nubes with Apache License 2.0 6 votes vote down vote up
private void instanciateFixtures(Future<Void> future) {
  List<String> fixturePackages = config.getFixturePackages();
  if (fixturePackages == null || fixturePackages.isEmpty()) {
    return;
  }
  for (String fixturePackage : fixturePackages) {
    if (fixturePackage == null)
      continue;

    Set<Class<? extends Fixture>> fixtureClasses = ReflectionProviderHelper.getAnnotationProcessor(config, fixturePackage).getSubClassOf(Fixture.class);
    for (Class<? extends Fixture> fixtureClass : fixtureClasses) {
      try {
        Fixture fixture = fixtureClass.newInstance();
        injectServicesIntoFixture(fixture);
        fixtures.add(fixture);
      } catch (Exception e) {
        future.fail(e);
        return;
      }
    }
  }
}
 
Example 3
Source File: DataLoader.java    From vertx-dataloader with Apache License 2.0 6 votes vote down vote up
/**
 * Requests to load the data with the specified key asynchronously, and returns a future of the resulting value.
 * <p>
 * If batching is enabled (the default), you'll have to call {@link DataLoader#dispatch()} at a later stage to
 * start batch execution. If you forget this call the future will never be completed (unless already completed,
 * and returned from cache).
 *
 * @param key the key to load
 * @return the future of the value
 */
public Future<V> load(K key) {
    Objects.requireNonNull(key, "Key cannot be null");
    Object cacheKey = getCacheKey(key);
    if (loaderOptions.cachingEnabled() && futureCache.containsKey(cacheKey)) {
        return futureCache.get(cacheKey);
    }

    Future<V> future = Future.future();
    if (loaderOptions.batchingEnabled()) {
        loaderQueue.put(key, future);
    } else {
        CompositeFuture compositeFuture = batchLoadFunction.load(Collections.singleton(key));
        if (compositeFuture.succeeded()) {
            future.complete(compositeFuture.result().resultAt(0));
        } else {
            future.fail(compositeFuture.cause());
        }
    }
    if (loaderOptions.cachingEnabled()) {
        futureCache.set(cacheKey, future);
    }
    return future;
}
 
Example 4
Source File: ShoppingCartServiceImpl.java    From vertx-blueprint-microservice with Apache License 2.0 6 votes vote down vote up
/**
 * Generate current shopping cart from a data stream including necessary product data.
 * Note: this is not an asynchronous method. `Future` only marks whether the process is successful.
 *
 * @param rawCart       raw shopping cart
 * @param productList product data stream
 * @return async result
 */
private Future<ShoppingCart> generateCurrentCartFromStream(ShoppingCart rawCart, List<Product> productList) {
  Future<ShoppingCart> future = Future.future();
  // check if any of the product is invalid
  if (productList.stream().anyMatch(Objects::isNull)) {
    future.fail("Error when retrieve products: empty");
    return future;
  }
  // construct the product items
  List<ProductTuple> currentItems = rawCart.getAmountMap().entrySet()
    .stream()
    .map(item -> new ProductTuple(getProductFromStream(productList, item.getKey()),
      item.getValue()))
    .filter(item -> item.getAmount() > 0)
    .collect(Collectors.toList());

  ShoppingCart cart = rawCart.setProductItems(currentItems);
  return Future.succeededFuture(cart);
}
 
Example 5
Source File: VertxCompletableFutureTest.java    From vertx-completable-future with Apache License 2.0 6 votes vote down vote up
@Test
public void testFromVertxFuture(TestContext tc) {
  Async async1 = tc.async();
  Async async2 = tc.async();

  Future<Integer> vertxFuture1 = Future.future();
  Future<Integer> vertxFuture2 = Future.future();
  VertxCompletableFuture.from(vertx, vertxFuture1).thenApply(i -> i + 1).whenComplete((res, err) -> {
    tc.assertNotNull(res);
    tc.assertNull(err);
    tc.assertEquals(43, res);
    async1.complete();
  });

  VertxCompletableFuture.from(vertx, vertxFuture2).thenApply(i -> i + 1).whenComplete((res, err) -> {
    tc.assertNotNull(err);
    tc.assertNull(res);
    tc.assertTrue(err.getMessage().contains("My bad"));
    async2.complete();
  });

  vertxFuture1.complete(42);
  vertxFuture2.fail(new Exception("My bad"));
}
 
Example 6
Source File: DataService.java    From gushici with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param categories 用户请求的类别 [img, shenghuo ,buyi]
 * @return 返回一个随机类别的 key (set)
 */
private Future<String> checkAndGetKey(JsonArray categories) {
    Future<String> result = Future.future();
    List<String> toRandom = keysInRedis.getKeys(categories);
    if (toRandom.size() >= 1) {
        result.complete(toRandom.get(random.nextInt(toRandom.size())));
    } else {
        result.fail(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 404, "没有结果,请检查API"));
    }
    return result;
}
 
Example 7
Source File: AsyncUtils.java    From nubes with Apache License 2.0 5 votes vote down vote up
static <T> Handler<AsyncResult<T>> onSuccessOnly(Future<Void> future, Handler<T> handler) {
  return res -> {
    if (res.failed()) {
      future.fail(res.cause());
      return;
    }
    handler.handle(res.result());
  };
}
 
Example 8
Source File: AsyncUtils.java    From nubes with Apache License 2.0 5 votes vote down vote up
static <T> Handler<AsyncResult<T>> ignoreResult(Future<Void> future) {
  return res -> {
    if (res.failed()) {
      future.fail(res.cause());
    } else {
      future.complete();
    }
  };
}
 
Example 9
Source File: AsyncUtils.java    From nubes with Apache License 2.0 5 votes vote down vote up
static <T> Handler<AsyncResult<T>> completeOrFail(Future<T> fut) {
  return res -> {
    if (res.failed()) {
      fut.fail(res.cause());
    } else {
      fut.complete(res.result());
    }
  };
}
 
Example 10
Source File: MyFirstVerticle.java    From my-vertx-first-app with Apache License 2.0 5 votes vote down vote up
private void completeStartup(AsyncResult<HttpServer> http, Future<Void> fut) {
  if (http.succeeded()) {
    fut.complete();
  } else {
    fut.fail(http.cause());
  }
}
 
Example 11
Source File: JavaCompulsiveTraderVerticle.java    From vertx-microservices-workshop with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Future<Void> future) {
  super.start();

  //TODO
  //----
  future.fail("no implemented yet...");
  // ----
}
 
Example 12
Source File: Job.java    From vertx-kue with Apache License 2.0 5 votes vote down vote up
private static <T, R> Handler<AsyncResult<T>> _completer(Future<R> future, R result) {
  return r -> {
    if (r.failed())
      future.fail(r.cause());
    else
      future.complete(result);
  };
}
 
Example 13
Source File: AuditVerticle.java    From microtrader with MIT License 5 votes vote down vote up
/**
 * A utility method returning a `Handler<SQLConnection>`
 *
 * @param future     the future.
 * @param connection the connection
 * @return the handler.
 */
private static Handler<AsyncResult<Void>> completer(Future<SQLConnection> future, SQLConnection connection) {
    return ar -> {
        if (ar.failed()) {
            future.fail(ar.cause());
        } else {
            future.complete(connection);
        }
    };
}
 
Example 14
Source File: ConvertUtil.java    From gushici with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param obj base64 加密后的图片
 * @return Buffer 流
 */
public static Future<Buffer> getImageFromBase64(String obj) {
    Future<Buffer> result = Future.future();
    if (obj == null) {
        result.fail(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 500, "图片读取失败"));
        return result;
    }

    Base64.Decoder decoder = Base64.getDecoder();
    byte[] bs;
    bs = decoder.decode(obj);
    Buffer buffer = Buffer.buffer(bs);
    result.complete(buffer);
    return result;
}
 
Example 15
Source File: DummyFailingVerticle.java    From kiqr with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {
    startFuture.fail("oops");
}
 
Example 16
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 17
Source File: VertxHttpRecorder.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Future<Void> startFuture) {
    final AtomicInteger remainingCount = new AtomicInteger(0);
    boolean httpServerEnabled = httpOptions != null && insecureRequests != HttpConfiguration.InsecureRequests.DISABLED;
    if (httpServerEnabled) {
        remainingCount.incrementAndGet();
    }
    if (httpsOptions != null) {
        remainingCount.incrementAndGet();
    }
    if (domainSocketOptions != null) {
        remainingCount.incrementAndGet();
    }

    if (remainingCount.get() == 0) {
        startFuture
                .fail(new IllegalArgumentException("Must configure at least one of http, https or unix domain socket"));
    }

    if (httpServerEnabled) {
        httpServer = vertx.createHttpServer(httpOptions);
        if (insecureRequests == HttpConfiguration.InsecureRequests.ENABLED) {
            httpServer.requestHandler(ACTUAL_ROOT);
        } else {
            httpServer.requestHandler(new Handler<HttpServerRequest>() {
                @Override
                public void handle(HttpServerRequest req) {
                    try {
                        String host = req.getHeader(HttpHeaderNames.HOST);
                        if (host == null) {
                            //TODO: solution for HTTP/1.0, but really there is not much we can do
                            req.response().setStatusCode(HttpResponseStatus.NOT_FOUND.code()).end();
                        } else {
                            int includedPort = host.indexOf(":");
                            if (includedPort != -1) {
                                host = host.substring(0, includedPort);
                            }
                            req.response()
                                    .setStatusCode(301)
                                    .putHeader("Location",
                                            "https://" + host + ":" + httpsOptions.getPort() + req.uri())
                                    .end();
                        }
                    } catch (Exception e) {
                        req.response().setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()).end();
                    }
                }
            });
        }
        setupTcpHttpServer(httpServer, httpOptions, false, startFuture, remainingCount);
    }

    if (domainSocketOptions != null) {
        domainSocketServer = vertx.createHttpServer(domainSocketOptions);
        domainSocketServer.requestHandler(ACTUAL_ROOT);
        setupUnixDomainSocketHttpServer(domainSocketServer, domainSocketOptions, startFuture, remainingCount);
    }

    if (httpsOptions != null) {
        httpsServer = vertx.createHttpServer(httpsOptions);
        httpsServer.requestHandler(ACTUAL_ROOT);
        setupTcpHttpServer(httpsServer, httpsOptions, true, startFuture, remainingCount);
    }
}
 
Example 18
Source File: TestVerticle.java    From nubes with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {
  HttpServerOptions options = new HttpServerOptions();
  options.setPort(PORT);
  options.setHost(HOST);
  HttpServer server = vertx.createHttpServer(options);
  JsonObject config = createTestConfig();
  config.put("templates", new JsonArray().add("mvel").add("hbs"));
  //config.put("relectionprovider", "reflections");
  nubes = new VertxNubes(vertx, config);
  nubes.registerService(DOG_SERVICE_NAME, dogService);
  nubes.registerService(SNOOPY_SERVICE_NAME, SNOOPY);
  nubes.registerServiceProxy(new ParrotServiceImpl());
  if (nubes.getService(DOG_SERVICE_NAME) == null) {
    startFuture.fail("Services should not be null");
    return;
  }
  List<Locale> locales = new ArrayList<>();
  locales.add(Locale.FRENCH);
  locales.add(Locale.US);
  locales.add(Locale.JAPANESE);
  locales.add(Locale.ENGLISH);
  nubes.setAvailableLocales(locales);
  nubes.setDefaultLocale(Locale.GERMAN);
  nubes.setAuthProvider(new MockAuthProvider());
  nubes.registerInterceptor("setDateBefore", context -> {
    context.response().headers().add("X-Date-Before", Long.toString(new Date().getTime()));
    context.next();
  });
  nubes.registerInterceptor("setDateAfter", context -> {
    context.response().headers().add("X-Date-After", Long.toString(new Date().getTime()));
    context.next();
  });
  nubes.registerTemplateEngine("hbs", HandlebarsTemplateEngine.create());
  nubes.bootstrap(onSuccessOnly(startFuture, router -> {
    server.requestHandler(router::accept);
    server.listen(res -> {
      if (res.failed()) {
        startFuture.fail(res.cause());
        return;
      }
      startFuture.complete();
    });
  }));
}