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:com.che.software.testato.domain.dao.jdbc.impl.IterationDAO.java

/**
 * Creates the next iteration (both analytical and selective) for a given
 * prioritization.//w w w  . jav a  2s. c  om
 * 
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param prioritization the given prioritization.
 * @param scripts the scripts to use for this depth.
 * @since July, 2011.
 * @throws IterationCreationDAOException if an error occurs during the
 *         creation.
 */
@Override
public void createNextIteration(Prioritization prioritization, List<Script> scripts)
        throws IterationCreationDAOException {
    LOGGER.debug("createNextIteration(" + prioritization.getPrioritizationId() + ").");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        connection.setAutoCommit(false);
        getQueryRunner().update(connection,
                "INSERT INTO iteration(iteration_id, prioritization_id) VALUES(nextval('iteration_seq'), ?) ",
                new Object[] { prioritization.getPrioritizationId() });
        Integer createdIterationId = (Integer) getQueryRunner().query(connection,
                "SELECT MAX(iteration_id)::int AS iterationId FROM iteration ",
                new ScalarHandler("iterationId"));
        getQueryRunner().update(connection,
                "INSERT INTO iteration_assignment(iteration_assignment_id, criterion_type, iteration_id, analytical_prioritization_status) VALUES(nextval('iteration_assignment_seq'), ?, ?, ?) ",
                new Object[] { CriterionTypes.COST.name(), createdIterationId,
                        AssignmentStatus.NOT_ASSIGNED.name() });
        createComparisonMatrixItem(connection, scripts,
                (Integer) getQueryRunner().query(connection,
                        "SELECT MAX(iteration_assignment_id)::int AS result FROM iteration_assignment ",
                        new ScalarHandler("result")));
        getQueryRunner().update(connection,
                "INSERT INTO iteration_assignment(iteration_assignment_id, criterion_type, iteration_id, analytical_prioritization_status) VALUES(nextval('iteration_assignment_seq'), ?, ?, ?) ",
                new Object[] { CriterionTypes.FIT.name(), createdIterationId,
                        AssignmentStatus.NOT_ASSIGNED.name() });
        createComparisonMatrixItem(connection, scripts,
                (Integer) getQueryRunner().query(connection,
                        "SELECT MAX(iteration_assignment_id)::int AS result FROM iteration_assignment ",
                        new ScalarHandler("result")));
        getQueryRunner().update(connection,
                "INSERT INTO iteration_assignment(iteration_assignment_id, criterion_type, iteration_id, analytical_prioritization_status) VALUES(nextval('iteration_assignment_seq'), ?, ?, ?) ",
                new Object[] { CriterionTypes.RISK.name(), createdIterationId,
                        AssignmentStatus.NOT_ASSIGNED.name() });
        createComparisonMatrixItem(connection, scripts,
                (Integer) getQueryRunner().query(connection,
                        "SELECT MAX(iteration_assignment_id)::int AS result FROM iteration_assignment ",
                        new ScalarHandler("result")));
        getQueryRunner().update(connection,
                "INSERT INTO iteration_assignment(iteration_assignment_id, criterion_type, iteration_id, analytical_prioritization_status) VALUES(nextval('iteration_assignment_seq'), ?, ?, ?) ",
                new Object[] { CriterionTypes.VALUE.name(), createdIterationId,
                        AssignmentStatus.NOT_ASSIGNED.name() });
        createComparisonMatrixItem(connection, scripts,
                (Integer) getQueryRunner().query(connection,
                        "SELECT MAX(iteration_assignment_id)::int AS result FROM iteration_assignment ",
                        new ScalarHandler("result")));
        getQueryRunner().update(connection,
                "INSERT INTO iteration_assignment(iteration_assignment_id, iteration_id, selective_prioritization_status) VALUES(nextval('iteration_assignment_seq'), ?, ?) ",
                new Object[] { createdIterationId, AssignmentStatus.NOT_ASSIGNED.name() });
        connection.commit();
    } catch (SQLException e) {
        try {
            connection.rollback();
        } catch (SQLException e1) {
            throw new IterationCreationDAOException(e1);
        }
        throw new IterationCreationDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}

From source file:com.splicemachine.derby.impl.sql.catalog.SqlStatisticsIT.java

private int getResultSetCountFromShowIndexes(String schemaName, String tableName) throws Exception {
    if (schemaName == null) {
        schemaName = "null";
    } else {//  ww  w  . j a  v  a 2s .c  o  m
        schemaName = "'" + schemaName + "'";
    }
    if (tableName == null) {
        tableName = "null";
    } else {
        tableName = "'" + tableName + "'";
    }
    CallableStatement cs = methodWatcher.prepareCall(
            format("call SYSIBM.SQLSTATISTICS(null, %s, %s, 1, 1, null)", schemaName, tableName),
            ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
    ResultSet rs = cs.executeQuery();
    int count = 0;
    LOG.trace(format("Show Indexes Args: schema = %s, table = %s", schemaName, tableName));
    while (rs.next()) {
        String schema = rs.getString("TABLE_SCHEM");
        String table = rs.getString("TABLE_NAME");
        String index = rs.getString("INDEX_NAME");
        String column = rs.getString("COLUMN_NAME");
        int position = rs.getInt("ORDINAL_POSITION");
        LOG.trace(
                format("Show Indexes Results: schema = %s, table = %s, index = %s, column = %s, position = %s",
                        schema, table, index, column, position));
        count++;
    }
    LOG.trace(format("Show Indexes Results: count = %s", count));
    DbUtils.closeQuietly(rs);
    return count;
}

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

/**
 * Service search from a bean of criterions.
 * /* w w w. j a v  a  2 s .  c om*/
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param searchBean the criterions to use for the search.
 * @return the resulting object list.
 * @since July, 2011.
 * @throws ServiceSearchDAOException if an error occurs during the search.
 */
@Override
public List<Service> searchService(ServiceSearch searchBean) throws ServiceSearchDAOException {
    LOGGER.debug("searchService().");
    Connection connection = null;
    List<Service> result = null;
    try {
        connection = getDataSource().getConnection();
        List<Object> params = new ArrayList<Object>();
        result = getQueryRunner().query(connection, getServiceSearchQueryFromCriterion(searchBean, params),
                new BeanListHandler<Service>(Service.class), params.toArray());
    } catch (SQLException e) {
        throw new ServiceSearchDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
    return result;
}

From source file:com.mirth.connect.server.userutil.DatabaseConnection.java

/**
 * Executes a prepared query on the database and returns a CachedRowSet.
 * //from  w  w w .  java  2s . c  o m
 * @param expression
 *            The prepared statement to be executed.
 * @param parameters
 *            The parameters for the prepared statement.
 * @return The result of the query, as a CachedRowSet.
 * @throws SQLException
 */
public CachedRowSet executeCachedQuery(String expression, List<Object> parameters) throws SQLException {
    PreparedStatement statement = null;

    try {
        statement = connection.prepareStatement(expression);
        logger.debug("executing prepared statement:\n" + expression);

        ListIterator<Object> iterator = parameters.listIterator();

        while (iterator.hasNext()) {
            int index = iterator.nextIndex() + 1;
            Object value = iterator.next();
            logger.debug("adding parameter: index=" + index + ", value=" + value);
            statement.setObject(index, value);
        }

        ResultSet result = statement.executeQuery();
        CachedRowSet crs = new MirthCachedRowSet();
        crs.populate(result);
        DbUtils.closeQuietly(result);
        return crs;
    } catch (SQLException e) {
        throw e;
    } finally {
        DbUtils.closeQuietly(statement);
    }
}

From source file:com.mirth.connect.server.util.DatabaseUtil.java

/**
 * Tell whether or not the given index exists in the database
 *///from  w w w.  j av  a 2 s.c o  m
public static boolean indexExists(Connection connection, String tableName, String indexName) {
    if (!tableExists(connection, tableName)) {
        return false;
    }

    ResultSet resultSet = null;

    try {
        DatabaseMetaData metaData = connection.getMetaData();
        resultSet = metaData.getIndexInfo(null, null, tableName.toUpperCase(), false, false);

        while (resultSet.next()) {
            if (indexName.equalsIgnoreCase(resultSet.getString("INDEX_NAME"))) {
                return true;
            }
        }

        resultSet = metaData.getIndexInfo(null, null, tableName.toLowerCase(), false, false);

        while (resultSet.next()) {
            if (indexName.equalsIgnoreCase(resultSet.getString("INDEX_NAME"))) {
                return true;
            }
        }

        return false;
    } catch (SQLException e) {
        throw new DonkeyDaoException(e);
    } finally {
        DbUtils.closeQuietly(resultSet);
    }
}

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

/**
 * Variant search from a bean of criterions.
 * // w  w  w.  j  a  va  2  s  .  co m
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param searchBean the criterions to use for the search.
 * @return the resulting object list.
 * @since July, 2011.
 * @throws VariantSearchDAOException if an error occurs during the search.
 */
@Override
public List<Variant> searchVariant(VariantSearch searchBean) throws VariantSearchDAOException {
    LOGGER.debug("searchVariant().");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        List<Object> params = new ArrayList<Object>();
        List<Variant> variants = getQueryRunner().query(connection,
                getVariantSearchQueryFromCriterion(searchBean, params),
                new BeanListHandler<Variant>(Variant.class), params.toArray());
        for (Variant variant : variants) {
            variant.setVariantType(VariantTypes.valueOf((String) getQueryRunner().query(connection,
                    "SELECT variant_type AS variantTypeAsString FROM variant WHERE variant_id = ? ",
                    new ScalarHandler("variantTypeAsString"), new Object[] { variant.getVariantId() })));
        }
        return variants;
    } catch (SQLException e) {
        throw new VariantSearchDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}

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

/**
 * Creates a map from an action plan id, a list of intentions and a list of
 * sections./* www .  java 2 s  . c  om*/
 * 
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param actionPlanId the action plan id to be linked to the created
 *        actions.
 * @param intentions the intentions to add in the map.
 * @param sections the sections to add in the map.
 * @since July, 2011.
 * @throws ActionCreationDAOException if an error occurs during the
 *         creation.
 */
@Override
public void createMap(int actionPlanId, List<Intention> intentions, List<Section> sections)
        throws ActionCreationDAOException {
    LOGGER.debug("createMap(" + actionPlanId + "," + intentions.size() + " intentions," + sections.size()
            + " sections).");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        connection.setAutoCommit(false);
        List<Integer> createdIntentionsId = new ArrayList<Integer>();
        for (Intention intention : intentions) {
            getQueryRunner().update(connection,
                    "INSERT INTO intention(intention_id, label) VALUES(nextval('intention_seq'), ?) ",
                    new Object[] { intention.getLabel() });
            createdIntentionsId.add((Integer) getQueryRunner().query(connection,
                    "SELECT MAX(intention_id)::int AS intentionId FROM intention ",
                    new ScalarHandler("intentionId")));
        }
        List<Intention> createdIntentions = getQueryRunner().query(connection,
                "SELECT intention_id AS intentionId, label FROM intention WHERE intention_id IN("
                        + getInClauseFromIntentionsIds(createdIntentionsId) + ") ",
                new BeanListHandler<Intention>(Intention.class));
        LOGGER.debug(createdIntentions.size() + " intentions created with success...");
        for (Section section : sections) {
            boolean source = false, target = false;
            for (Intention intention : createdIntentions) {
                if (!source && intention.getLabel().equalsIgnoreCase(section.getSourceIntention())) {
                    section.setSourceIntentionId(intention.getIntentionId());
                    source = true;
                }
                if (!target && intention.getLabel().equalsIgnoreCase(section.getTargetIntention())) {
                    section.setTargetIntentionId(intention.getIntentionId());
                    target = true;
                }
                if (target && source) {
                    break;
                }
            }
            Integer actionId = (Integer) getQueryRunner().query(connection,
                    "SELECT action_id::int AS actionId FROM action WHERE action_plan_id = ? AND source_intention = ? AND target_intention = ? ",
                    new ScalarHandler("actionId"), new Object[] { actionPlanId, section.getSourceIntentionId(),
                            section.getTargetIntentionId() });
            if (null == actionId) {
                LOGGER.debug("Action creation...");
                getQueryRunner().update(connection,
                        "INSERT INTO action(action_id, target_intention, source_intention, action_plan_id) VALUES(nextval('action_seq'),?,?,?) ",
                        new Object[] { section.getTargetIntentionId(), section.getSourceIntentionId(),
                                actionPlanId });
                actionId = (Integer) getQueryRunner().query(connection,
                        "SELECT action_id::int AS actionId FROM action WHERE action_plan_id = ? AND source_intention = ? AND target_intention = ? ",
                        new ScalarHandler("actionId"), new Object[] { actionPlanId,
                                section.getSourceIntentionId(), section.getTargetIntentionId() });
            }
            getQueryRunner().update(connection,
                    "INSERT INTO item(item_id, label, iteration_max_number) VALUES(nextval('item_seq'), ?, ?) ",
                    new Object[] { section.getStrategyLabel(), section.getMaxIterationNumber() });
            Integer createdItemId = (Integer) getQueryRunner().query(connection,
                    "SELECT MAX(item_id)::int AS itemId FROM item ", new ScalarHandler("itemId"));
            getQueryRunner().update(connection,
                    (section.isExclusive())
                            ? "INSERT INTO action_exclusive_item(action_id, item_id) VALUES(?,?) "
                            : "INSERT INTO action_inclusive_item(action_id, item_id) VALUES(?,?) ",
                    new Object[] { actionId, createdItemId });
        }
        connection.commit();
    } catch (SQLException e) {
        try {
            connection.rollback();
        } catch (SQLException e1) {
            throw new ActionCreationDAOException(e1);
        }
        throw new ActionCreationDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}

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

/**
 * User search from a bean of criterions.
 * /* ww  w.  j  a  va 2s .c  o  m*/
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param searchBean the criterions to use for the search.
 * @return the resulting object list.
 * @since July, 2011.
 * @throws UserSearchDAOException if an error occurs during the search.
 */
@Override
public List<User> searchUsers(UserSearch searchBean) throws UserSearchDAOException {
    LOGGER.debug("searchUsers().");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        List<Object> params = new ArrayList<Object>();
        List<User> result = getQueryRunner().query(connection,
                getUserSearchQueryFromCriterion(searchBean, params), new BeanListHandler<User>(User.class),
                params.toArray());
        if (null != result) { // Adding the users roles.
            for (User user : result) {
                List<Role> roles = new ArrayList<Role>();
                for (Object[] role : getQueryRunner().query(connection, getUserRoleSearchQuery(),
                        new ArrayListHandler(), new Object[] { user.getUserId() })) {
                    roles.add(Role.valueOf(role[0].toString().toUpperCase()));
                }
                user.setRoles(roles);
            }
        }
        return result;
    } catch (SQLException e) {
        throw new UserSearchDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}

From source file:com.mirth.connect.server.migration.Migrate3_0_0.java

private void migrateChannelTable() {
    PreparedStatement preparedStatement = null;
    ResultSet results = null;//  ww w  .  j  a  v a  2 s .c o m

    try {
        /*
         * MIRTH-1667: Derby fails if autoCommit is set to true and there are a large number of
         * results. The following error occurs: "ERROR 40XD0: Container has been closed"
         */
        Connection connection = getConnection();
        connection.setAutoCommit(false);

        preparedStatement = connection.prepareStatement(
                "SELECT ID, NAME, DESCRIPTION, IS_ENABLED, VERSION, REVISION, LAST_MODIFIED, SOURCE_CONNECTOR, DESTINATION_CONNECTORS, PROPERTIES, PREPROCESSING_SCRIPT, POSTPROCESSING_SCRIPT, DEPLOY_SCRIPT, SHUTDOWN_SCRIPT FROM OLD_CHANNEL");
        results = preparedStatement.executeQuery();

        while (results.next()) {
            String channelId = "";

            try {
                channelId = results.getString(1);
                String name = results.getString(2);
                String description = results.getString(3);
                Boolean isEnabled = results.getBoolean(4);
                String version = results.getString(5);
                Integer revision = results.getInt(6);

                Calendar lastModified = Calendar.getInstance();
                lastModified.setTimeInMillis(results.getTimestamp(7).getTime());

                String sourceConnector = results.getString(8);
                String destinationConnectors = results.getString(9);
                String properties = results.getString(10);
                String preprocessingScript = results.getString(11);
                String postprocessingScript = results.getString(12);
                String deployScript = results.getString(13);
                String shutdownScript = results.getString(14);

                Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
                Element element = document.createElement("channel");
                document.appendChild(element);
                DonkeyElement channel = new DonkeyElement(element);

                channel.addChildElement("id", channelId);
                channel.addChildElement("name", name);
                channel.addChildElement("description", description);
                channel.addChildElement("enabled", Boolean.toString(isEnabled));
                channel.addChildElement("version", version);

                DonkeyElement lastModifiedElement = channel.addChildElement("lastModified");
                lastModifiedElement.addChildElement("time", String.valueOf(lastModified.getTimeInMillis()));
                lastModifiedElement.addChildElement("timezone", lastModified.getTimeZone().getDisplayName());

                channel.addChildElement("revision", String.valueOf(revision));

                channel.addChildElementFromXml(sourceConnector).setNodeName("sourceConnector");
                channel.addChildElementFromXml(destinationConnectors).setNodeName("destinationConnectors");
                channel.addChildElementFromXml(properties);

                channel.addChildElement("preprocessingScript", preprocessingScript);
                channel.addChildElement("postprocessingScript", postprocessingScript);
                channel.addChildElement("deployScript", deployScript);
                channel.addChildElement("shutdownScript", shutdownScript);

                String serializedChannel = channel.toXml();

                PreparedStatement updateStatement = null;

                try {
                    updateStatement = connection.prepareStatement(
                            "INSERT INTO CHANNEL (ID, NAME, REVISION, CHANNEL) VALUES (?, ?, ?, ?)");
                    updateStatement.setString(1, channelId);
                    updateStatement.setString(2, name);
                    updateStatement.setInt(3, revision);
                    updateStatement.setString(4, serializedChannel);
                    updateStatement.executeUpdate();
                    updateStatement.close();
                } finally {
                    DbUtils.closeQuietly(updateStatement);
                }
            } catch (Exception e) {
                logger.error("Error migrating channel " + channelId + ".", e);
            }
        }

        connection.commit();
    } catch (SQLException e) {
        logger.error("Error migrating channels.", e);
    } finally {
        DbUtils.closeQuietly(results);
        DbUtils.closeQuietly(preparedStatement);
    }
}

From source file:com.zionex.t3sinc.util.db.SincDatabaseUtility.java

public void close(Connection connection) {
    DbUtils.closeQuietly(connection);
}