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.ActivityDAO.java

/**
 * Activities to describe search from a parent test case id.
 * /*  w  ww .jav  a 2  s.  co m*/
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param testCaseId the parent test case id.
 * @return the resulting object list.
 * @since July, 2011.
 * @throws ActivitySearchDAOException
 */
@Override
public List<Activity> searchActivitiesToDescribeFromTestCaseId(int testCaseId)
        throws ActivitySearchDAOException {
    LOGGER.debug("searchActivitiesToDescribeFromTestCaseId(" + testCaseId + ").");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        List<Object> params = new ArrayList<Object>();
        return getQueryRunner().query(connection, getActivitiesToDescribeQuery(testCaseId, params),
                new BeanListHandler<Activity>(Activity.class), params.toArray());
    } catch (SQLException e) {
        throw new ActivitySearchDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}

From source file:com.intelligentz.appointmentz.controllers.Data.java

public static String equipmentsGetRPI(String hospital_id) {
    String rpi = "";
    try {/*from   w  ww. ja v  a2s.com*/
        connection = DBConnection.getDBConnection().getConnection();
        String SQL = "select * from rpi natural join room where hospital_id = ?";
        preparedStatement = connection.prepareStatement(SQL);
        preparedStatement.setString(1, hospital_id);
        resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            String auth = resultSet.getString("auth");
            String serial = resultSet.getString("serial");
            String room_id = resultSet.getString("room_id");
            String room_number = resultSet.getString("room_number");
            rpi += "<tr><form action='./deleteRPI' method='post'><td>" + auth
                    + "</td><input type='hidden' name='auth' value='" + auth + "'>";
            rpi += "<td>" + serial + "</td><input type='hidden' name='serial' value='" + serial + "'><td>"
                    + room_number + "</td><td>" + room_id + "</td>";
            rpi += "<input type='hidden' name='room_number' value='" + room_number + "'>";
            rpi += "<input type='hidden' name='room_id' value='" + room_id + "'>";
            rpi += "<td><button type=\"submit\" onClick=\"return confirm('Do you wish to delete the Device. Ref: Serial = "
                    + serial + ", rel: Room: " + room_number + " ');\" style='color:red'>delete</button></td>";
            rpi += "</form>";
            rpi += "<form action='./editRPI' method='post'><input type='hidden' name='room_number' value='"
                    + room_number + "'><input type='hidden' name='room_id' value='" + room_id
                    + "'><input type='hidden' name='serial' value='" + serial
                    + "'><input type='hidden' name='auth' value='" + auth + "'>";
            rpi += "<td><button type=\"submit\" style='color:blue'>edit</button></td>";
            rpi += "</form></tr>";
        }
    } catch (SQLException | IOException | PropertyVetoException e) {
        //throw new IllegalStateException
        rpi = "Error";

    } finally {
        try {
            DbUtils.closeQuietly(resultSet);
            DbUtils.closeQuietly(preparedStatement);
            DbUtils.close(connection);
        } catch (SQLException ex) {
            Logger.getLogger(register.class.getName()).log(Level.SEVERE, ex.toString(), ex);
        }
    }
    return rpi;
}

From source file:azkaban.trigger.JdbcTriggerLoader.java

@Override
public void updateTrigger(Trigger t) throws TriggerLoaderException {
    if (logger.isDebugEnabled()) {
        logger.debug("Updating trigger " + t.getTriggerId() + " into db.");
    }// w w  w  . ja va 2  s  . c  o m
    t.setLastModifyTime(System.currentTimeMillis());
    Connection connection = getConnection();
    try {
        updateTrigger(connection, t, defaultEncodingType);
    } catch (Exception e) {
        e.printStackTrace();
        throw new TriggerLoaderException("Failed to update trigger " + t.toString() + " into db!");
    } finally {
        DbUtils.closeQuietly(connection);
    }
}

From source file:azkaban.project.JdbcProjectLoader.java

/**
 * Fetch first project with a given name {@inheritDoc}
 *
 * @see azkaban.project.ProjectLoader#fetchProjectByName(java.lang.String)
 */// w w  w. j  av  a  2 s  . c  o m
@Override
public Project fetchProjectByName(String name) throws ProjectManagerException {
    Connection connection = getConnection();

    Project project = null;
    try {
        project = fetchProjectByName(connection, name);
    } finally {
        DbUtils.closeQuietly(connection);
    }

    return project;
}

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

@Override
public ImmutableCollection<RuleBinding> getRuleBindings(DaSchema schema, Connection conn) {
    String schemaName = schema.getName();
    // return the bindings to columns and bindings to domains
    String sql = "select tab.name 'object', rul.name 'rule', "
            + "'sp_bindrule ' || rul.name || ', ''' || tab.name || '.' || col.name || '''' 'sql'\n" + "from "
            + schemaName + "..syscolumns col, " + schemaName + "..sysobjects rul, " + schemaName
            + "..sysobjects tab\n"
            + "where col.domain = rul.id and col.id = tab.id and tab.type='U' and col.domain <> 0\n" + "union\n"
            + "select obj.name 'object', rul.name 'rule', "
            + "'sp_bindrule ' || rul.name || ', ' || obj.name 'sql'\n" + "from " + schemaName
            + "..systypes obj, " + schemaName + "..sysobjects rul\n"
            + "where obj.domain = rul.id and obj.domain <> 0\n";
    PreparedStatement ps = null;/*from  w  ww  .j a  v  a  2 s.c om*/
    ResultSet rs = null;
    try {
        ps = conn.prepareStatement(sql);
        rs = ps.executeQuery();

        MutableList<RuleBinding> ruleBindings = Lists.mutable.empty();
        while (rs.next()) {
            RuleBindingImpl ruleBinding = new RuleBindingImpl();
            ruleBinding.setObject(rs.getString("object"));
            ruleBinding.setRule(rs.getString("rule"));
            ruleBinding.setSql(rs.getString("sql"));
            ruleBindings.add(ruleBinding);
        }
        return ruleBindings.toImmutable();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(ps);
    }
}

From source file:jp.mathes.databaseWiki.db.postgres.PostgresBackend.java

private String getNameField(final Connection conn, final String table, final String db)
        throws BackendException {
    Statement st = null;//  w w  w . j a va  2s .c  om
    ResultSet rs = null;
    String result = null;

    try {
        String schema = this.getSchemaName(table, db);
        String plainTable = this.getPlainTableName(table);
        st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

        StringBuilder sb = new StringBuilder("");
        sb.append("select k.column_name ");
        sb.append(" from information_schema.table_constraints c ");
        sb.append("  inner join information_schema.key_column_usage k ");
        sb.append("   on c.constraint_catalog = k.constraint_catalog and ");
        sb.append("      c.constraint_schema = k.constraint_schema and ");
        sb.append("      c.constraint_name = k.constraint_name ");
        sb.append(" where c.constraint_type='PRIMARY KEY' and ");
        sb.append("       c.table_name='%s' and ");
        sb.append("       c.table_schema='%s'");
        String queryString = String.format(sb.toString().replaceAll("[ ]+", " "), plainTable, schema);

        this.logString(queryString, "?");
        rs = st.executeQuery(queryString);
        if (this.getNumRows(rs) != 1) {
            throw new BackendException(
                    String.format("Table %s.%s has no or a multi column primary key which is not supported.",
                            this.getSchemaName(table, db), this.getPlainTableName(table)));
        }
        rs.next();
        result = rs.getString(1);
    } catch (SQLException e) {
        throw new BackendException(e);
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(st);
    }
    return result;
}

From source file:com.gs.obevo.db.impl.core.jdbc.JdbcHelper.java

public <T> T query(Connection conn, String sql, ResultSetHandler<T> resultSetHandler) {
    Statement statement = null;//  w w  w . j  a v a2 s .co m
    ResultSet resultSet = null;
    try {
        statement = conn.createStatement();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Executing query on connection {}: {}", displayConnection(conn), sql);
        }
        resultSet = statement.executeQuery(sql);
        return resultSetHandler.handle(resultSet);
    } catch (SQLException e) {
        throw new DataAccessException(e);
    } finally {
        DbUtils.closeQuietly(resultSet);
        DbUtils.closeQuietly(statement);
    }
}

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

public CachedRowSet executeUpdateAndGetGeneratedKeys(String expression) throws SQLException {
    Statement statement = null;/*from w  w w  . ja  va2  s  .  com*/

    try {
        statement = connection.createStatement();
        logger.debug("executing update:\n" + expression);
        statement.executeUpdate(expression, Statement.RETURN_GENERATED_KEYS);
        CachedRowSetImpl crs = new CachedRowSetImpl();
        crs.populate(statement.getGeneratedKeys());
        return crs;
    } catch (SQLException e) {
        throw e;
    } finally {
        DbUtils.closeQuietly(statement);
    }
}

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

/**
 * Creates a procedural diagram from a testCaseId, a set of elements and a
 * set of transitions. If activities have been reused or not to create this
 * diagram.//from  w ww. j av a 2s.  co m
 * 
 * @param testCaseId the test case id.
 * @param elements the set of elements.
 * @param transitions the set of transitions.
 * @throws ElementCreationDAOException if an error occurs during the
 *         creation.
 */
@Override
public void createDiagram(int testCaseId, List<ElementCreation> elements, List<TransitionCreation> transitions)
        throws ElementCreationDAOException {
    LOGGER.debug("createDiagram(" + testCaseId + ", " + elements.size() + " elements, " + transitions.size()
            + " transitions).");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        connection.setAutoCommit(false);
        for (ElementCreation element : elements) {
            Integer activityId = null, pointId = null;
            if (element.getType().equals(ElementCreationTypes.ACTIVITY)) {
                activityId = (Integer) getQueryRunner().query(connection,
                        "SELECT activity_id::int AS activityId FROM activity WHERE label = ? ",
                        new ScalarHandler("activityId"), new Object[] { element.getLabel() });
                if (null == activityId) {
                    getQueryRunner().update(connection,
                            "INSERT INTO activity(activity_id, global_description, label) VALUES(nextval('activity_id_seq'), NULL, ?) ",
                            new Object[] { element.getLabel() });
                    activityId = (Integer) getQueryRunner().query(connection,
                            "SELECT activity_id::int AS activityId FROM activity WHERE label = ? ",
                            new ScalarHandler("activityId"), new Object[] { element.getLabel() });
                }
            } else {
                getQueryRunner().update(connection,
                        "INSERT INTO point(point_id, point_type, label) VALUES(nextval('point_id_seq'), ?, ?) ",
                        new Object[] { element.getType().name(), element.getLabel() });
                pointId = (Integer) getQueryRunner().query(connection,
                        "SELECT MAX(point_id)::int AS pointId FROM point ", new ScalarHandler("pointId"));
            }
            getQueryRunner().update(connection,
                    "INSERT INTO element(element_id, point_id, activity_id, test_case_id) VALUES(nextval('element_id_seq'),"
                            + ((null != activityId) ? "NULL" : "?") + "," + ((null != pointId) ? "NULL" : "?")
                            + ",?) ",
                    (null != activityId) ? new Object[] { activityId, testCaseId }
                            : new Object[] { pointId, testCaseId });
        }
        List<Element> createdElements = getQueryRunner().query(connection,
                "SELECT element_id AS elementId, point_id AS pointId, activity_id AS activityId, test_case_id AS testCaseId, COALESCE(activity.label, point.label) AS label FROM element LEFT JOIN activity USING(activity_id) LEFT JOIN point USING(point_id) WHERE test_case_id = ? ",
                new BeanListHandler<Element>(Element.class), new Object[] { testCaseId });
        for (TransitionCreation transition : transitions) {
            boolean source = false, target = false;
            for (Element element : createdElements) {
                if (element.getLabel().equalsIgnoreCase(transition.getSource())) {
                    transition.setSourceId(element.getElementId());
                    source = true;
                }
                if (element.getLabel().equalsIgnoreCase(transition.getTarget())) {
                    transition.setTargetId(element.getElementId());
                    target = true;
                }
                if (source && target) {
                    break;
                }
            }
            getQueryRunner().update(connection,
                    "INSERT INTO transition(transition_id, target_element, source_element, test_case_id, label) VALUES(nextval('transition_id_seq'), ?, ?, ?, ?) ",
                    new Object[] { transition.getTargetId(), transition.getSourceId(), testCaseId,
                            (null != transition.getLabel()) ? transition.getLabel() : "" });
        }
        connection.commit();
    } catch (SQLException e) {
        try {
            connection.rollback();
        } catch (SQLException e1) {
            throw new ElementCreationDAOException(e1);
        }
        throw new ElementCreationDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}

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

public void close(Statement statement) {
    DbUtils.closeQuietly(statement);
}