io.vertx.reactivex.core.Vertx Java Examples

The following examples show how to use io.vertx.reactivex.core.Vertx. 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: RxVertxTestBase.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
protected void startNodes(int numNodes, VertxOptions options) {
    CountDownLatch latch = new CountDownLatch(numNodes);
    vertices = new Vertx[numNodes];
    for (int i = 0; i < numNodes; i++) {
        int index = i;
        clusteredVertx(options.setClusterHost("localhost").setClusterPort(0).setClustered(true)
                .setClusterManager(getClusterManager()), ar -> {
            try {
                if (ar.failed()) {
                    ar.cause().printStackTrace();
                }
                assertTrue("Failed to start node", ar.succeeded());
                vertices[index] = ar.result();
            }
            finally {
                latch.countDown();
            }
        });
    }
    try {
        assertTrue(latch.await(2, TimeUnit.MINUTES));
    } catch (InterruptedException e) {
        fail(e.getMessage());
    }
}
 
Example #2
Source File: ApiResource.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@RequiresPermissions("update")
@PUT
@Path("pages/{id}")
public Single<Response> apiUpdatePage(@PathParam("id") String id, 
		@ApiUpdateValid("markdown") JsonObject page,
		@Context HttpServerRequest req,
		@Context Vertx vertx){
	JsonArray params = new JsonArray();
	params.add(page.getString("markdown")).add(id);
	return SQLUtil.doInConnection(connection -> connection.rxUpdateWithParams(SQL.SQL_SAVE_PAGE, params))
			.map(res -> {
			    JsonObject event = new JsonObject()
			    	      .put("id", id)
			    	      .put("client", page.getString("client"));
			    vertx.eventBus().publish("page.saved", event);
				return Response.ok(new JsonObject().put("success", true)).build();
			});
}
 
Example #3
Source File: RxVertxTestBase.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
protected void tearDown() throws Exception {
    if (vertx != null) {
        close(vertx.getDelegate());
    }
    if (created != null) {
        CountDownLatch latch = new CountDownLatch(created.size());
        for (Vertx v : created) {
            v.close(ar -> {
                if (ar.failed()) {
                    log.error("Failed to shutdown vert.x", ar.cause());
                }
                latch.countDown();
            });
        }
        assertTrue(latch.await(180, TimeUnit.SECONDS));
    }
    FakeClusterManager.reset(); // Bit ugly
    super.tearDown();
}
 
Example #4
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 #5
Source File: CongratsTest.java    From vertx-in-action with MIT License 6 votes vote down vote up
@Test
@DisplayName("Smoke test to send a mail using mailhog")
void smokeTestSendmail(Vertx vertx, VertxTestContext testContext) {
  MailConfig config = new MailConfig()
    .setHostname("localhost")
    .setPort(1025);
  MailClient client = MailClient.createShared(vertx, config);
  MailMessage message = new MailMessage()
    .setFrom("[email protected]")
    .setSubject("Yo")
    .setTo("[email protected]")
    .setText("This is cool");
  client
    .rxSendMail(message)
    .subscribe(
      ok -> testContext.completeNow(),
      testContext::failNow);
}
 
Example #6
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 #7
Source File: EventProcessingTest.java    From vertx-in-action with MIT License 6 votes vote down vote up
@BeforeEach
void resetPgAndKafka(Vertx vertx, VertxTestContext testContext) {
  consumer = KafkaConsumer.create(vertx, KafkaConfig.consumer("activity-service-test-" + System.currentTimeMillis()));
  producer = KafkaProducer.create(vertx, KafkaConfig.producer());
  KafkaAdminClient adminClient = KafkaAdminClient.create(vertx, KafkaConfig.producer());

  PgPool pgPool = PgPool.pool(vertx, PgConfig.pgConnectOpts(), new PoolOptions());
  pgPool.query("DELETE FROM stepevent")
    .rxExecute()
    .flatMapCompletable(rs -> adminClient.rxDeleteTopics(Arrays.asList("incoming.steps", "daily.step.updates")))
    .andThen(Completable.fromAction(pgPool::close))
    .onErrorComplete()
    .subscribe(
      testContext::completeNow,
      testContext::failNow);
}
 
Example #8
Source File: ApiResource.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@RequiresPermissions("update")
@PUT
@Path("pages/{id}")
public Single<Response> apiUpdatePage(@PathParam("id") String id, 
		@ApiUpdateValid("markdown") JsonObject page,
		@Context HttpServerRequest req,
		@Context Vertx vertx){
	return Fibers.fiber(() -> {
		Optional<Pages> res = Fibers.await(dao.findOneById(Integer.valueOf(id)));
		if(!res.isPresent())
			return Response.status(Status.NOT_FOUND).build();
		Fibers.await(dao.update(res.get().setContent(page.getString("markdown"))));
		JsonObject event = new JsonObject()
				.put("id", id)
				.put("client", page.getString("client"));
		vertx.eventBus().publish("page.saved", event);
		return Response.ok(new JsonObject().put("success", true)).build();
	});
}
 
Example #9
Source File: TestResource.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@Path("inject")
@GET
public String inject(@Context Vertx vertx,
		@Context RoutingContext routingContext,
		@Context HttpServerRequest request,
		@Context HttpServerResponse response,
		@Context AuthProvider authProvider,
		@Context User user,
		@Context Session session) {
	if(vertx == null
			|| routingContext == null
			|| request == null
			|| response == null
			|| session == null)
		throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
	return "ok";
}
 
Example #10
Source File: RxVertxTestBase.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
public void setUp() throws Exception {
    super.setUp();
    vinit();
    VertxOptions options = getOptions();
    boolean nativeTransport = options.getPreferNativeTransport();
    vertx = Vertx.vertx(options);
    if (nativeTransport) {
        assertTrue(vertx.isNativeTransportEnabled());
    }
}
 
Example #11
Source File: InMemoryUserStoreTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotGetUser_userEviction() throws InterruptedException {
    User user = new User();
    user.setId("user-id");
    user.setUsername("username");
    Vertx vertx = Vertx.vertx();
    InMemoryUserStore inMemoryUserStore = new InMemoryUserStore(vertx, 1000);
    inMemoryUserStore.add(user);
    Thread.sleep(3000l);
    User fetchedUser = inMemoryUserStore.get(user.getId());
    Assert.assertNull(fetchedUser);
    vertx.close();
}
 
Example #12
Source File: InMemoryUserStoreTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGetUser() throws InterruptedException {
    User user = new User();
    user.setId("user-id");
    user.setUsername("username");
    Vertx vertx = Vertx.vertx();
    InMemoryUserStore inMemoryUserStore = new InMemoryUserStore(vertx, 5000);
    inMemoryUserStore.add(user);
    Thread.sleep(3000l);
    User fetchedUser = inMemoryUserStore.get(user.getId());
    Assert.assertNotNull(fetchedUser);
    Assert.assertTrue("username".equals(fetchedUser.getUsername()));
    vertx.close();
}
 
Example #13
Source File: RxVertxTestBase.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
/**
 * Create a blank new clustered Vert.x instance with @{@code options} closed when tear down executes.
 */
protected void clusteredVertx(VertxOptions options, Handler<AsyncResult<Vertx>> ar) {
    if (created == null) {
        created = Collections.synchronizedList(new ArrayList<>());
    }
    Vertx.clusteredVertx(options, event -> {
        if (event.succeeded()) {
            created.add(event.result());
        }
        ar.handle(event);
    });
}
 
Example #14
Source File: RestApiTestBase.java    From vertx-postgresql-starter with MIT License 5 votes vote down vote up
protected void mockServer(int port, HttpMethod httpMethod, String routingPath, Handler<RoutingContext> handler, TestContext testContext) {
  vertx = new Vertx(rule.vertx());
  router = Router.router(vertx);

  if (httpMethod.equals(HttpMethod.POST) || httpMethod.equals(HttpMethod.PUT)) {
    router.route().handler(BodyHandler.create());
  }

  router.route(httpMethod, routingPath).handler(handler);

  vertx.createHttpServer().requestHandler(router::accept).listen(port, testContext.asyncAssertSuccess());
}
 
Example #15
Source File: WebClientsConfiguration.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private WebClient createWebClient(Vertx vertx, URL url) {

        final int port = url.getPort() != -1 ? url.getPort() : (HTTPS_SCHEME.equals(url.getProtocol()) ? 443 : 80);

        WebClientOptions options = new WebClientOptions()
                .setDefaultPort(port)
                .setDefaultHost(url.getHost())
                .setKeepAlive(true)
                .setMaxPoolSize(10)
                .setTcpKeepAlive(true)
                .setConnectTimeout(httpClientTimeout)
                .setSsl(url.getProtocol().equals(HTTPS_SCHEME));

        if (this.isProxyConfigured) {
            ProxyOptions proxyOptions = new ProxyOptions();
            proxyOptions.setType(ProxyType.valueOf(httpClientProxyType));
            if (HTTPS_SCHEME.equals(url.getProtocol())) {
                proxyOptions.setHost(httpClientProxyHttpsHost);
                proxyOptions.setPort(httpClientProxyHttpsPort);
                proxyOptions.setUsername(httpClientProxyHttpsUsername);
                proxyOptions.setPassword(httpClientProxyHttpsPassword);
            } else {
                proxyOptions.setHost(httpClientProxyHttpHost);
                proxyOptions.setPort(httpClientProxyHttpPort);
                proxyOptions.setUsername(httpClientProxyHttpUsername);
                proxyOptions.setPassword(httpClientProxyHttpPassword);
            }
            options.setProxyOptions(proxyOptions);
        }

        return WebClient.create(vertx, options);
    }
 
Example #16
Source File: VerticleTest.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
  super.setUp();
  vertx = new Vertx(super.vertx);
  startedCount = 0;
  stoppedCount = 0;
}
 
Example #17
Source File: VertxPluginRequestHandler.java    From redpipe with Apache License 2.0 5 votes vote down vote up
public VertxPluginRequestHandler(Vertx vertx, ResteasyDeployment deployment, String servletMappingPrefix, SecurityDomain domain, List<Plugin> plugins)
{
   this.vertx = vertx;
   this.dispatcher = new PluginRequestDispatcher((SynchronousDispatcher) deployment.getDispatcher(), deployment.getProviderFactory(), domain, plugins);
   this.servletMappingPrefix = servletMappingPrefix;
   appGlobals = AppGlobals.get();
}
 
Example #18
Source File: ProdMailer.java    From redpipe with Apache License 2.0 5 votes vote down vote up
public ProdMailer(Vertx vertx, JsonObject serverConfig) {
	MailConfig config = new MailConfig();
	config.setHostname(serverConfig.getString("smtp.hostname", MailConfig.DEFAULT_HOST));
	config.setPort(serverConfig.getInteger("smtp.port", MailConfig.DEFAULT_PORT));
	config.setUsername(serverConfig.getString("smtp.username"));
	config.setPassword(serverConfig.getString("smtp.password"));
	config.setKeepAlive(serverConfig.getBoolean("smtp.keepAlive", MailConfig.DEFAULT_KEEP_ALIVE));
	// make the default work on default linux installs
	config.setTrustAll(serverConfig.getBoolean("smtp.trustAll", true));
	config.setStarttls(StartTLSOptions.valueOf(serverConfig.getString("smtp.starttls", MailConfig.DEFAULT_TLS.name())));
	mailClient = MailClient.createShared(vertx, config);
}
 
Example #19
Source File: PgClientModule.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Provides
@Singleton
public PgClients pgClients(PgPoolOptions options, Vertx vertx) {
    List<PgClient> clients = new ArrayList<>();

    for (int i = 0; i < Runtime.getRuntime().availableProcessors(); i++) {
        clients.add(PgClient.pool(vertx, options));
    }

    return new PgClients(clients);
}
 
Example #20
Source File: AbstractSuperAPI.java    From rxjava2-lab with Apache License 2.0 5 votes vote down vote up
protected Flowable<Character> load() {
    Vertx vertx = Vertx.vertx();
    FileSystem fileSystem = vertx.fileSystem();
    return fileSystem.rxReadFile("src/main/resources/characters.json")
        .map(buffer -> buffer.toString())
        .map(content -> new JsonArray(content))
        .flatMapPublisher(array -> Flowable.fromIterable(array))
        .cast(JsonObject.class)
        .map(json -> json.mapTo(Character.class));
}
 
Example #21
Source File: Main.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    Vertx vertx = Vertx.vertx();

    vertx.rxDeployVerticle(Exercise1Verticle.class.getName())
        .flatMap(x -> vertx.rxDeployVerticle(Exercise2Verticle.class.getName()))
        .flatMap(x -> vertx.rxDeployVerticle(Exercise3Verticle.class.getName()))
        .subscribe();
}
 
Example #22
Source File: CdiPlugin.java    From redpipe with Apache License 2.0 5 votes vote down vote up
@Override
public Completable init() {
	return Completable.defer(() -> {
		// Setup the Vertx-CDI integration
		VertxExtension vertxExtension = CDI.current().select(VertxExtension.class).get();
		BeanManager beanManager = CDI.current().getBeanManager();
		// has to be done in a blocking thread
		Vertx vertx = AppGlobals.get().getVertx();
		return vertx.rxExecuteBlocking(future -> {
			vertxExtension.registerConsumers(vertx.getDelegate(), BeanManagerProxy.unwrap(beanManager).event());
			future.complete();
		}).ignoreElement();
	});
}
 
Example #23
Source File: WikiServer.java    From redpipe with Apache License 2.0 5 votes vote down vote up
@Override
protected SQLClient createDbClient(JsonObject config) {
	JsonObject myConfig = new JsonObject();
	if(config.containsKey("db_host"))
		myConfig.put("host", config.getString("db_host"));
	if(config.containsKey("db_port"))
		myConfig.put("port", config.getInteger("db_port"));
	if(config.containsKey("db_user"))
		myConfig.put("username", config.getString("db_user"));
	if(config.containsKey("db_pass"))
		myConfig.put("password", config.getString("db_pass"));
	if(config.containsKey("db_name"))
		myConfig.put("database", config.getString("db_name"));
	myConfig.put("max_pool_size", config.getInteger("db_max_pool_size", 30));
	
	Vertx vertx = AppGlobals.get().getVertx();
	AsyncSQLClient dbClient = PostgreSQLClient.createNonShared(vertx, myConfig);

	Configuration configuration = new DefaultConfiguration();
	configuration.set(SQLDialect.POSTGRES);

	PagesDao dao = new PagesDao(configuration, dbClient);
	
	AppGlobals.get().setGlobal(PagesDao.class, dao);
	
	return dbClient;
}
 
Example #24
Source File: QuasiFibers.java    From redpipe with Apache License 2.0 5 votes vote down vote up
public static FiberScheduler getContextScheduler() {
		Context context = Vertx.currentContext();
		if (context == null) {
//	        final Fiber parent = Fiber.currentFiber();
//	        if (parent == null)
//	            return DefaultFiberScheduler.getInstance();
//	        else
//	            return parent.getScheduler();
			throw new IllegalStateException("Not in context");
		}
		if (!context.isEventLoopContext()) {
			throw new IllegalStateException("Not on event loop");
		}
		// We maintain one scheduler per context
		FiberScheduler scheduler = context.get(Fibers.FIBER_SCHEDULER_CONTEXT_KEY);
		if (scheduler == null) {
			Thread eventLoop = Thread.currentThread();
			scheduler = new FiberExecutorScheduler("vertx.contextScheduler", command -> {
				if (Thread.currentThread() != eventLoop) {
					context.runOnContext(v -> command.run());
				} else {
					// Just run directly
					command.run();
				}
			});
			context.put(Fibers.FIBER_SCHEDULER_CONTEXT_KEY, scheduler);
		}
		return scheduler;
	}
 
Example #25
Source File: HelloResource.java    From redpipe with Apache License 2.0 5 votes vote down vote up
private Single<String> get(Vertx vertx, URI uri){
	WebClient client = WebClient.create(vertx);
	Single<HttpResponse<Buffer>> responseHandler = 
			client.get(uri.getPort(), uri.getHost(), uri.getPath()).rxSend();

	return responseHandler.map(response -> response.body().toString())
			.doAfterTerminate(() -> client.close());
}
 
Example #26
Source File: HelloResource.java    From redpipe with Apache License 2.0 5 votes vote down vote up
@Path("fiber")
@GET
public Single<String> helloFiber(@Context Vertx vertx,
		@Context UriInfo uriInfo) {
	return Fibers.fiber(() -> {
		String hello1 = Fibers.await(get(vertx, getURI(HelloResource::hello)));
		String hello2 = Fibers.await(get(vertx, getURI(HelloResource::helloReactive)));
		
		return hello1 + "\n" + hello2;
	});
}
 
Example #27
Source File: HelloResource.java    From redpipe with Apache License 2.0 5 votes vote down vote up
@Path("composed")
@GET
public Single<String> helloComposed(@Context Vertx vertx) {
	Single<String> request1 = get(vertx, getURI(HelloResource::hello));
	Single<String> request2 = get(vertx, getURI(HelloResource::helloReactive));
		
	return request1.zipWith(request2, (hello1, hello2) -> hello1 + "\n" + hello2);
}
 
Example #28
Source File: CoreTest.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
  super.setUp();
  vertx = new Vertx(super.vertx);
  java.nio.file.FileSystem fs = FileSystems.getDefault();
  pathSep = fs.getSeparator();
  File ftestDir = testFolder.newFolder();
  testDir = ftestDir.toString();
}
 
Example #29
Source File: Code3.java    From rxjava2-lab with Apache License 2.0 5 votes vote down vote up
static Flowable<Character> load() {
    Vertx vertx = Vertx.vertx();
    FileSystem fileSystem = vertx.fileSystem();
    return fileSystem.rxReadFile("src/main/resources/characters.json")
        .map(buffer -> buffer.toString())
        .map(content -> new JsonArray(content))
        .flatMapPublisher(array -> Flowable.fromIterable(array))
        .cast(JsonObject.class)
        .map(json -> json.mapTo(Character.class));
}
 
Example #30
Source File: PgClientFactory.java    From micronaut-sql with Apache License 2.0 5 votes vote down vote up
/**
 * Create a connection pool to the database configured with the {@link PgClientConfiguration }.
 * @param vertx The Vertx instance.
 * @return A pool of connections.
 */
private PgPool createClient(Vertx vertx) {
    PgClientConfiguration configuration = this.connectionConfiguration;
    String connectionUri = configuration.getUri();
    if (StringUtils.isNotEmpty(connectionUri)) {
        return PgPool.pool(vertx, connectionUri, configuration.poolOptions);
    } else {
        return PgPool.pool(vertx, configuration.connectOptions, configuration.poolOptions);
    }
}