Java Code Examples for io.vertx.core.AsyncResult

The following are top voted examples for showing how to use io.vertx.core.AsyncResult. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: vertx-guide-for-java-devs_chinese   File: WikiDatabaseServiceImpl.java   View source code 6 votes vote down vote up
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));
        }
      });
    }
  });
}
 
Example 2
Project: vertx-guide-for-java-devs_chinese   File: WikiDatabaseServiceImpl.java   View source code 6 votes vote down vote up
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));
        }
      });
    }
  });
}
 
Example 3
Project: jspare-vertx-ms-blueprint   File: MailServiceVertxEBProxy.java   View source code 6 votes vote down vote up
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;
}
 
Example 4
Project: vertx-kubernetes-workshop   File: PortfolioServiceImpl.java   View source code 6 votes vote down vote up
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));
            }
        });
}
 
Example 5
Project: vertx-guide-for-java-devs_chinese   File: HttpServerVerticle.java   View source code 6 votes vote down vote up
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);
  }
}
 
Example 6
Project: vertx-fastdfs-client   File: FdfsClientImpl.java   View source code 6 votes vote down vote up
@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;
}
 
Example 7
Project: vertx-kubernetes-workshop   File: PortfolioServiceVertxEBProxy.java   View source code 6 votes vote down vote up
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())));
                    }
  });
}
 
Example 8
Project: vertx-zero   File: RpcClientImpl.java   View source code 5 votes vote down vote up
@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);
}
 
Example 9
Project: vertx-guide-for-java-devs_chinese   File: WikiDatabaseServiceImpl.java   View source code 5 votes vote down vote up
@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;
}
 
Example 10
Project: vertx-kubernetes-workshop   File: PortfolioServiceImpl.java   View source code 5 votes vote down vote up
@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()));
    }
}
 
Example 11
Project: vertx-graphql-utils   File: AsyncResCF.java   View source code 5 votes vote down vote up
@Override
public void handle(AsyncResult<T> ar) {
    if (ar.succeeded()) {
        complete(ar.result());
    } else {
        completeExceptionally(ar.cause());
    }
}
 
Example 12
Project: vertx-aws-lambda   File: LambdaServer.java   View source code 5 votes vote down vote up
@Override

    public HttpServer listen(int port, Handler<AsyncResult<HttpServer>> listenHandler) {
        localPort = port;
        listenHandler.handle(Future.succeededFuture(this));
        processRequest();
        return this;
    }
 
Example 13
Project: vertx-guide-for-java-devs   File: WikiDatabaseServiceImpl.java   View source code 5 votes vote down vote up
@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;
}
 
Example 14
Project: vertx-guide-for-java-devs_chinese   File: HttpServerVerticle.java   View source code 5 votes vote down vote up
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());
  }
}
 
Example 15
Project: vertx-jooq-async   File: VertxDAO.java   View source code 5 votes vote down vote up
/**
 * 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;
    });
}
 
Example 16
Project: vertx-guide-for-java-devs_chinese   File: WikiDatabaseServiceImpl.java   View source code 5 votes vote down vote up
@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;
}
 
Example 17
Project: vertx-guide-for-java-devs_chinese   File: WikiDatabaseServiceImpl.java   View source code 5 votes vote down vote up
@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;
}
 
Example 18
Project: jspare-vertx-ms-blueprint   File: BasicAuthAdapterImpl.java   View source code 5 votes vote down vote up
@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()));
		}
	});
}
 
Example 19
Project: etagate   File: TestCircuitBreaker.java   View source code 5 votes vote down vote up
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);
	}

}
 
Example 20
Project: vertx-jooq-async   File: AsyncJooqSQLClientImpl.java   View source code 5 votes vote down vote up
@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()));
        }
    });
}
 
Example 21
Project: vertx-sfdc-platformevents   File: CometD.java   View source code 5 votes vote down vote up
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;
	}
}
 
Example 22
Project: vertx-zero   File: AsyncTestBase.java   View source code 5 votes vote down vote up
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());
        }
    };
}
 
Example 23
Project: vertx-guide-for-java-devs_chinese   File: WikiDatabaseServiceImpl.java   View source code 5 votes vote down vote up
@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;
}
 
Example 24
Project: vertx-corenlp-client   File: CoreNLPClientImpl.java   View source code 5 votes vote down vote up
@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()));
      }
    });
}
 
Example 25
Project: domino   File: DominoLoader.java   View source code 5 votes vote down vote up
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);
}
 
Example 26
Project: vertx-ssdb   File: SSDBClientImpl.java   View source code 4 votes vote down vote up
@Override
public SSDBClient auth(String authKey, Handler<AsyncResult<Boolean>> handler)
{
    sendCommand(F.ofSucceeded(handler, this::booleanValue), "auth", authKey);
    return this;
}
 
Example 27
Project: vertx-starter   File: ProjectRepository.java   View source code 4 votes vote down vote up
public void findAll(Handler<AsyncResult<List<JsonObject>>> handler) {
  mongoClient.find(COLLECTION_NAME, new JsonObject(), handler);
}
 
Example 28
Project: irked   File: TestBase.java   View source code 4 votes vote down vote up
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);
}
 
Example 29
Project: reactive-pg-client   File: Transaction.java   View source code 4 votes vote down vote up
private CommandBase query(String sql, Handler<AsyncResult<PgResult<Row>>> handler) {
  return new SimpleQueryCommand<>(sql, new RowResultDecoder(), new SimpleQueryResultHandler<>(handler));
}
 
Example 30
Project: vertx-guide-for-java-devs_chinese   File: WikiDatabaseService.java   View source code 4 votes vote down vote up
@Fluent
WikiDatabaseService deletePage(int id, Handler<AsyncResult<Void>> resultHandler);
 
Example 31
Project: vertx-jpa   File: EntityManagerExt.java   View source code 4 votes vote down vote up
@Fluent
EntityManagerExt isJoinedToTransaction(Handler<AsyncResult<Boolean>> handler);
 
Example 32
Project: reactive-pg-client   File: QueryResultHandler.java   View source code 4 votes vote down vote up
@Override
void handle(AsyncResult<Boolean> res);
 
Example 33
Project: vertx-aws-lambda   File: LambdaServer.java   View source code 4 votes vote down vote up
@Override
public HttpServer listen(Handler<AsyncResult<HttpServer>> listenHandler) {
    listenHandler.handle(Future.succeededFuture(this));
    processRequest();
    return this;
}
 
Example 34
Project: vertx-ssdb   File: SSDBClientImpl.java   View source code 4 votes vote down vote up
@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;
}
 
Example 35
Project: domino   File: JDBCServiceDiscovery.java   View source code 4 votes vote down vote up
public void getClient(Function<Record, Boolean> filter, Handler<AsyncResult<JDBCClient>> handler) {
    JDBCDataSource.getJDBCClient(serviceDiscovery, filter, handler);
}
 
Example 36
Project: domino   File: MessageSourceServiceDiscoveryTest.java   View source code 4 votes vote down vote up
private void publishMessageSourceService(MessageSourceConfiguration configuration, Handler<AsyncResult<Record>> handler) {
    vertxServiceDiscovery.messageSource().publish(configuration, handler);
}
 
Example 37
Project: vertx-aws-lambda   File: HttpServerResponseImpl.java   View source code 4 votes vote down vote up
@Override
public HttpServerResponse push(io.vertx.core.http.HttpMethod method, String host, String path,
        Handler<AsyncResult<HttpServerResponse>> handler) {
    return push(method, path, handler);
}
 
Example 38
Project: vertx-jooq-async   File: SomethingDao.java   View source code 4 votes vote down vote up
/**
 * 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);
}
 
Example 39
Project: vertx-guide-for-java-devs   File: WikiDatabaseService.java   View source code 4 votes vote down vote up
@Fluent
WikiDatabaseService createPage(String title, String markdown, Handler<AsyncResult<Void>> resultHandler);
 
Example 40
Project: vertx-jooq-async   File: SomethingDao.java   View source code 4 votes vote down vote up
/**
 * 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);
}