Example usage for org.apache.commons.dbutils DbUtils closeQuietly

List of usage examples for org.apache.commons.dbutils DbUtils closeQuietly

Introduction

In this page you can find the example usage for org.apache.commons.dbutils DbUtils closeQuietly.

Prototype

public static void closeQuietly(Statement stmt) 

Source Link

Document

Close a Statement, avoid closing if null and hide any SQLExceptions that occur.

Usage

From source file:de.iritgo.aktario.jdbc.StoreUser.java

/**
 * Perform the command./*from w w w  .  jav  a  2s. c o m*/
 */
public void perform() {
    if (properties.get("id") == null) {
        Log.logError("persist", "StoreUser", "Missing unique id for the user to store");

        return;
    }

    UserRegistry userRegistry = Server.instance().getUserRegistry();
    long userId = ((Long) properties.get("id")).longValue();
    User user = userRegistry.getUser(userId);

    if (user == null) {
        Log.logError("persist", "StoreUser", "Unable to find user with id " + userId);

        return;
    }

    JDBCManager jdbcManager = (JDBCManager) Engine.instance().getManager("persist.JDBCManager");
    DataSource dataSource = jdbcManager.getDefaultDataSource();

    Connection connection = null;
    PreparedStatement stmt = null;

    try {
        connection = dataSource.getConnection();

        stmt = connection.prepareStatement("delete from IritgoUser where id=?");
        stmt.setLong(1, userId);
        stmt.execute();
        stmt.close();

        String userSql = "insert into IritgoUser (id, name, password, email) " + " values (?, ?, ?, ?)";

        stmt = connection.prepareStatement(userSql);
        stmt.setLong(1, userId);
        stmt.setString(2, user.getName());
        stmt.setString(3, user.getPassword());
        stmt.setString(4, user.getEmail());
        stmt.execute();
        stmt.close();

        stmt = connection.prepareStatement("delete from IritgoNamedObjects where userId=?");
        stmt.setLong(1, userId);
        stmt.execute();
        stmt.close();

        Log.logVerbose("persist", "StoreUser", "INSERT USER " + userId + " |" + userSql + "|");
    } catch (SQLException x) {
        Log.logError("persist", "StoreUser", "Error while storing user with id " + userId + ": " + x);
    } finally {
        DbUtils.closeQuietly(stmt);
        DbUtils.closeQuietly(connection);
    }
}

From source file:com.splicemachine.derby.test.framework.SpliceUserWatcher.java

public void dropUser(String userName) {
    Connection connection = null;
    PreparedStatement statement = null;
    try {//w ww  .  j  a  v a 2s .c om
        connection = SpliceNetConnection.getConnection();
        statement = connection.prepareStatement("select username from sys.sysusers where username = ?");
        statement.setString(1, userName.toUpperCase());
        ResultSet rs = statement.executeQuery();
        if (rs.next()) {
            statement = connection.prepareStatement("call syscs_util.syscs_drop_user(?)");
            statement.setString(1, userName);
            statement.execute();
        }
    } catch (Exception e) {
        LOG.error("error Creating " + e.getMessage());
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        DbUtils.closeQuietly(statement);
        DbUtils.commitAndCloseQuietly(connection);
    }
}

From source file:com.gs.obevo.dbmetadata.impl.dialects.MsSqlMetadataDialect.java

@Override
public void setSchemaOnConnection(Connection conn, String schema) {
    PreparedStatement ps = null;/*from   w  w w  .  j  ava 2s  .c  o m*/
    try {
        ps = conn.prepareStatement("use " + schema);
        ps.executeUpdate();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        DbUtils.closeQuietly(ps);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.jdbc.JdbcReaderExample.java

@Test
public void hsqldbExampleTest() throws SQLException, UIMAException, IOException {
    // Setup in-memory database.
    Connection conn = null;/*w w  w.  j ava2 s. c o  m*/
    Statement stmnt = null;
    try {
        conn = DriverManager.getConnection("jdbc:hsqldb:mem:/" + DB_NAME, DB_USER, DB_PASS);
        stmnt = conn.createStatement();
        stmnt.addBatch("CREATE TABLE " + TBL_NAME + " (title varchar(50), text varchar(100));");
        stmnt.addBatch("INSERT INTO " + TBL_NAME + " (title, text) VALUES ('title1', 'text...1');");
        stmnt.addBatch("INSERT INTO " + TBL_NAME + " (title, text) VALUES ('title2', 'text...2');");
        stmnt.addBatch("INSERT INTO " + TBL_NAME + " (title, text) VALUES ('title3', 'text...3');");
        stmnt.addBatch("INSERT INTO " + TBL_NAME + " (title, text) VALUES ('title4', 'text...4');");
        stmnt.executeBatch();
    } finally {
        DbUtils.closeQuietly(stmnt);
        DbUtils.closeQuietly(conn);
    }
    // Read out with JdbcReader.
    CollectionReader jdbcReader = CollectionReaderFactory.createReader(JdbcReader.class,
            JdbcReader.PARAM_DATABASE, "test_db", JdbcReader.PARAM_USER, "root", JdbcReader.PARAM_PASSWORD, "",
            JdbcReader.PARAM_QUERY, query, JdbcReader.PARAM_DRIVER, "org.hsqldb.jdbc.JDBCDriver",
            JdbcReader.PARAM_CONNECTION, "jdbc:hsqldb:mem:");

    int i = 1;
    while (jdbcReader.hasNext()) {
        // Does it still have a next row?
        jdbcReader.hasNext();
        // Really?
        jdbcReader.hasNext();

        CAS cas = JCasFactory.createJCas().getCas();
        jdbcReader.getNext(cas);
        Assert.assertEquals("title" + i, DocumentMetaData.get(cas).getDocumentTitle());
        Assert.assertEquals("text..." + i, cas.getDocumentText());
        i++;
    }
}

From source file:com.gs.obevo.db.impl.core.deploy.CsvStaticDataDeployerTest.java

@After
public void teardown() {
    DbUtils.closeQuietly(conn);

}

From source file:com.gs.obevo.db.impl.platforms.sybasease.AseEnvironmentInfraSetup.java

@Override
public void setupEnvInfra(boolean failOnSetupException) {
    Connection conn = null;//  w w w  .  j a  va  2  s.  c  o  m
    try {
        conn = ds.getConnection();
        for (PhysicalSchema schema : env.getPhysicalSchemas()) {
            LOG.info("Verifying existence of Sybase groups and users in database {} prior to deployment",
                    schema);
            setupGroups(conn, schema, failOnSetupException);
            setupUsers(conn, schema, failOnSetupException);
        }
    } catch (SQLException e) {
        if (failOnSetupException) {
            throw new DataAccessException(e);
        } else {
            LOG.warn("Env Infra Setup connection failed", e);
            deployMetricsCollector
                    .addMetric(DeployMetrics.WARNINGS_PREFIX + ".aseEnvInfraSetupConnectionFailure", true);
            return;
        }
    } finally {
        DbUtils.closeQuietly(conn);
    }
}

From source file:com.gs.obevo.db.impl.platforms.hsql.HsqlDeployerTest.java

@Test
public void testUnitTestDeploy() throws SQLException {
    DbDeployerAppContext context = UnitTestDbBuilder.newBuilder().setEnvName("test2")
            .setDbPlatform(new HsqlDbPlatform()).setSourcePath("platforms/hsql").setDbServer("HsqlCustomName")
            .buildContext();/*from  ww w.j  av  a 2 s.  c o  m*/
    context.setupEnvInfra();

    // run it twice to ensure that we can drop the schema
    context.cleanAndDeploy();
    context.cleanAndDeploy();

    DbEnvironment env = context.getEnvironment();
    System.out.println("Created env at " + env.getJdbcUrl());
    int result;

    this.setup(context);
    Connection conn = context.getDataSource().getConnection();
    try {
        result = this.jdbc.queryForInt(conn, "select count(*) from SCHEMA1.TABLE_A");
        assertEquals(3, result);
        result = this.jdbc.queryForInt(conn, "select count(*) from SCHEMA1.VIEW1");
        assertEquals(3, result);
    } finally {
        DbUtils.closeQuietly(conn);
    }
}

From source file:ca.qc.adinfo.rouge.achievement.db.AchievementDb.java

public static boolean createAchievement(DBManager dbManager, String key, String name, int pointValue,
        double total) {

    Connection connection = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;/*from   w  ww  .ja va 2  s.c om*/
    String sql = null;

    sql = "INSERT INTO rouge_achievements (`key`, `name`, `point_value`, `total`) " + " VALUES (?, ?, ?, ?);";

    try {
        connection = dbManager.getConnection();
        stmt = connection.prepareStatement(sql);

        stmt.setString(1, key);
        stmt.setString(2, name);
        stmt.setInt(3, pointValue);
        stmt.setDouble(4, total);

        int ret = stmt.executeUpdate();

        return (ret > 0);

    } catch (SQLException e) {
        log.error(stmt);
        log.error(e);
        return false;

    } finally {

        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(stmt);
        DbUtils.closeQuietly(connection);
    }

}

From source file:com.che.software.testato.domain.dao.jdbc.impl.MatrixItemDAO.java

/**
 * Checks if a comparison matrix is ready to be prioritize. In other words,
 * checks if a matrix item exists without value for a given matrix (i.e. a
 * given iteration assignment).//from   w  w  w  .  j  a  v a 2s . co  m
 * 
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param iterationAssignmentId the given iteration assignment id.
 * @return true if the matrix is complete, else false.
 * @since August, 2011.
 * @throws MatrixItemSearchDAOException if an error occurs during the
 *         search.
 */
@Override
public boolean isComparisonMatrixComplete(int iterationAssignmentId) throws MatrixItemSearchDAOException {
    LOGGER.debug("isComparisonMatrixComplete(" + iterationAssignmentId + ").");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        return (Boolean) getQueryRunner().query(connection,
                "SELECT NOT EXISTS( SELECT comparison_matrix_item FROM comparisonMatrixItem WHERE iteration_assignment_id = ? AND value IS NULL ) AS result ",
                new ScalarHandler("result"), new Object[] { iterationAssignmentId });
    } catch (SQLException e) {
        throw new MatrixItemSearchDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}

From source file:com.manydesigns.portofino.model.database.JdbcConnectionProvider.java

public void releaseConnection(Connection conn) {
    DbUtils.closeQuietly(conn);
}