io.vertx.reactivex.CompletableHelper Java Examples

The following examples show how to use io.vertx.reactivex.CompletableHelper. 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: RestQuoteAPIVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Future<Void> future) throws Exception {
    // Get the stream of messages sent on the "market" address
    vertx.eventBus().<JsonObject>consumer(GeneratorConfigVerticle.ADDRESS).toFlowable()
        // TODO Extract the body of the message using `.map(msg -> {})`
        // ----
        //
        // ----
        // TODO For each message, populate the `quotes` map with the received quote. Use `.doOnNext(json -> {})`
        // Quotes are json objects you can retrieve from the message body
        // The map is structured as follows: name -> quote
        // ----
        //
        // ----
        .subscribe();

    HttpServer server = vertx.createHttpServer();
    server.requestStream().toFlowable()
        .doOnNext(request -> {
            HttpServerResponse response = request.response()
                .putHeader("content-type", "application/json");

            // TODO Handle the HTTP request
            // The request handler returns a specific quote if the `name` parameter is set, or the whole map if none.
            // To write the response use: `response.end(content)`
            // If the name is set but not found, you should return 404 (use response.setStatusCode(404)).
            // To encode a Json object, use the `encorePrettily` method
            // ----

            // Remove this line
            response.end(Json.encodePrettily(quotes));
            
            // ----
        })
    .subscribe();

    server.rxListen(config().getInteger("http.port", 8080))
        .toCompletable()
        .subscribe(CompletableHelper.toObserver(future));
}
 
Example #2
Source File: GeneratorConfigVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
@Override
public void stop(Future<Void> future) throws Exception {
    if (record != null) {
        discovery.rxUnpublish(record.getRegistration()).subscribe(CompletableHelper.toObserver(future));
    } else {
        future.complete();
    }
}
 
Example #3
Source File: GeneratorConfigVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
@Override
public void stop(Future<Void> future) throws Exception {
    if (record != null) {
        discovery.rxUnpublish(record.getRegistration()).subscribe(CompletableHelper.toObserver(future));
    } else {
        future.complete();
    }
}
 
Example #4
Source File: HelperTest.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Test
public void testToCompletableObserverSuccess() {
  Promise<String> promise = Promise.promise();
  CompletableObserver observer = CompletableHelper.toObserver(promise);
  Completable s = Completable.complete();
  s.subscribe(observer);
  assertTrue(promise.future().succeeded());
  assertNull(promise.future().result());
}
 
Example #5
Source File: HelperTest.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Test
public void testToCompletableObserverFailure() {
  Promise<String> promise = Promise.promise();
  CompletableObserver observer = CompletableHelper.toObserver(promise);
  RuntimeException cause = new RuntimeException();
  Completable s = Completable.error(cause);
  s.subscribe(observer);
  assertTrue(promise.future().failed());
  assertSame(cause, promise.future().cause());
}
 
Example #6
Source File: MyFirstVerticle.java    From introduction-to-eclipse-vertx with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Future<Void> fut) {

    // Create a router object.
    Router router = Router.router(vertx);

    // Bind "/" to our hello message - so we are still compatible.
    router.route("/").handler(routingContext -> {
        HttpServerResponse response = routingContext.response();
        response
            .putHeader("content-type", "text/html")
            .end("<h1>Hello from my first Vert.x 3 application</h1>");
    });

    // Serve static resources from the /assets directory
    router.route("/assets/*").handler(StaticHandler.create("assets"));
    router.get("/api/articles").handler(this::getAll);
    router.get("/api/articles/:id").handler(this::getOne);
    router.route("/api/articles*").handler(BodyHandler.create());
    router.post("/api/articles").handler(this::addOne);
    router.delete("/api/articles/:id").handler(this::deleteOne);
    router.put("/api/articles/:id").handler(this::updateOne);

    ConfigRetriever retriever = ConfigRetriever.create(vertx);

    // Start sequence:
    // 1 - Retrieve the configuration
    //      |- 2 - Create the JDBC client
    //      |- 3 - Connect to the database (retrieve a connection)
    //              |- 4 - Create table if needed
    //                   |- 5 - Add some data if needed
    //                          |- 6 - Close connection when done
    //              |- 7 - Start HTTP server
    //      |- 9 - we are done!

    retriever.rxGetConfig()
        .doOnSuccess(config ->
            jdbc = JDBCClient.createShared(vertx, config, "My-Reading-List"))
        .flatMap(config ->
            connect()
                .flatMap(connection ->
                    this.createTableIfNeeded(connection)
                        .flatMap(this::createSomeDataIfNone)
                        .doAfterTerminate(connection::close)
                )
                .map(x -> config)
        )
        .flatMapCompletable(config -> createHttpServer(config, router))
        .subscribe(CompletableHelper.toObserver(fut));

}
 
Example #7
Source File: RXCompulsiveTraderVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Future<Void> future) {
    String company = TraderUtils.pickACompany();
    int numberOfShares = TraderUtils.pickANumber();
    System.out.println("Java-RX compulsive trader configured for company " + company + " and shares: " +
        numberOfShares);


    ServiceDiscovery.create(vertx, discovery -> {
        Single<PortfolioService> retrieveThePortfolioService = RXEventBusService.rxGetProxy(discovery, PortfolioService.class,
            rec -> rec.getName().equalsIgnoreCase("portfolio"));

        Single<MessageConsumer<JsonObject>> retrieveTheMarket = MessageSource.rxGetConsumer(discovery,
            rec -> rec.getName().equalsIgnoreCase("market-data"));

        //TODO
        //----

        // TODO 1 - "wait" for both single to be completed (using Single.zip or Single.zipWith methods)
        retrieveThePortfolioService.zipWith(retrieveTheMarket, (ps, consumer) -> {

        // TODO 2 - When both single have completed, attach the handler to the message consumer to execute the
            // trading logic

            consumer.handler(message ->
                // TODO 3 - Use the TraderUtils.drumpTradingLogic method returning a Completable. Don't forget to
                // subscribe to it, or nothing will happen. Return "true" to comply with the "zip" operator
                // signature.
                
                TraderUtils.dumbTradingLogic(company, numberOfShares, ps, message.body()).subscribe());
            // We need to return something as requested by the "zip" signature.
            return true;
        })

            // TODO 4 - Transform the output into a Completable (toCompletable) and subscribe to it using:
            //.subscribe(CompletableHelper.toObserver(future)) - it reports the failure or success to the `done`
            // future.
            .toCompletable()
            .subscribe(CompletableHelper.toObserver(future));
        //----

    });
}
 
Example #8
Source File: RestQuoteAPIVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Future<Void> future) throws Exception {
    // Get the stream of messages sent on the "market" address
    vertx.eventBus().<JsonObject>consumer(GeneratorConfigVerticle.ADDRESS).toFlowable()
        // TODO Extract the body of the message using `.map(msg -> {})`
        // ----
        .map(Message::body)
        // ----
        // TODO For each message, populate the `quotes` map with the received quote. Use `.doOnNext(json -> {})`
        // Quotes are json objects you can retrieve from the message body
        // The map is structured as follows: name -> quote
        // ----
        .doOnNext(json -> {
            quotes.put(json.getString("name"), json); // 2
        })
        // ----
        .subscribe();

    HttpServer server = vertx.createHttpServer();
    server.requestStream().toFlowable()
        .doOnNext(request -> {
            HttpServerResponse response = request.response()
                .putHeader("content-type", "application/json");

            // TODO Handle the HTTP request
            // The request handler returns a specific quote if the `name` parameter is set, or the whole map if none.
            // To write the response use: `response.end(content)`
            // If the name is set but not found, you should return 404 (use response.setStatusCode(404)).
            // To encode a Json object, use the `encorePrettily` method
            // ----
            
            String company = request.getParam("name");
            if (company == null) {
                String content = Json.encodePrettily(quotes);
                response.end(content);
            } else {
                JsonObject quote = quotes.get(company);
                if (quote == null) {
                    response.setStatusCode(404).end();
                } else {
                    response.end(quote.encodePrettily());
                }
            }
            // ----
        })
        .subscribe();

    server.rxListen(config().getInteger("http.port", 8080))
        .toCompletable()
        .subscribe(CompletableHelper.toObserver(future));
}
 
Example #9
Source File: NativeExamples.java    From vertx-rx with Apache License 2.0 3 votes vote down vote up
public void handlerToCompletableObserver() {

    Handler<AsyncResult<Void>> handler = getHandler();

    // Subscribe to a Single
    Completable.complete().subscribe(CompletableHelper.toObserver(handler));
  }