io.vertx.reactivex.ext.jdbc.JDBCClient Java Examples

The following examples show how to use io.vertx.reactivex.ext.jdbc.JDBCClient. 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: AuditVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 6 votes vote down vote up
private Single<JDBCClient> initializeDatabase(JDBCClient client, boolean drop) {
    // TODO - Initialize the database and return the JDBC client
    // ----
    // The database initialization is a multi-step process:
    // 1. Retrieve the connection
    // 2. Drop the table is exist
    // 3. Create the table
    // 4. Close the connection (in any case)
    // To handle such a process, we are going to create an RxJava Single and compose it with the RxJava flatMap operation:
    // retrieve the connection -> drop table -> create table -> close the connection
    // For this we use `Func1<X, Single<R>>`that takes a parameter `X` and return a `Single<R>` object.

    return Single.error(new UnsupportedOperationException("Not implemented yet"));
    // ----

}
 
Example #2
Source File: AuditVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
/**
 * Starts the verticle asynchronously. The the initialization is completed, it calls
 * `complete()` on the given {@link Future} object. If something wrong happens,
 * `fail` is called.
 *
 * @param future the future to indicate the completion
 */
@Override
public void start(Future<Void> future) {
    // creates the jdbc client.

    ServiceDiscovery.create(vertx, discovery -> {

        // Discover and configure the database.
        Single<JDBCClient> jdbc = JDBCDataSource.rxGetJDBCClient(discovery,
            svc -> svc.getName().equals("audit-database"),
            getDatabaseConfiguration()
        ).doOnSuccess(jdbcClient -> this.jdbc = jdbcClient);

        // TODO
        // ----

        Single<MessageConsumer<JsonObject>> readySingle = Single
            .error(new UnsupportedOperationException("Not implemented yet"));

        // ----

        // signal a verticle start failure
        readySingle.doOnSuccess(consumer -> {
            // on success we set the handler that will store message in the database
            consumer.handler(message -> storeInDatabase(message.body()));
        }).subscribe(consumer -> {
            // complete the verticle start with a success
            future.complete();
            // indicate our readiness state
            ready = true;
        }, future::fail);
    });


}
 
Example #3
Source File: AuditVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
/**
 * Starts the verticle asynchronously. The the initialization is completed, it calls
 * `complete()` on the given {@link Future} object. If something wrong happens,
 * `fail` is called.
 *
 * @param future the future to indicate the completion
 */
@Override
public void start(Future<Void> future) {
    // creates the jdbc client.

    ServiceDiscovery.create(vertx, discovery -> {

        // Discover and configure the database.
        Single<JDBCClient> jdbc = JDBCDataSource.rxGetJDBCClient(discovery,
            svc -> svc.getName().equals("audit-database"),
            getDatabaseConfiguration()
        ).doOnSuccess(jdbcClient -> this.jdbc = jdbcClient);

        // TODO
        // ----

        Single<JDBCClient> databaseReady = jdbc
            .flatMap(client -> initializeDatabase(client, true));
        Single<HttpServer> httpServerReady = configureTheHTTPServer();
        Single<MessageConsumer<JsonObject>> messageConsumerReady = retrieveThePortfolioMessageSource();

        Single<MessageConsumer<JsonObject>> readySingle = Single.zip(databaseReady, httpServerReady,
            messageConsumerReady, (db, http, consumer) -> consumer);

        // ----

        // signal a verticle start failure
        readySingle.doOnSuccess(consumer -> {
            // on success we set the handler that will store message in the database
            consumer.handler(message -> storeInDatabase(message.body()));
        }).subscribe(consumer -> {
            // complete the verticle start with a success
            future.complete();
            ready = true;
        }, future::fail);
    });


}
 
Example #4
Source File: SQLTestBase.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
  super.setUp();
  client = new JDBCClient(io.vertx.ext.jdbc.JDBCClient.create(vertx, config));
  client.rxGetConnection().flatMapCompletable(conn -> {
    Completable setup = conn.rxExecute("drop table folks if exists")
      .andThen(conn.rxExecute("create table folks (firstname varchar(255) not null)"));
    for (String name : NAMES) {
      setup = setup.andThen(conn.rxExecute(String.format(INSERT_FOLK_SQL, name)));
    }
    return setup.doFinally(conn::close);
  }).blockingAwait();
}
 
Example #5
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 #6
Source File: Server.java    From redpipe with Apache License 2.0 4 votes vote down vote up
protected SQLClient createDbClient(JsonObject config) {
	return JDBCClient.createNonShared(vertx, new JsonObject()
			.put("url", config.getString("db_url", "jdbc:hsqldb:file:db/wiki"))
			.put("driver_class", config.getString("db_driver", "org.hsqldb.jdbcDriver"))
			.put("max_pool_size", config.getInteger("db_max_pool_size", 30)));
}
 
Example #7
Source File: AuditVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 4 votes vote down vote up
private Single<JDBCClient> initializeDatabase(JDBCClient client, boolean drop) {
    // TODO - Initialize the database and return the JDBC client
    // ----
    // The database initialization is a multi-step process:
    // 1. Retrieve the connection
    // 2. Drop the table is exist
    // 3. Create the table
    // 4. Close the connection (in any case)
    // To handle such a process, we are going to create an RxJava Single and compose it with the RxJava flatMap operation:
    // retrieve the connection -> drop table -> create table -> close the connection
    // For this we use `Func1<X, Single<R>>`that takes a parameter `X` and return a `Single<R>` object.

    // This is the starting point of our operations
    // This single will be completed when the connection with the database is established.
    // We are going to use this single as a reference on the connection to close it.
    Single<SQLConnection> connectionRetrieved = client.rxGetConnection();

    // Ok, now it's time to chain all these actions (2 to 4):
    return connectionRetrieved
        .flatMap(conn -> {
            // When the connection is retrieved

            // Prepare the batch
            List<String> batch = new ArrayList<>();
            if (drop) {
                // When the table is dropped, we recreate it
                batch.add(DROP_STATEMENT);
            }
            // Just create the table
            batch.add(CREATE_TABLE_STATEMENT);

            // We compose with a statement batch
            Single<List<Integer>> next = conn.rxBatch(batch);

            // Whatever the result, if the connection has been retrieved, close it
            return next.doAfterTerminate(conn::close);
        })
        .map(list -> client);
    // ----

}
 
Example #8
Source File: JdbcTodoService.java    From vertx-blueprint-todo-backend with Apache License 2.0 4 votes vote down vote up
public JdbcTodoService(Vertx vertx, JsonObject config) {
  this.vertx = vertx;
  this.config = config;
  this.client = JDBCClient.createShared(vertx, config);
}
 
Example #9
Source File: UsingConnectionSafetyTest.java    From vertx-rx with Apache License 2.0 4 votes vote down vote up
@Override
public void setUp() throws Exception {
  super.setUp();
  client = new JDBCClient(io.vertx.ext.jdbc.JDBCClient.create(vertx, config));
}