io.vertx.reactivex.core.RxHelper Java Examples

The following examples show how to use io.vertx.reactivex.core.RxHelper. 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: DashboardWebAppVerticle.java    From vertx-in-action with MIT License 6 votes vote down vote up
private void hydrate() {
  WebClient webClient = WebClient.create(vertx);
  webClient
    .get(3001, "localhost", "/ranking-last-24-hours")
    .as(BodyCodec.jsonArray())
    .rxSend()
    .delay(5, TimeUnit.SECONDS, RxHelper.scheduler(vertx))
    .retry(5)
    .map(HttpResponse::body)
    .flattenAsFlowable(Functions.identity())
    .cast(JsonObject.class)
    .flatMapSingle(json -> whoOwnsDevice(webClient, json))
    .flatMapSingle(json -> fillWithUserProfile(webClient, json))
    .subscribe(
      this::hydrateEntryIfPublic,
      err -> logger.error("Hydratation error", err),
      () -> logger.info("Hydratation completed"));
}
 
Example #2
Source File: CongratsTest.java    From vertx-in-action with MIT License 6 votes vote down vote up
@BeforeEach
void prepare(Vertx vertx, VertxTestContext testContext) {
  Map<String, String> conf = new HashMap<>();
  conf.put("bootstrap.servers", "localhost:9092");
  conf.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
  conf.put("value.serializer", "io.vertx.kafka.client.serialization.JsonObjectSerializer");
  conf.put("acks", "1");
  producer = KafkaProducer.create(vertx, conf);
  webClient = WebClient.create(vertx);
  KafkaAdminClient adminClient = KafkaAdminClient.create(vertx, conf);
  adminClient
    .rxDeleteTopics(Arrays.asList("incoming.steps", "daily.step.updates"))
    .onErrorComplete()
    .andThen(vertx.rxDeployVerticle(new CongratsVerticle()))
    .ignoreElement()
    .andThen(vertx.rxDeployVerticle(new FakeUserService()))
    .ignoreElement()
    .andThen(webClient.delete(8025, "localhost", "/api/v1/messages").rxSend())
    .ignoreElement()
    .delay(1, TimeUnit.SECONDS, RxHelper.scheduler(vertx))
    .subscribe(testContext::completeNow, testContext::failNow);
}
 
Example #3
Source File: CongratsTest.java    From vertx-in-action with MIT License 6 votes vote down vote up
@Test
@DisplayName("No email must be sent below 10k steps")
void checkNothingBelow10k(Vertx vertx, VertxTestContext testContext) {
  producer
    .rxSend(record("123", 5000))
    .ignoreElement()
    .delay(3, TimeUnit.SECONDS, RxHelper.scheduler(vertx))
    .andThen(webClient
      .get(8025, "localhost", "/api/v2/search?kind=to&[email protected]")
      .as(BodyCodec.jsonObject()).rxSend())
    .map(HttpResponse::body)
    .subscribe(
      json -> {
        testContext.verify(() -> assertThat(json.getInteger("total")).isEqualTo(0));
        testContext.completeNow();
      },
      testContext::failNow);
}
 
Example #4
Source File: AuditReporterManagerImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private void deployReporterVerticle(Collection<Reporter> reporters) {
    Single<String> deployment = RxHelper.deployVerticle(vertx, applicationContext.getBean(AuditReporterVerticle.class));

    deployment.subscribe(id -> {
        // Deployed
        deploymentId = id;
        if (!reporters.isEmpty()) {
            for (io.gravitee.reporter.api.Reporter reporter : reporters) {
                try {
                    logger.info("Starting reporter: {}", reporter);
                    reporter.start();
                } catch (Exception ex) {
                    logger.error("Unexpected error while starting reporter", ex);
                }
            }
        } else {
            logger.info("\tThere is no reporter to start");
        }
    }, err -> {
        // Could not deploy
        logger.error("Reporter service can not be started", err);
    });
}
 
Example #5
Source File: IntegrationTest.java    From vertx-in-action with MIT License 6 votes vote down vote up
@Test
@DisplayName("Ingest a badly-formed JSON data over HTTP and observe no Kafka record")
void httpIngestWrong(Vertx vertx, VertxTestContext testContext) {
  JsonObject body = new JsonObject();

  given(requestSpecification)
    .contentType(ContentType.JSON)
    .body(body.encode())
    .post("/ingest")
    .then()
    .assertThat()
    .statusCode(400);

  kafkaConsumer.subscribe("incoming.steps")
    .toFlowable()
    .timeout(3, TimeUnit.SECONDS, RxHelper.scheduler(vertx))
    .subscribe(
      record -> testContext.failNow(new IllegalStateException("We must not get a record")),
      err -> {
        if (err instanceof TimeoutException) {
          testContext.completeNow();
        } else {
          testContext.failNow(err);
        }
      });
}
 
Example #6
Source File: AuditReporterManagerImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    logger.info("Initializing reporters for domain {}", domain.getName());
    logger.info("\t Starting reporter verticle for domain {}", domain.getName());

    Single<String> deployment = RxHelper.deployVerticle(vertx, applicationContext.getBean(AuditReporterVerticle.class));
    deployment.subscribe(id -> {
        // Deployed
        deploymentId = id;
        // Start reporters
        List<Reporter> reporters = reporterRepository.findByDomain(domain.getId()).blockingGet();
        if (!reporters.isEmpty()) {
            reporters.forEach(reporter -> startReporterProvider(reporter));
            logger.info("Reporters loaded for domain {}", domain.getName());
        } else {
            logger.info("\tThere is no reporter to start");
        }
    }, err -> {
        // Could not deploy
        logger.error("Reporter service can not be started", err);
    });
}
 
Example #7
Source File: DashboardWebAppVerticle.java    From vertx-in-action with MIT License 5 votes vote down vote up
@Override
public Completable rxStart() {
  Router router = Router.router(vertx);

  KafkaConsumer.<String, JsonObject>create(vertx, KafkaConfig.consumerConfig("dashboard-webapp-throughput"))
    .subscribe("event-stats.throughput")
    .toFlowable()
    .subscribe(record -> forwardKafkaRecord(record, "client.updates.throughput"));

  KafkaConsumer.<String, JsonObject>create(vertx, KafkaConfig.consumerConfig("dashboard-webapp-city-trend"))
    .subscribe("event-stats.city-trend.updates")
    .toFlowable()
    .subscribe(record -> forwardKafkaRecord(record, "client.updates.city-trend"));

  KafkaConsumer.<String, JsonObject>create(vertx, KafkaConfig.consumerConfig("dashboard-webapp-ranking"))
    .subscribe("event-stats.user-activity.updates")
    .toFlowable()
    .filter(record -> record.value().getBoolean("makePublic"))
    .buffer(5, TimeUnit.SECONDS, RxHelper.scheduler(vertx))
    .subscribe(this::updatePublicRanking);

  hydrate();

  SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
  SockJSBridgeOptions bridgeOptions = new SockJSBridgeOptions()
    .addInboundPermitted(new PermittedOptions().setAddressRegex("client.updates.*"))
    .addOutboundPermitted(new PermittedOptions().setAddressRegex("client.updates.*"));
  sockJSHandler.bridge(bridgeOptions);
  router.route("/eventbus/*").handler(sockJSHandler);

  router.get("/").handler(ctx -> ctx.reroute("/index.html"));
  router.route().handler(StaticHandler.create("webroot/assets"));

  return vertx.createHttpServer()
    .requestHandler(router)
    .rxListen(HTTP_PORT)
    .ignoreElement();
}
 
Example #8
Source File: CoreApiTest.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeployVerticle() throws Exception {
  CountDownLatch deployLatch = new CountDownLatch(2);
  RxHelper.deployVerticle(vertx, new AbstractVerticle() {
    @Override
    public void start() {
      deployLatch.countDown();
    }
  }).subscribe(resp -> {
    deployLatch.countDown();
  });
  awaitLatch(deployLatch);
}
 
Example #9
Source File: RxHelperTest.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Test
public void deployVerticleFailure() throws Exception {
  CoreVerticle verticle = new CoreVerticle(true);
  Single<String> single = RxHelper.deployVerticle(vertx, verticle);
  assertNull(verticle.config);
  try {
    single.blockingGet();
    fail("Verticle deployment should fail");
  } catch (RuntimeException e) {
    assertThat(e.getCause(), instanceOf(MyException.class));
    assertNotNull(verticle.config);
    assertTrue(verticle.config.isEmpty());
  }
}
 
Example #10
Source File: RxHelperTest.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Test
public void deployVerticleWithOptions() throws Exception {
  CoreVerticle verticle = new CoreVerticle();
  JsonObject expected = new JsonObject()
    .put("bim", 1).put("bam", new JsonArray().add(1).add(2).add(3)).put("boum", new JsonObject().put("toto", "titi"));
  Single<String> single = RxHelper.deployVerticle(vertx, verticle, new DeploymentOptions().setConfig(expected));
  assertNull(verticle.config);
  single.blockingGet();
  assertEquals(expected, verticle.config);
}
 
Example #11
Source File: RxHelperTest.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Test
public void deployVerticle() throws Exception {
  CoreVerticle verticle = new CoreVerticle();
  Single<String> single = RxHelper.deployVerticle(vertx, verticle);
  assertNull(verticle.config);
  single.blockingGet();
  assertNotNull(verticle.config);
  assertTrue(verticle.config.isEmpty());
}
 
Example #12
Source File: RxifiedExamples.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
public void deployVerticle(Vertx vertx, Verticle verticle) {
  Single<String> deployment = RxHelper.deployVerticle(vertx, verticle);

  deployment.subscribe(id -> {
    // Deployed
  }, err -> {
    // Could not deploy
  });
}
 
Example #13
Source File: RxJava2Test.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("Check the deployment and interaction of a Rx1 verticle")
void check_deployment_and_message_send(Vertx vertx, VertxTestContext testContext) {
  RxHelper
    .deployVerticle(vertx, new RxVerticle())
    .flatMap(id -> vertx.eventBus().rxRequest("check", "Ok?"))
    .subscribe(
      message -> testContext.verify(() -> {
        assertThat(message.body()).isEqualTo("Check!");
        testContext.completeNow();
      }),
      testContext::failNow);
}
 
Example #14
Source File: VertxExecutionModel.java    From smallrye-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@Override
public Flowable apply(Flowable input) {
    Context context = Vertx.currentContext();
    if (context != null && context.getDelegate() != null) {
        return input.compose(f -> f.observeOn(RxHelper.scheduler(context)));
    }
    return input;
}
 
Example #15
Source File: VertxIntro.java    From vertx-in-action with MIT License 5 votes vote down vote up
@Override
public Completable rxStart() {
  Observable
    .interval(1, TimeUnit.SECONDS, RxHelper.scheduler(vertx))
    .subscribe(n -> System.out.println("tick"));

  return vertx.createHttpServer()
    .requestHandler(r -> r.response().end("Ok"))
    .rxListen(8080)
    .ignoreElement();
}
 
Example #16
Source File: EventStatsVerticle.java    From vertx-in-action with MIT License 5 votes vote down vote up
@Override
public Completable rxStart() {
  webClient = WebClient.create(vertx);
  producer = KafkaProducer.create(vertx, KafkaConfig.producer());

  KafkaConsumer.<String, JsonObject>create(vertx, KafkaConfig.consumer("event-stats-throughput"))
    .subscribe("incoming.steps")
    .toFlowable()
    .buffer(5, TimeUnit.SECONDS, RxHelper.scheduler(vertx))
    .flatMapCompletable(this::publishThroughput)
    .doOnError(err -> logger.error("Woops", err))
    .retryWhen(this::retryLater)
    .subscribe();

  KafkaConsumer.<String, JsonObject>create(vertx, KafkaConfig.consumer("event-stats-user-activity-updates"))
    .subscribe("daily.step.updates")
    .toFlowable()
    .flatMapSingle(this::addDeviceOwner)
    .flatMapSingle(this::addOwnerData)
    .flatMapCompletable(this::publishUserActivityUpdate)
    .doOnError(err -> logger.error("Woops", err))
    .retryWhen(this::retryLater)
    .subscribe();

  KafkaConsumer.<String, JsonObject>create(vertx, KafkaConfig.consumer("event-stats-city-trends"))
    .subscribe("event-stats.user-activity.updates")
    .toFlowable()
    .groupBy(this::city)
    .flatMap(groupedFlowable -> groupedFlowable.buffer(5, TimeUnit.SECONDS, RxHelper.scheduler(vertx)))
    .flatMapCompletable(this::publishCityTrendUpdate)
    .doOnError(err -> logger.error("Woops", err))
    .retryWhen(this::retryLater)
    .subscribe();

  return Completable.complete();
}
 
Example #17
Source File: IntegrationTest.java    From vertx-in-action with MIT License 5 votes vote down vote up
@Test
@DisplayName("Ingest a badly-formed AMQP message and observe no Kafka record")
void amqIngestWrong(Vertx vertx, VertxTestContext testContext) {
  JsonObject body = new JsonObject();

  amqpClient.rxConnect()
    .flatMap(connection -> connection.rxCreateSender("step-events"))
    .subscribe(
      sender -> {
        AmqpMessage msg = AmqpMessage.create()
          .durable(true)
          .ttl(5000)
          .withJsonObjectAsBody(body).build();
        sender.send(msg);
      },
      testContext::failNow);

  kafkaConsumer.subscribe("incoming.steps")
    .toFlowable()
    .timeout(3, TimeUnit.SECONDS, RxHelper.scheduler(vertx))
    .subscribe(
      record -> testContext.failNow(new IllegalStateException("We must not get a record")),
      err -> {
        if (err instanceof TimeoutException) {
          testContext.completeNow();
        } else {
          testContext.failNow(err);
        }
      });
}
 
Example #18
Source File: IntegrationTest.java    From vertx-in-action with MIT License 5 votes vote down vote up
@BeforeEach
void setup(Vertx vertx, VertxTestContext testContext) {
  kafkaConsumer = KafkaConsumer.create(vertx, kafkaConfig());
  amqpClient = AmqpClient.create(vertx, amqClientOptions());
  KafkaAdminClient adminClient = KafkaAdminClient.create(vertx, kafkaConfig());
  vertx
    .rxDeployVerticle(new IngesterVerticle())
    .delay(500, TimeUnit.MILLISECONDS, RxHelper.scheduler(vertx))
    .flatMapCompletable(id -> adminClient.rxDeleteTopics(singletonList("incoming.steps")))
    .onErrorComplete()
    .subscribe(testContext::completeNow, testContext::failNow);
}
 
Example #19
Source File: RxProxyClient.java    From vertx-in-action with MIT License 5 votes vote down vote up
@Override
public void start() {
  SensorDataService service = SensorDataService.createProxy(vertx, "sensor.data-service");
  service.rxAverage()
    .delaySubscription(3, TimeUnit.SECONDS, RxHelper.scheduler(vertx))
    .repeat()
    .map(data -> "avg = " + data.getDouble("average"))
    .subscribe(System.out::println);
}
 
Example #20
Source File: EventStatsVerticle.java    From vertx-in-action with MIT License 4 votes vote down vote up
private Flowable<Throwable> retryLater(Flowable<Throwable> errs) {
  return errs.delay(10, TimeUnit.SECONDS, RxHelper.scheduler(vertx));
}
 
Example #21
Source File: RxifiedExamples.java    From vertx-rx with Apache License 2.0 4 votes vote down vote up
public void schedulerHook(Vertx vertx) {
  RxJavaPlugins.setComputationSchedulerHandler(s -> RxHelper.scheduler(vertx));
  RxJavaPlugins.setIoSchedulerHandler(s -> RxHelper.blockingScheduler(vertx));
  RxJavaPlugins.setNewThreadSchedulerHandler(s -> RxHelper.scheduler(vertx));
}
 
Example #22
Source File: IngesterVerticle.java    From vertx-in-action with MIT License 4 votes vote down vote up
private Flowable<Throwable> retryLater(Flowable<Throwable> errs) {
  return errs.delay(10, TimeUnit.SECONDS, RxHelper.scheduler(vertx));
}
 
Example #23
Source File: RxifiedExamples.java    From vertx-rx with Apache License 2.0 4 votes vote down vote up
public void writeStreamSubscriberAdapter(Flowable<io.vertx.core.buffer.Buffer> flowable, io.vertx.core.http.HttpServerResponse response) {
  response.setChunked(true);
  WriteStreamSubscriber<io.vertx.core.buffer.Buffer> subscriber = io.vertx.reactivex.RxHelper.toSubscriber(response);
  flowable.subscribe(subscriber);
}
 
Example #24
Source File: CongratsTest.java    From vertx-in-action with MIT License 4 votes vote down vote up
private Flowable<Long> retryLater(Vertx vertx, Flowable<Throwable> errs) {
  return errs
    .flatMap(d -> Flowable.timer(10, TimeUnit.SECONDS, RxHelper.scheduler(vertx)));
}
 
Example #25
Source File: CongratsVerticle.java    From vertx-in-action with MIT License 4 votes vote down vote up
private Flowable<Throwable> retryLater(Flowable<Throwable> errs) {
  return errs.delay(10, TimeUnit.SECONDS, RxHelper.scheduler(vertx));
}
 
Example #26
Source File: EventsVerticle.java    From vertx-in-action with MIT License 4 votes vote down vote up
private Flowable<Throwable> retryLater(Flowable<Throwable> errs) {
  return errs.delay(10, TimeUnit.SECONDS, RxHelper.scheduler(vertx));
}