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:ccc.cli.StringToDecConverterUtil.java

/**
 * Generates and stores decimal values for the values of the paragraphs
 * of type 'NUMBER'. The new values are stored in the value_decimal column.
        /*www .  j av  a 2s  .  c o m*/
 * @param connection The DB connection.
 */
public void convertParagraphs(final Connection connection) {
    LOG.info("Convert Paragraphs Started");
    Statement stmt = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {

        stmt = connection.createStatement();
        LOG.trace("Getting the paragraphs where type is 'NUMBER'");
        rs = stmt.executeQuery(GET_PARAGRAPHS_QUERY);

        if (rs != null && rs.next()) {
            LOG.debug("Processing result set");
            pstmt = connection.prepareStatement(UPDATE_PARAGRAPH);
            int totalparagraphs = 0;
            do {
                final String textNumber = rs.getString("value_text");
                final String pageId = rs.getString("page_revision_id");

                LOG.trace("Found " + textNumber + " for id " + pageId);

                // Conversion
                final BigDecimal decNumber = convert(textNumber);
                if (decNumber == null) {
                    LOG.warn("Failed to convert paragraph " + pageId + " with value " + textNumber);
                }

                pstmt.setBigDecimal(1, decNumber);
                pstmt.setString(2, pageId);
                pstmt.addBatch();
                totalparagraphs++;
            } while (rs.next());

            LOG.debug("Executing updates");
            pstmt.executeBatch();
            LOG.info("Processed " + totalparagraphs + " paragraphs");
            LOG.info("Finished");
        }
    } catch (final SQLException e) {
        LOG.fatal("An error occured while converting Strings to Decimal", e);
    } finally {
        LOG.info("Releasing the resources");
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(pstmt);
        DbUtils.closeQuietly(stmt);
    }
}

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

/**
 * Checks if some script have been elicited for a given hierarchy.
 * //from  www.  j  ava  2 s  . c  o  m
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param hierarchyId the hierarchy id.
 * @return true if the hierarchy has already been elicitate, else false.
 * @since July, 2011.
 * @throws ScriptSearchDAOException if an error occurs during the search.
 */
@Override
public boolean isScriptExistingFromHierarchyId(int hierarchyId) throws ScriptSearchDAOException {
    LOGGER.debug("isScriptExistingFromHierarchyId(" + hierarchyId + ").");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        return (Boolean) getQueryRunner().query(connection,
                "SELECT EXISTS ( SELECT script_id FROM script WHERE hierarchy_id = ? ) AS result ",
                new ScalarHandler("result"), new Object[] { hierarchyId });
    } catch (SQLException e) {
        throw new ScriptSearchDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}

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

/**
 * Retrieves the users number of a specific service.
 * //  w  w  w  .j  a  v  a2  s  .  c  o m
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param serviceId the service id.
 * @return the resulting number.
 * @since July, 2011.
 * @throws ServiceSearchDAOException if an error occurs during the search.
 */
@Override
public long getUsersNumberFromServiceId(int serviceId) throws ServiceSearchDAOException {
    LOGGER.debug("getUsersNumberFromServiceId(" + serviceId + ").");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        return (Long) getQueryRunner().query(connection,
                "SELECT COUNT(*) AS usersNb FROM user_service WHERE service_id = ? ",
                new ScalarHandler("usersNb"), new Object[] { serviceId });
    } catch (SQLException e) {
        throw new ServiceSearchDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}

From source file:azkaban.executor.JdbcExecutorLoader.java

@Override
public void updateExecutableFlow(ExecutableFlow flow) throws ExecutorManagerException {
    Connection connection = this.getConnection();

    try {/*ww  w  .j  a  va2s .  c  om*/
        updateExecutableFlow(connection, flow, defaultEncodingType);
    } finally {
        DbUtils.closeQuietly(connection);
    }
}

From source file:azkaban.trigger.JdbcTriggerLoader.java

@Override
public void addTrigger(Trigger t) throws TriggerLoaderException {
    logger.info("Inserting trigger " + t.toString() + " into db.");
    t.setLastModifyTime(System.currentTimeMillis());
    Connection connection = getConnection();
    try {/*from  ww  w . j a  v a2  s .c  o  m*/
        addTrigger(connection, t, defaultEncodingType);
    } catch (Exception e) {
        throw new TriggerLoaderException("Error uploading trigger", e);
    } finally {
        DbUtils.closeQuietly(connection);
    }
}

From source file:com.manydesigns.portofino.database.platforms.AbstractDatabasePlatform.java

public List<String> getSchemaNames(DatabaseMetaData databaseMetaData) throws SQLException {
    ResultSet rs = databaseMetaData.getSchemas();
    List<String> schemaNames = new ArrayList<String>();
    try {/*w  w  w.j  a v  a 2s.  co  m*/
        while (rs.next()) {
            String schemaName = rs.getString(TABLE_SCHEM);
            schemaNames.add(schemaName);
        }
    } finally {
        DbUtils.closeQuietly(rs);
    }
    return schemaNames;
}

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

/**
 * Retrieves the versions number of a specific project.
 * /*from  w  w  w  . j  ava 2s.  com*/
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param projectId the project id.
 * @return the resulting number.
 * @since July, 2011.
 * @throws VersionSearchDAOException if an error occurs during the search.
 */
@Override
public long getVersionsNumberFromProjectId(int projectId) throws VersionSearchDAOException {
    LOGGER.debug("getVersionsNumberFromProjectId(" + projectId + ").");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        return (Long) getQueryRunner().query(connection,
                "SELECT COUNT(*) AS versionsNb FROM version WHERE project_id = ? ",
                new ScalarHandler("versionsNb"), new Object[] { projectId });
    } catch (SQLException e) {
        throw new VersionSearchDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}

From source file:com.gs.obevo.db.impl.platforms.db2.Db2DeployerMainIT.java

@Test
public void testDeploy() throws Exception {
    int stepsToRun = 3; // this toggle is here to help w/ local testing

    DbDeployerAppContext dbDeployerAppContext = null;

    if (stepsToRun >= 0) {
        System.out.println("Running step 0");
        dbDeployerAppContext = getAppContext.valueOf(1);
        dbDeployerAppContext.cleanEnvironment().setupEnvInfra()
                .deploy(new MainDeployerArgs().reason("try1").deployExecutionAttributes(
                        Sets.immutable.with(new DeployExecutionAttributeImpl("A", "aval"),
                                new DeployExecutionAttributeImpl("B", "bval"))));
    }//from w  w w .j  a  v  a2s .com

    if (stepsToRun >= 1) {
        System.out.println("Running step 1");
        dbDeployerAppContext = getAppContext.valueOf(1);
        dbDeployerAppContext.deploy(new MainDeployerArgs().reason("try1a-noop")
                .deployExecutionAttributes(Sets.immutable.with(new DeployExecutionAttributeImpl("A", "aval"),
                        new DeployExecutionAttributeImpl("B", "bval"),
                        new DeployExecutionAttributeImpl("C", "cval"))));
    }

    if (stepsToRun >= 2) {
        System.out.println("Running step 2");
        dbDeployerAppContext = getAppContext.valueOf(2);
        dbDeployerAppContext.setupEnvInfra()
                .deploy(new MainDeployerArgs().reason("try2").deployExecutionAttributes(
                        Sets.immutable.with(new DeployExecutionAttributeImpl("C", "cval2"),
                                new DeployExecutionAttributeImpl("E", "eval"))));
    }

    if (stepsToRun >= 3) {
        System.out.println("Running step 3");
        dbDeployerAppContext = getAppContext.valueOf(3);
        dbDeployerAppContext.setupEnvInfra().deploy(new MainDeployerArgs().reason("try3")
                .deployExecutionAttributes(Sets.immutable.with(new DeployExecutionAttributeImpl("F", "fval"))));
    }

    String schema1 = "DEPLOY_TRACKER";
    MutableList<DeployExecution> executions = dbDeployerAppContext.getDeployExecutionDao()
            .getDeployExecutions(schema1).toSortedListBy(DeployExecution.TO_ID);
    assertThat(executions, hasSize(4));
    DeployExecution execution4 = dbDeployerAppContext.getDeployExecutionDao().getLatestDeployExecution(schema1);
    verifyExecution1(executions.get(0));
    verifyExecution1a(executions.get(1));
    verifyExecution2(executions.get(2));
    verifyExecution3(executions.get(3));
    verifyExecution3(execution4);

    JdbcHelper db2JdbcTemplate = new JdbcHelper();

    // Assert the columns which are available in table TEST_TABLE
    String schema = dbDeployerAppContext.getEnvironment().getPhysicalSchema("DEPLOY_TRACKER").getPhysicalName();
    String columnListSql = "select colname from syscat.COLUMNS where tabschema = '" + schema
            + "' AND tabname = 'TABLE_D'";
    Connection conn = ds.getConnection();
    try {
        List<String> columnsInTestTable = db2JdbcTemplate.query(conn, columnListSql,
                new ColumnListHandler<String>());
        Assert.assertEquals(Lists.mutable.with("D_ID"), FastList.newList(columnsInTestTable));
    } finally {
        DbUtils.closeQuietly(conn);
    }
}

From source file:com.mirth.connect.connectors.jdbc.DatabaseReceiver.java

@SuppressWarnings("unchecked")
@Override/* w  w  w.j a v a2 s. co  m*/
protected void poll() throws InterruptedException {
    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getSourceName(),
            ConnectionStatusEventType.POLLING));
    Object result = null;

    try {
        result = delegate.poll();

        if (isTerminated()) {
            return;
        }

        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getSourceName(), ConnectionStatusEventType.READING));

        // the result object will be a ResultSet or if JavaScript is used, we also allow the user to return a List<Map<String, Object>>
        if (result instanceof ResultSet) {
            processResultSet((ResultSet) result);
        } else if (result instanceof List) {
            // if the result object is a List, then assume it is a list of maps representing a row to process
            processResultList((List<Map<String, Object>>) result);
        } else {
            throw new DatabaseReceiverException("Unrecognized result: " + result.toString());
        }
    } catch (InterruptedException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Failed to poll for messages from the database in channel \""
                + ChannelController.getInstance().getDeployedChannelById(getChannelId()).getName() + "\"", e);
        eventController.dispatchEvent(
                new ErrorEvent(getChannelId(), getMetaDataId(), null, ErrorEventType.SOURCE_CONNECTOR,
                        getSourceName(), connectorProperties.getName(), null, e.getCause()));
        return;
    } finally {
        if (result instanceof ResultSet) {
            DbUtils.closeQuietly((ResultSet) result);
        }

        try {
            delegate.afterPoll();
        } catch (DatabaseReceiverException e) {
            logger.error("Error in channel \""
                    + ChannelController.getInstance().getDeployedChannelById(getChannelId()).getName() + "\": "
                    + e.getMessage(), ExceptionUtils.getRootCause(e));
            eventController.dispatchEvent(
                    new ErrorEvent(getChannelId(), getMetaDataId(), null, ErrorEventType.SOURCE_CONNECTOR,
                            getSourceName(), connectorProperties.getName(), null, e.getCause()));
        }

        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getSourceName(), ConnectionStatusEventType.IDLE));
    }
}

From source file:com.splicemachine.derby.impl.sql.execute.operations.CallStatementOperationIT.java

@Test
public void testCallGetTypeInfo() throws Exception {
    String[] expectedTypes = { "BIGINT", "LONG VARCHAR FOR BIT DATA", "VARCHAR () FOR BIT DATA",
            "CHAR () FOR BIT DATA", "LONG VARCHAR", "CHAR", "NUMERIC", "DECIMAL", "INTEGER", "SMALLINT",
            "FLOAT", "REAL", "DOUBLE", "VARCHAR", "BOOLEAN", "DATE", "TIME", "TIMESTAMP", "OBJECT", "BLOB",
            "CLOB", "XML" };
    Arrays.sort(expectedTypes);/*  w ww  .j  a  va2 s. c om*/

    CallableStatement cs = methodWatcher.prepareCall("call SYSIBM.SQLGETTYPEINFO(0,null)");
    ResultSet rs = cs.executeQuery();
    try {
        List<String> actual = new ArrayList<>(expectedTypes.length);
        while (rs.next()) {
            actual.add(rs.getString(1));
        }
        String[] actualArray = actual.toArray(new String[actual.size()]);
        Arrays.sort(actualArray);
        Assert.assertArrayEquals(expectedTypes, actualArray);
    } finally {
        DbUtils.closeQuietly(rs);
    }
}