Skip to content

Instantly share code, notes, and snippets.

@cescoffier
Created September 18, 2020 13:36
Show Gist options
  • Select an option

  • Save cescoffier/1ed68bef12b798529e10350f77686e9a to your computer and use it in GitHub Desktop.

Select an option

Save cescoffier/1ed68bef12b798529e10350f77686e9a to your computer and use it in GitHub Desktop.

Revisions

  1. cescoffier created this gist Sep 18, 2020.
    70 changes: 70 additions & 0 deletions Quotes.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,70 @@
    //usr/bin/env jbang "$0" "$@" ; exit $?

    //DEPS io.smallrye.reactive:smallrye-mutiny-vertx-web-client:1.1.0
    //DEPS io.smallrye.reactive:mutiny:0.7.0
    //DEPS org.slf4j:slf4j-nop:1.7.30

    package io.vertx.mutiny.quotes;

    import io.smallrye.mutiny.Multi;
    import io.smallrye.mutiny.Uni;
    import io.vertx.core.json.JsonObject;
    import io.vertx.ext.web.client.WebClientOptions;
    import io.vertx.mutiny.core.Vertx;
    import io.vertx.mutiny.core.buffer.Buffer;
    import io.vertx.mutiny.ext.web.client.HttpResponse;
    import io.vertx.mutiny.ext.web.client.WebClient;
    import io.vertx.mutiny.ext.web.codec.BodyCodec;

    import java.util.Collections;
    import java.util.List;
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.atomic.AtomicInteger;
    import java.util.stream.Collectors;

    public class Quotes {

    public static final String PROGRAMMING_QUOTE = "https://programming-quotes-api.herokuapp.com/quotes/random";
    public static final String CHUCK_NORRIS_QUOTE = "https://api.chucknorris.io/jokes/random";

    public static void main(String[] args) throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    // Create the Vert.x instance. In a Quarkus app, just inject it.
    Vertx vertx = Vertx.vertx();
    // Create a Web Client
    WebClient client = WebClient.create(vertx);

    // Combine the result of our 2 Unis in a tuple and subscribe to it
    Uni.combine().all()
    .unis(getProgrammingQuote(client), getChuckNorrisQuote(client))
    .asTuple()
    .subscribe().with(tuple -> {
    System.out.println("Programming Quote: " + tuple.getItem1());
    System.out.println("Chuck Norris Quote: " + tuple.getItem2());

    latch.countDown();
    });


    latch.await(10, TimeUnit.SECONDS);
    vertx.closeAndAwait();
    }

    private static Uni<String> getProgrammingQuote(WebClient client) {
    return client.getAbs(PROGRAMMING_QUOTE)
    .as(BodyCodec.jsonObject())
    .send()
    .onItem().transform(r -> r.body().getString("en") + " (" + r.body().getString("author") + ")");
    }

    private static Uni<String> getChuckNorrisQuote(WebClient client) {
    return client.getAbs(CHUCK_NORRIS_QUOTE)
    .as(BodyCodec.jsonObject())
    .send()
    .onItem().transform(r -> r.body().getString("value"));
    }



    }