Search in sources :

Example 61 with JsonArray

use of io.vertx.core.json.JsonArray in project vertx-examples by vert-x3.

the class Transaction method start.

@Override
public void start() throws Exception {
    JsonObject config = new JsonObject().put("url", "jdbc:hsqldb:mem:test?shutdown=true").put("driver_class", "org.hsqldb.jdbcDriver");
    String sql = "CREATE TABLE colors (" + "id INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1, INCREMENT BY 1) PRIMARY KEY, " + "name VARCHAR(255), " + "datetime TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP NOT NULL)";
    JDBCClient client = JDBCClient.createShared(vertx, config);
    // Connect to the database
    client.rxGetConnection().flatMap(conn -> conn.rxSetAutoCommit(false).toSingleDefault(false).flatMap(autoCommit -> conn.rxExecute(sql).toSingleDefault(true)).flatMap(executed -> conn.rxUpdateWithParams("INSERT INTO colors (name) VALUES (?)", new JsonArray().add("BLACK"))).flatMap(updateResult -> conn.rxUpdateWithParams("INSERT INTO colors (name) VALUES (?)", new JsonArray().add("WHITE"))).flatMap(updateResult -> conn.rxUpdateWithParams("INSERT INTO colors (name) VALUES (?)", new JsonArray().add("PURPLE"))).flatMap(updateResult -> conn.rxCommit().toSingleDefault(true).map(commit -> updateResult)).onErrorResumeNext(ex -> conn.rxRollback().toSingleDefault(true).onErrorResumeNext(ex2 -> Single.error(new CompositeException(ex, ex2))).flatMap(ignore -> Single.error(ex))).flatMap(updateResult -> conn.rxQuery("SELECT * FROM colors")).doAfterTerminate(conn::close)).subscribe(resultSet -> {
        // Subscribe to get the final result
        System.out.println("Results : " + resultSet.getRows());
    }, Throwable::printStackTrace);
}
Also used : JsonArray(io.vertx.core.json.JsonArray) CompositeException(io.reactivex.exceptions.CompositeException) JDBCClient(io.vertx.reactivex.ext.jdbc.JDBCClient) JsonObject(io.vertx.core.json.JsonObject) AbstractVerticle(io.vertx.reactivex.core.AbstractVerticle) Single(io.reactivex.Single) Runner(io.vertx.example.util.Runner) JsonArray(io.vertx.core.json.JsonArray) CompositeException(io.reactivex.exceptions.CompositeException) JsonObject(io.vertx.core.json.JsonObject) JDBCClient(io.vertx.reactivex.ext.jdbc.JDBCClient)

Example 62 with JsonArray

use of io.vertx.core.json.JsonArray in project vertx-examples by vert-x3.

the class JDBCExample method start.

@Override
public void start() throws Exception {
    final JDBCClient client = JDBCClient.createShared(vertx, new JsonObject().put("url", "jdbc:hsqldb:mem:test?shutdown=true").put("driver_class", "org.hsqldb.jdbcDriver").put("max_pool_size", 30));
    client.getConnection(conn -> {
        if (conn.failed()) {
            System.err.println(conn.cause().getMessage());
            return;
        }
        final SQLConnection connection = conn.result();
        connection.execute("create table test(id int primary key, name varchar(255))", res -> {
            if (res.failed()) {
                throw new RuntimeException(res.cause());
            }
            // insert some test data
            connection.execute("insert into test values(1, 'Hello')", insert -> {
                // query some data
                connection.query("select * from test", rs -> {
                    for (JsonArray line : rs.result().getResults()) {
                        System.out.println(line.encode());
                    }
                    // and close the connection
                    connection.close(done -> {
                        if (done.failed()) {
                            throw new RuntimeException(done.cause());
                        }
                    });
                });
            });
        });
    });
}
Also used : JsonArray(io.vertx.core.json.JsonArray) SQLConnection(io.vertx.ext.sql.SQLConnection) JDBCClient(io.vertx.ext.jdbc.JDBCClient) JsonObject(io.vertx.core.json.JsonObject)

Example 63 with JsonArray

use of io.vertx.core.json.JsonArray in project vertx-examples by vert-x3.

the class Server method handleAddProduct.

private void handleAddProduct(RoutingContext routingContext) {
    HttpServerResponse response = routingContext.response();
    SQLConnection conn = routingContext.get("conn");
    JsonObject product = routingContext.getBodyAsJson();
    conn.updateWithParams("INSERT INTO products (name, price, weight) VALUES (?, ?, ?)", new JsonArray().add(product.getString("name")).add(product.getFloat("price")).add(product.getInteger("weight")), query -> {
        if (query.failed()) {
            sendError(500, response);
        } else {
            response.end();
        }
    });
}
Also used : JsonArray(io.vertx.core.json.JsonArray) HttpServerResponse(io.vertx.core.http.HttpServerResponse) SQLConnection(io.vertx.ext.sql.SQLConnection) JsonObject(io.vertx.core.json.JsonObject)

Example 64 with JsonArray

use of io.vertx.core.json.JsonArray in project vertx-examples by vert-x3.

the class Server method handleGetProduct.

private void handleGetProduct(RoutingContext routingContext) {
    String productID = routingContext.request().getParam("productID");
    HttpServerResponse response = routingContext.response();
    if (productID == null) {
        sendError(400, response);
    } else {
        SQLConnection conn = routingContext.get("conn");
        conn.queryWithParams("SELECT id, name, price, weight FROM products where id = ?", new JsonArray().add(Integer.parseInt(productID)), query -> {
            if (query.failed()) {
                sendError(500, response);
            } else {
                if (query.result().getNumRows() == 0) {
                    sendError(404, response);
                } else {
                    response.putHeader("content-type", "application/json").end(query.result().getRows().get(0).encode());
                }
            }
        });
    }
}
Also used : JsonArray(io.vertx.core.json.JsonArray) HttpServerResponse(io.vertx.core.http.HttpServerResponse) SQLConnection(io.vertx.ext.sql.SQLConnection)

Example 65 with JsonArray

use of io.vertx.core.json.JsonArray in project vertx-examples by vert-x3.

the class Server method handleListProducts.

private void handleListProducts(RoutingContext routingContext) {
    HttpServerResponse response = routingContext.response();
    SQLConnection conn = routingContext.get("conn");
    conn.query("SELECT id, name, price, weight FROM products", query -> {
        if (query.failed()) {
            sendError(500, response);
        } else {
            JsonArray arr = new JsonArray();
            query.result().getRows().forEach(arr::add);
            routingContext.response().putHeader("content-type", "application/json").end(arr.encode());
        }
    });
}
Also used : JsonArray(io.vertx.core.json.JsonArray) HttpServerResponse(io.vertx.core.http.HttpServerResponse) SQLConnection(io.vertx.ext.sql.SQLConnection)

Aggregations

JsonArray (io.vertx.core.json.JsonArray)535 JsonObject (io.vertx.core.json.JsonObject)379 Test (org.junit.Test)185 List (java.util.List)69 ArrayList (java.util.ArrayList)66 Map (java.util.Map)52 Handler (io.vertx.core.Handler)49 HashMap (java.util.HashMap)42 Collectors (java.util.stream.Collectors)42 Test (org.junit.jupiter.api.Test)41 Future (io.vertx.core.Future)37 IOException (java.io.IOException)35 AsyncResult (io.vertx.core.AsyncResult)34 Buffer (io.vertx.core.buffer.Buffer)33 HttpURLConnection (java.net.HttpURLConnection)30 StandardCharsets (java.nio.charset.StandardCharsets)29 RoutingContext (io.vertx.ext.web.RoutingContext)26 Objects (java.util.Objects)25 Instant (java.time.Instant)24 Rule (org.junit.Rule)22