WikiDatabaseServiceImpl(JDBCClient dbClient, HashMap<SqlQuery, String> sqlQueries, Handler<AsyncResult<WikiDatabaseService>> readyHandler) { this.dbClient = dbClient; this.sqlQueries = sqlQueries; dbClient.getConnection(ar -> { if (ar.failed()) { LOGGER.error("Could not open a database connection", ar.cause()); readyHandler.handle(Future.failedFuture(ar.cause())); } else { SQLConnection connection = ar.result(); connection.execute(sqlQueries.get(SqlQuery.CREATE_PAGES_TABLE), create -> { connection.close(); if (create.failed()) { LOGGER.error("Database preparation error", create.cause()); readyHandler.handle(Future.failedFuture(create.cause())); } else { readyHandler.handle(Future.succeededFuture(this)); } }); } }); }
public MailService send(MailMessage message, Handler<AsyncResult<MailResult>> resultHandler) { if (closed) { resultHandler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed"))); return this; } JsonObject _json = new JsonObject(); _json.put("message", message == null ? null : message.toJson()); DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions(); _deliveryOptions.addHeader("action", "send"); _vertx.eventBus().<JsonObject>send(_address, _json, _deliveryOptions, res -> { if (res.failed()) { resultHandler.handle(Future.failedFuture(res.cause())); } else { resultHandler.handle(Future.succeededFuture(res.result().body() == null ? null : new MailResult(res.result().body()))); } }); return this; }
private void computeEvaluation(WebClient webClient, Handler<AsyncResult<Double>> resultHandler) { // We need to call the service for each company in which we own shares Flowable.fromIterable(portfolio.getShares().entrySet()) // For each, we retrieve the value .flatMapSingle(entry -> getValueForCompany(webClient, entry.getKey(), entry.getValue())) // We accumulate the results .toList() // And compute the sum .map(list -> list.stream().mapToDouble(x -> x).sum()) // We report the result or failure .subscribe((sum, err) -> { if (err != null) { System.out.println("Evaluation of the portfolio failed " + err.getMessage()); resultHandler.handle(Future.failedFuture(err)); } else { System.out.println("Evaluation of the portfolio succeeeded"); resultHandler.handle(Future.succeededFuture(sum)); } }); }
private void pageUpdateHandler(RoutingContext context) { String title = context.request().getParam("title"); Handler<AsyncResult<Void>> handler = reply -> { if (reply.succeeded()) { context.response().setStatusCode(303); context.response().putHeader("Location", "/wiki/" + title); context.response().end(); } else { context.fail(reply.cause()); } }; String markdown = context.request().getParam("markdown"); if ("yes".equals(context.request().getParam("newPage"))) { dbService.createPage(title, markdown, handler); } else { dbService.savePage(Integer.valueOf(context.request().getParam("id")), markdown, handler); } }
@Override public FdfsClient fileInfo(FdfsFileId fileId, Handler<AsyncResult<FdfsFileInfo>> handler) { getTracker().setHandler(tracker -> { if (tracker.succeeded()) { tracker.result().getUpdateStorage(fileId, storage -> { if (storage.succeeded()) { storage.result().fileInfo(fileId, fileInfo -> { handler.handle(fileInfo); }); } else { handler.handle(Future.failedFuture(storage.cause())); } }); } else { handler.handle(Future.failedFuture(tracker.cause())); } }); return this; }
public void sell(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler) { if (closed) { resultHandler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed"))); return; } JsonObject _json = new JsonObject(); _json.put("amount", amount); _json.put("quote", quote); DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions(); _deliveryOptions.addHeader("action", "sell"); _vertx.eventBus().<JsonObject>send(_address, _json, _deliveryOptions, res -> { if (res.failed()) { resultHandler.handle(Future.failedFuture(res.cause())); } else { resultHandler.handle(Future.succeededFuture(res.result().body() == null ? null : new Portfolio(res.result().body()))); } }); }
@Override public RpcClient connect(final String name, final String address, final JsonObject data, final Handler<AsyncResult<JsonObject>> handler) { return this.connect(RpcHelper.on(name, address), data, handler); }
@Override public WikiDatabaseService fetchAllPagesData(Handler<AsyncResult<List<JsonObject>>> resultHandler) { dbClient.query(sqlQueries.get(SqlQuery.ALL_PAGES_DATA), queryResult -> { if (queryResult.succeeded()) { resultHandler.handle(Future.succeededFuture(queryResult.result().getRows())); } else { LOGGER.error("Database query error", queryResult.cause()); resultHandler.handle(Future.failedFuture(queryResult.cause())); } }); return this; }
@Override public void buy(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler) { if (amount <= 0) { resultHandler.handle(Future.failedFuture("Cannot buy " + quote.getString("name") + " - the amount must be " + "greater than 0")); return; } if (quote.getInteger("shares") < amount) { resultHandler.handle(Future.failedFuture("Cannot buy " + amount + " - not enough " + "stocks on the market (" + quote.getInteger("shares") + ")")); return; } double price = amount * quote.getDouble("ask"); String name = quote.getString("name"); // 1) do we have enough money if (portfolio.getCash() >= price) { // Yes, buy it portfolio.setCash(portfolio.getCash() - price); int current = portfolio.getAmount(name); int newAmount = current + amount; portfolio.getShares().put(name, newAmount); sendActionOnTheEventBus("BUY", amount, quote, newAmount); resultHandler.handle(Future.succeededFuture(portfolio)); } else { resultHandler.handle(Future.failedFuture("Cannot buy " + amount + " of " + name + " - " + "not enough money, " + "need " + price + ", has " + portfolio.getCash())); } }
@Override public void handle(AsyncResult<T> ar) { if (ar.succeeded()) { complete(ar.result()); } else { completeExceptionally(ar.cause()); } }
@Override public HttpServer listen(int port, Handler<AsyncResult<HttpServer>> listenHandler) { localPort = port; listenHandler.handle(Future.succeededFuture(this)); processRequest(); return this; }
@Override public WikiDatabaseService savePage(int id, String markdown, Handler<AsyncResult<Void>> resultHandler) { JsonArray data = new JsonArray().add(markdown).add(id); dbClient.updateWithParams(sqlQueries.get(SqlQuery.SAVE_PAGE), data, res -> { if (res.succeeded()) { resultHandler.handle(Future.succeededFuture()); } else { LOGGER.error("Database query error", res.cause()); resultHandler.handle(Future.failedFuture(res.cause())); } }); return this; }
private void handleSimpleDbReply(RoutingContext context, AsyncResult<Void> reply) { if (reply.succeeded()) { context.response().setStatusCode(200); context.response().putHeader("Content-Type", "application/json"); context.response().end(new JsonObject().put("success", true).encode()); } else { context.response().setStatusCode(500); context.response().putHeader("Content-Type", "application/json"); context.response().end(new JsonObject() .put("success", false) .put("error", reply.cause().getMessage()).encode()); } }
/** * Performs an async <code>INSERT</code> statement for a given POJO and passes the primary key * to the <code>resultHandler</code>. When the value could not be inserted, the <code>resultHandler</code> * will fail. * @param object The POJO to be inserted * @param resultHandler the resultHandler. In case of Postgres or when PK length is greater 1 or PK is not of * type int or long, the resultHandler will be in error state. */ default void insertReturningPrimaryAsync(P object, Handler<AsyncResult<T>> resultHandler){ VertxDAOHelper.insertReturningPrimaryAsync(object,this, (query,fun)->{ client().insertReturning(query,res -> { if (res.failed()) { resultHandler.handle(Future.failedFuture(res.cause())); } else { resultHandler.handle(Future.succeededFuture(fun.apply(res.result()))); } }); return null; }); }
@Override public WikiDatabaseService fetchAllPagesData(Handler<AsyncResult<List<JsonObject>>> resultHandler) { dbClient.rxQuery(sqlQueries.get(SqlQuery.ALL_PAGES_DATA)) .map(ResultSet::getRows) .subscribe(RxHelper.toSubscriber(resultHandler)); return this; }
@Override public void authenticate(JsonObject authInfo, Handler<AsyncResult<JsonObject>> resultHandler) { fs.readFile(path, res -> { if(res.failed()){ resultHandler.handle(Future.failedFuture(res.cause())); return; } String username = authInfo.getString("username"); String password = authInfo.getString("password"); JsonArray json = res.result().toJsonArray(); Optional<JsonObject> oUser = json.stream() .map(o -> (JsonObject) o) .filter(o -> { JsonObject user = (JsonObject) o; return username.equals(user.getString("username")) && password.equals(user.getString("password")); }).collect(Collectors.toList()).stream().findFirst(); if(oUser.isPresent()){ resultHandler.handle(Future.succeededFuture(oUser.get())); }else{ resultHandler.handle(Future.failedFuture(new CredentialNotFoundException())); } }); }
public static void main(String[] args) throws InterruptedException { Vertx vertx = Vertx.vertx(); WebClient http = WebClient.create(vertx); App a =new App(vertx,http,"test"); Node n = new Node(a,"localhost", 8080, 1); n.addCircuitBreaker(vertx, 1000, 2, 30*1000); Handler<AsyncResult<HttpResponse<Buffer>>> h = r->{ if(r.succeeded()) System.out.println("OK "+n.status()); else System.out.println("Fail "+n.status()); }; n.get("/test", null, h); n.get("/test", null, h); n.get("/test", null, h); for(int i=0;i<20;i++){ Thread.sleep(10* 1000); n.get("/test", null, h); n.get("/test", null, h); n.get("/test", null, h); } }
@Override public <P> void fetch(Query query, Function<JsonObject, P> mapper, Handler<AsyncResult<List<P>>> resultHandler) { getConnection().setHandler(sqlConnectionResult->{ if(sqlConnectionResult.succeeded()){ log("Fetch", ()-> query.getSQL(ParamType.INLINED)); sqlConnectionResult.result().queryWithParams( query.getSQL(), getBindValues(query), executeAndClose(rs -> rs.getRows().stream().map(mapper).collect(Collectors.toList()), sqlConnectionResult.result(), resultHandler) ); }else{ resultHandler.handle(Future.failedFuture(sqlConnectionResult.cause())); } }); }
private void subscriptionResult(final AsyncResult<HttpResponse<JsonArray>> ar) { if (ar.succeeded()) { // Process the result this.captureCookies(ar.result().cookies()); final JsonArray receivedData = ar.result().body(); final JsonObject status = receivedData.getJsonObject(receivedData.size() - 1); if (status.getBoolean("successful", false)) { // If the array has only one member we didn't get new data if (receivedData.size() > 1) { this.processReceivedData(receivedData); } // Do it again eventually if (!this.shuttingDown && !this.shutdownCompleted) { this.subscriptionFetch(); } else { this.shutdownCompleted = true; } } else { // We won't continue this.logger.fatal(status.encodePrettily()); this.shutdownCompleted = true; } } else { // Preliminary stopping here // needs to be handled this.logger.fatal(ar.cause()); this.shutdownCompleted = true; } }
protected <T> Handler<AsyncResult<T>> onSuccess(final Consumer<T> consumer) { return result -> { if (result.failed()) { result.cause().printStackTrace(); fail(result.cause().getMessage()); } else { consumer.accept(result.result()); } }; }
@Override public WikiDatabaseService createPage(String title, String markdown, Handler<AsyncResult<Void>> resultHandler) { dbClient.rxUpdateWithParams(sqlQueries.get(SqlQuery.CREATE_PAGE), new JsonArray().add(title).add(markdown)) .map(res -> (Void) null) .subscribe(RxHelper.toSubscriber(resultHandler)); return this; }
@Override public void semgrex(RequestParameters parameters, Handler<AsyncResult<JsonObject>> handler) { Objects.requireNonNull(parameters.getPattern(), "pattern must have a value"); buildRequest("/semgrex", parameters) .sendBuffer(Buffer.buffer(parameters.getText()), h -> { if (h.succeeded()) { handler.handle(Future.succeededFuture(h.result().body())); } else { handler.handle(Future.failedFuture(h.cause())); } }); }
public void start(Handler<AsyncResult<HttpServer>> serverStartupHandler) { ImmutableHttpServerOptions immutableHttpServerOptions = new ImmutableHttpServerOptions(); VertxContext vertxContext = initializeContext(immutableHttpServerOptions); Future<HttpServerOptions> future = Future.future(); future.setHandler( options -> onHttpServerConfigurationCompleted(immutableHttpServerOptions, vertxContext, options, serverStartupHandler)); configureHttpServer(vertxContext, future); }
@Override public SSDBClient auth(String authKey, Handler<AsyncResult<Boolean>> handler) { sendCommand(F.ofSucceeded(handler, this::booleanValue), "auth", authKey); return this; }
public void findAll(Handler<AsyncResult<List<JsonObject>>> handler) { mongoClient.find(COLLECTION_NAME, new JsonObject(), handler); }
protected void deployController(Controller controller, Handler<AsyncResult<String>> handler) { Server server = new Server(controller); DeploymentOptions options = new DeploymentOptions().setConfig(new JsonObject().put("port", port)); rule.vertx().deployVerticle(server, options, handler); }
private CommandBase query(String sql, Handler<AsyncResult<PgResult<Row>>> handler) { return new SimpleQueryCommand<>(sql, new RowResultDecoder(), new SimpleQueryResultHandler<>(handler)); }
@Fluent WikiDatabaseService deletePage(int id, Handler<AsyncResult<Void>> resultHandler);
@Fluent EntityManagerExt isJoinedToTransaction(Handler<AsyncResult<Boolean>> handler);
@Override void handle(AsyncResult<Boolean> res);
@Override public HttpServer listen(Handler<AsyncResult<HttpServer>> listenHandler) { listenHandler.handle(Future.succeededFuture(this)); processRequest(); return this; }
@Override public SSDBClient hrscan(String hashKey, String fieldKeyStart, String fieldKeyEnd, int limit, Handler<AsyncResult<List<PairStringString>>> handler) { sendCommand(F.ofSucceeded(handler, this::listPairValue), "hscan", hashKey, fieldKeyStart, fieldKeyEnd, limit); return this; }
public void getClient(Function<Record, Boolean> filter, Handler<AsyncResult<JDBCClient>> handler) { JDBCDataSource.getJDBCClient(serviceDiscovery, filter, handler); }
private void publishMessageSourceService(MessageSourceConfiguration configuration, Handler<AsyncResult<Record>> handler) { vertxServiceDiscovery.messageSource().publish(configuration, handler); }
@Override public HttpServerResponse push(io.vertx.core.http.HttpMethod method, String host, String path, Handler<AsyncResult<HttpServerResponse>> handler) { return push(method, path, handler); }
/** * Fetch a unique record that has <code>someId = value</code> asynchronously */ public void fetchOneBySomeidAsync(Integer value,Handler<AsyncResult<generated.classic.async.vertx.tables.pojos.Something>> resultHandler) { fetchOneAsync(Something.SOMETHING.SOMEID,value,resultHandler); }
@Fluent WikiDatabaseService createPage(String title, String markdown, Handler<AsyncResult<Void>> resultHandler);
/** * Fetch records that have <code>someJsonObject IN (values)</code> asynchronously */ public void fetchBySomejsonobjectAsync(List<JsonObject> values,Handler<AsyncResult<List<generated.classic.async.vertx.tables.pojos.Something>>> resultHandler) { fetchAsync(Something.SOMETHING.SOMEJSONOBJECT,values,resultHandler); }