Search in sources :

Example 21 with Handle

use of jnc.platform.win32.Handle in project syndesis by syndesisio.

the class StoredSettings method withTransaction.

private void withTransaction(Consumer<Handle> cb) {
    try (Handle h = dbi.open()) {
        try {
            h.begin();
            cb.accept(h);
            h.commit();
        } catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") RuntimeException e) {
            h.rollback();
            throw e;
        }
    }
}
Also used : Handle(org.skife.jdbi.v2.Handle)

Example 22 with Handle

use of jnc.platform.win32.Handle in project syndesis by syndesisio.

the class SqlJsonDB method getAsStreamingOutput.

@Override
@SuppressWarnings({ "PMD.ExcessiveMethodLength", "PMD.NPathComplexity" })
public Consumer<OutputStream> getAsStreamingOutput(String path, GetOptions options) {
    GetOptions o;
    if (options != null) {
        o = options;
    } else {
        o = new GetOptions();
    }
    // Lets normalize the path a bit
    String baseDBPath = JsonRecordSupport.convertToDBPath(path);
    String like = baseDBPath + "%";
    GetOptions.Order order = o.order();
    if (order == null) {
        order = GetOptions.Order.ASC;
    }
    Consumer<OutputStream> result = null;
    final Handle h = dbi.open();
    try {
        StringBuilder sql = new StringBuilder(250);
        // Creating the iterator could fail with a runtime exception,
        ArrayList<Consumer<Query<Map<String, Object>>>> binds = new ArrayList<>();
        if (o.filter() == null) {
            sql.append("select path,value,ovalue from jsondb where path LIKE :like");
        } else {
            sql.append("SELECT path,value,ovalue FROM jsondb A INNER JOIN (");
            SqlExpressionBuilder.create(this, o.filter(), baseDBPath).build(sql, binds);
            sql.append(") B ON A.path LIKE B.match_path||'%'");
        }
        if (o.startAfter() != null) {
            String startAfter = validateKey(o.startAfter());
            if (o.order() == GetOptions.Order.DESC) {
                sql.append(" and path <= :startAfter");
                binds.add(query -> {
                    String bindPath = baseDBPath + startAfter;
                    query.bind("startAfter", bindPath);
                });
            } else {
                sql.append(" and path >= :startAfter");
                binds.add(query -> {
                    String bindPath = baseDBPath + incrementKey(startAfter);
                    query.bind("startAfter", bindPath);
                });
            }
        }
        if (o.startAt() != null) {
            String startAt = validateKey(o.startAt());
            if (o.order() == GetOptions.Order.DESC) {
                sql.append(" and path < :startAt");
                binds.add(query -> {
                    String bindPath = baseDBPath + incrementKey(startAt);
                    query.bind("startAt", bindPath);
                });
            } else {
                sql.append(" and path >= :startAt");
                binds.add(query -> {
                    String bindPath = baseDBPath + startAt;
                    query.bind("startAt", bindPath);
                });
            }
        }
        if (o.endAt() != null) {
            String endAt = validateKey(o.endAt());
            if (o.order() == GetOptions.Order.DESC) {
                sql.append(" and path > :endAt");
                binds.add(query -> {
                    String value = baseDBPath + endAt;
                    query.bind("endAt", value);
                });
            } else {
                sql.append(" and path < :endAt");
                binds.add(query -> {
                    String bindPath = baseDBPath + incrementKey(endAt);
                    query.bind("endAt", bindPath);
                });
            }
        }
        if (o.endBefore() != null) {
            String endBefore = validateKey(o.endBefore());
            if (o.order() == GetOptions.Order.DESC) {
                sql.append(" and path >= :endBefore");
                binds.add(query -> {
                    String value = baseDBPath + incrementKey(endBefore);
                    query.bind("endBefore", value);
                });
            } else {
                sql.append(" and path < :endBefore");
                binds.add(query -> {
                    String value = baseDBPath + endBefore;
                    query.bind("endBefore", value);
                });
            }
        }
        sql.append(" order by path ").append(order);
        Query<Map<String, Object>> query = h.createQuery(sql.toString()).bind("like", like);
        for (Consumer<Query<Map<String, Object>>> bind : binds) {
            bind.accept(query);
        }
        ResultIterator<JsonRecord> iterator = query.map(JsonRecordMapper.INSTANCE).iterator();
        try {
            // At this point we know if we can produce results..
            if (iterator.hasNext()) {
                result = output -> {
                    try (JsonRecordConsumer toJson = new JsonRecordConsumer(baseDBPath, output, o)) {
                        while (!toJson.isClosed() && iterator.hasNext()) {
                            toJson.accept(iterator.next());
                        }
                    } catch (IOException e) {
                        throw new JsonDBException(e);
                    } finally {
                        iterator.close();
                        h.close();
                    }
                };
            }
        } finally {
            // if we are producing results, then defer closing the iterator
            if (result == null) {
                iterator.close();
            }
        }
    } finally {
        // if we are producing results, then defer closing the handle
        if (result == null) {
            h.close();
        }
    }
    return result;
}
Also used : Query(org.skife.jdbi.v2.Query) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) JsonDBException(io.syndesis.server.jsondb.JsonDBException) IOException(java.io.IOException) GetOptions(io.syndesis.server.jsondb.GetOptions) Handle(org.skife.jdbi.v2.Handle) Consumer(java.util.function.Consumer) Map(java.util.Map)

Example 23 with Handle

use of jnc.platform.win32.Handle in project syndesis by syndesisio.

the class SqlJsonDB method withTransaction.

private void withTransaction(Consumer<Handle> cb) {
    try (Handle h = dbi.open()) {
        try {
            h.begin();
            cb.accept(h);
            h.commit();
        } catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") RuntimeException e) {
            h.rollback();
            throw e;
        }
    }
}
Also used : Handle(org.skife.jdbi.v2.Handle)

Example 24 with Handle

use of jnc.platform.win32.Handle in project syndesis by syndesisio.

the class SqlFileStore method doReadDerby.

/**
 * Derby does not allow to read from the blob after the connection has been closed.
 * It also requires an outcome of commit/rollback.
 */
@SuppressWarnings("PMD.EmptyCatchBlock")
private InputStream doReadDerby(String path) {
    Handle h = dbi.open();
    try {
        h.getConnection().setAutoCommit(false);
        List<Map<String, Object>> res = h.select("SELECT data FROM filestore WHERE path=?", path);
        Optional<Blob> blob = res.stream().map(row -> row.get("data")).map(Blob.class::cast).findFirst();
        if (blob.isPresent()) {
            return new HandleCloserInputStream(h, blob.get().getBinaryStream());
        } else {
            h.commit();
            h.close();
            return null;
        }
    } catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") Exception e) {
        // Do cleanup
        try {
            h.rollback();
        } catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") Exception ex) {
        // ignore
        }
        IOUtils.closeQuietly(h);
        throw DaoException.launderThrowable(e);
    }
}
Also used : Blob(java.sql.Blob) Map(java.util.Map) SQLException(java.sql.SQLException) IOException(java.io.IOException) CallbackFailedException(org.skife.jdbi.v2.exceptions.CallbackFailedException) DaoException(io.syndesis.server.dao.DaoException) Handle(org.skife.jdbi.v2.Handle)

Example 25 with Handle

use of jnc.platform.win32.Handle in project providence by morimekta.

the class TestDatabase method dumpInternal.

@VisibleForTesting
private void dumpInternal(String table) throws IOException {
    List<List<String>> tableValues = new ArrayList<>();
    if (dbi == null) {
        System.err.println("Trying to dump '" + table + "' of not started database");
        return;
    }
    try (Handle h = this.dbi.open()) {
        List<Map<String, Object>> rs = h.createQuery("SELECT * FROM " + table.toUpperCase(Locale.US)).list();
        List<String> cols = new ArrayList<>();
        for (Map<String, Object> rowResult : rs) {
            if (cols.isEmpty()) {
                List<String> header = new ArrayList<>();
                for (String key : new TreeSet<>(rowResult.keySet())) {
                    cols.add(key);
                    header.add(key);
                }
                tableValues.add(header);
            }
            List<String> row = new ArrayList<>();
            for (String key : cols) {
                row.add(String.valueOf(rowResult.get(key)));
            }
            tableValues.add(row);
        }
    }
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.err, "UTF-8"));
    writer.println("Table Dump: " + table);
    prettyPrintTable(writer, tableValues);
    writer.flush();
}
Also used : ArrayList(java.util.ArrayList) ResourceUtils.getResourceAsString(net.morimekta.testing.ResourceUtils.getResourceAsString) Handle(org.skife.jdbi.v2.Handle) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) List(java.util.List) OutputStreamWriter(java.io.OutputStreamWriter) Map(java.util.Map) PrintWriter(java.io.PrintWriter) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Aggregations

Handle (org.skife.jdbi.v2.Handle)103 DBI (org.skife.jdbi.v2.DBI)28 Before (org.junit.Before)21 IOException (java.io.IOException)18 List (java.util.List)17 DataSourceFactory (io.dropwizard.db.DataSourceFactory)15 DBIFactory (io.dropwizard.jdbi.DBIFactory)15 SQLException (java.sql.SQLException)15 Map (java.util.Map)14 Test (org.junit.Test)14 Test (org.testng.annotations.Test)14 DateTime (org.joda.time.DateTime)13 ArrayList (java.util.ArrayList)11 TransactionStatus (org.skife.jdbi.v2.TransactionStatus)11 ResultSet (java.sql.ResultSet)10 ImmutableList (com.google.common.collect.ImmutableList)8 UUID (java.util.UUID)8 CallbackFailedException (org.skife.jdbi.v2.exceptions.CallbackFailedException)7 ImmutableSet (com.google.common.collect.ImmutableSet)6 Set (java.util.Set)6