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.sql.SECExceptions.java

/**
 * Gathers a list of errors based on type and count total of them.
 *
 * @return//  w ww. j a  v  a 2 s.  c o  m
 */
public static List<SystemErrorModel> getErrorCounts() {
    List<SystemErrorModel> list = new ArrayList();
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        conn = DBConnection.connectToDB();
        String sql = "SELECT exceptionType, COUNT(*) AS 'num' " + "FROM SECExceptions "
                + "WHERE timeOccurred >= CAST(CURRENT_TIMESTAMP AS DATE) " + "GROUP BY exceptionType";
        ps = conn.prepareStatement(sql);
        rs = ps.executeQuery();
        while (rs.next()) {
            SystemErrorModel item = new SystemErrorModel();
            item.setExceptionType(rs.getString("exceptionType") == null ? "" : rs.getString("exceptionType"));
            item.setNumber(rs.getInt("num"));
            list.add(item);
        }
    } catch (SQLException ex) {
        ExceptionHandler.Handle(ex);
    } finally {
        DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(ps);
        DbUtils.closeQuietly(rs);
    }
    return list;
}

From source file:azkaban.scheduler.JdbcScheduleLoader.java

@Override
public List<Schedule> loadSchedules() throws ScheduleManagerException {
    logger.info("Loading all schedules from db.");
    Connection connection = getConnection();

    QueryRunner runner = new QueryRunner();
    ResultSetHandler<List<Schedule>> handler = new ScheduleResultHandler();

    List<Schedule> schedules;

    try {//from   ww  w .  j  a v  a2 s. c o  m
        schedules = runner.query(connection, SELECT_ALL_SCHEDULES, handler);
    } catch (SQLException e) {
        logger.error(SELECT_ALL_SCHEDULES + " failed.");

        DbUtils.closeQuietly(connection);
        throw new ScheduleManagerException("Loading schedules from db failed. ", e);
    } finally {
        DbUtils.closeQuietly(connection);
    }

    logger.info("Now trying to update the schedules");

    // filter the schedules
    for (Schedule sched : schedules) {
        if (!sched.updateTime()) {
            logger.info("Schedule " + sched.getScheduleName()
                    + " was scheduled before azkaban start, skipping it.");
            schedules.remove(sched);
            removeSchedule(sched);
        } else {
            logger.info("Recurring schedule, need to update next exec time");
            try {
                updateNextExecTime(sched);
            } catch (Exception e) {
                e.printStackTrace();
                throw new ScheduleManagerException("Update next execution time failed.", e);
            }
            logger.info("Schedule " + sched.getScheduleName() + " loaded and updated.");
        }
    }

    logger.info("Loaded " + schedules.size() + " schedules.");

    return schedules;
}

From source file:com.mycompany.rubricatelefonica.DefaultUtenteDao.java

public boolean insertNewUtente(UtenteModel utente) {
    boolean inserito = false;
    MysqlDataSource dataSource = new MysqlDataSource();

    dataSource.setUser("root");
    dataSource.setPassword("root");
    dataSource.setUrl("jdbc:mysql://localhost:3306/RubricaTelef");

    Connection conn = null;/*  w w w.  j  a v  a 2  s .  c o  m*/

    try {

        conn = dataSource.getConnection();

        PreparedStatement stmtInsertUtente = conn.prepareStatement(INSERT_UTENTE);
        stmtInsertUtente.setInt(1, utente.getId());
        stmtInsertUtente.setString(2, utente.getImei());
        stmtInsertUtente.setString(3, utente.getNome());
        stmtInsertUtente.setString(4, utente.getCognome());
        stmtInsertUtente.setString(5, utente.getEmail());
        stmtInsertUtente.setString(6, utente.getNumCell());
        stmtInsertUtente.setString(7, utente.getNumTelFisso());
        stmtInsertUtente.setString(8, utente.getData());

        if (stmtInsertUtente.executeUpdate() > 0) {
            inserito = true;
        }
    } catch (SQLException e) {
        System.out.println(e.getMessage());
        System.out.println("errore!! Connessione Fallita");
    } finally {

        DbUtils.closeQuietly(conn); //oppure try with resource
    }

    //
    return inserito;
}

From source file:azkaban.project.JdbcProjectLoader.java

@Override
public List<Project> fetchAllActiveProjects() throws ProjectManagerException {
    Connection connection = getConnection();

    List<Project> projects = null;
    try {/*from  w  w  w  .  java2 s .c om*/
        projects = fetchAllActiveProjects(connection);
    } finally {
        DbUtils.closeQuietly(connection);
    }

    return projects;
}

From source file:com.pinterest.deployservice.db.DatabaseUtil.java

/**
 * Create a MySQL datasource.//from  w w w .  ja v a  2s.c  om
 *
 * @param url             the url of the DB.
 * @param user            the user name to connect to MySQL as.
 * @param passwd          the password for the corresponding MySQL user.
 * @param poolSize        the connection pool size string, in the format of
 *                        initialSize:maxActive:maxIdle:minIdle.
 * @param maxWaitInMillis the max wait time in milliseconds to get a connection from the pool.
 * @return a BasicDataSource for the target MySQL instance.
 */
public static BasicDataSource createDataSource(String driverClassName, String url, String user, String passwd,
        String poolSize, int maxWaitInMillis) {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUrl(url);
    dataSource.setUsername(user);
    dataSource.setPassword(passwd);
    dataSource.setDefaultAutoCommit(true);
    dataSource.setDefaultReadOnly(false);

    // poolSize parsing, the poolsize string passed in the following format
    // initialSize:maxActive:maxIdle:minIdle
    String[] sizeStrs = poolSize.split(":");
    dataSource.setInitialSize(Integer.parseInt(sizeStrs[0]));
    dataSource.setMaxActive(Integer.parseInt(sizeStrs[1]));
    dataSource.setMaxIdle(Integer.parseInt(sizeStrs[2]));
    dataSource.setMinIdle(Integer.parseInt(sizeStrs[3]));

    dataSource.setValidationQuery("SELECT 1");
    dataSource.setTestOnBorrow(true);
    dataSource.setTestOnReturn(false);
    dataSource.setTestWhileIdle(true);
    dataSource.setMinEvictableIdleTimeMillis(5 * 60 * 1000);
    dataSource.setTimeBetweenEvictionRunsMillis(3 * 60 * 1000);
    // dataSource.setNumTestsPerEvictionRun(3);
    // max wait in milliseconds for a connection.
    dataSource.setMaxWait(maxWaitInMillis);

    // force connection pool initialization.
    Connection conn = null;
    try {
        // Here not getting the connection from ThreadLocal no need to worry about that.
        conn = dataSource.getConnection();
    } catch (SQLException e) {
        LOG.error(String.format("Failed to get a db connection when creating DataSource, url = %s", url), e);
    } finally {
        DbUtils.closeQuietly(conn);
    }
    return dataSource;
}

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

public static void executeScript(List<String> script, boolean ignoreErrors) throws Exception {
    SqlSessionManager sqlSessionManger = SqlConfig.getSqlSessionManager();

    Connection conn = null;/*www. j av a  2  s.c o  m*/
    ResultSet resultSet = null;
    Statement statement = null;

    try {
        sqlSessionManger.startManagedSession();
        conn = sqlSessionManger.getConnection();
        /*
         * Set auto commit to false or an exception will be thrown when trying to rollback
         */
        conn.setAutoCommit(false);
        statement = conn.createStatement();

        for (String statementString : script) {
            statementString = statementString.trim();
            if (statementString.length() > 0) {
                try {
                    statement.execute(statementString);
                    conn.commit();
                } catch (SQLException se) {
                    if (!ignoreErrors) {
                        throw se;
                    } else {
                        logger.error("Error was encountered and ignored while executing statement: "
                                + statementString, se);
                        conn.rollback();
                    }
                }
            }
        }

    } catch (Exception e) {
        throw new Exception(e);
    } finally {
        DbUtils.closeQuietly(statement);
        DbUtils.closeQuietly(resultSet);
        DbUtils.closeQuietly(conn);
        sqlSessionManger.close();
    }
}

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

@Override
public void setupEnvInfra(boolean failOnSetupException) {
    LOG.info("Verifying existence of DB2 groups prior to deployment");

    ImmutableSet<String> existingGroups;
    Connection conn = null;// w ww.  j  av a2 s .c o m
    try {
        conn = ds.getConnection();
        existingGroups = Sets.immutable
                .withAll(jdbc.query(conn, "select ROLENAME from sysibm.SYSROLES",
                        new ColumnListHandler<String>()))
                .newWithAll(jdbc.query(conn, "select GRANTEE from sysibm.SYSDBAUTH",
                        new ColumnListHandler<String>()))
                .collect(StringFunctions.trim()); // db2 sometimes has whitespace in its return results that needs trimming
    } catch (Exception e) {
        if (failOnSetupException) {
            if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            }
            throw new RuntimeException(e);
        } else {
            LOG.warn("Group validation query failed; continuing w/ deployment per configuration", e);
            deployMetricsCollector.addMetric(DeployMetrics.WARNINGS_PREFIX + ".db2GroupValidationQueryFailure",
                    true);
            return;
        }
    } finally {
        DbUtils.closeQuietly(conn);
    }

    LOG.info("Groups from DB: {}", existingGroups);

    ImmutableList<String> groupNames = env.getGroups().collect(Group.TO_NAME);
    LOG.info("Groups from system-config: {}", groupNames);

    // Do difference comparison in a case insensitive manner (convert all to lowercase)
    ImmutableList<String> missingGroups = groupNames.select(Predicates.attributeNotIn(
            StringFunctions.toLowerCase(), existingGroups.collect(StringFunctions.toLowerCase())));

    if (missingGroups.notEmpty()) {
        String errorMessage = "The following groups were not found in your DB2 server (checked against sysibm.SYSROLES and sysibm.SYSDBAUTH): "
                + missingGroups;
        if (failOnSetupException) {
            throw new IllegalArgumentException(errorMessage);
        } else {
            LOG.warn(errorMessage);
            LOG.warn("Will proceed with deployment as you have configured this to just be a warning");
            deployMetricsCollector.addMetric(DeployMetrics.WARNINGS_PREFIX + ".db2GroupsInConfigButNotInDb",
                    errorMessage);
        }
    }
}

From source file:azkaban.migration.scheduler.JdbcScheduleLoader.java

private Connection getConnection() throws ScheduleManagerException {
    Connection connection = null;
    try {//from  www.j a va2 s . com
        connection = dataSource.getConnection();
    } catch (Exception e) {
        DbUtils.closeQuietly(connection);
        throw new ScheduleManagerException("Error getting DB connection.", e);
    }

    return connection;
}

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

/**
 * Checks if variants are already existing or not for a given test case.
 * // w  w w  . java  2 s. co  m
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param testCaseId the test case id.
 * @return true if variants are already existing, else false.
 * @since July, 2011.
 * @throws VariantSearchDAOException if an error occurs during the search.
 */
@Override
public boolean areVariantsExistingFromTestCaseId(int testCaseId) throws VariantSearchDAOException {
    LOGGER.debug("areVariantsExistingFromTestCaseId(" + testCaseId + ").");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        return (Boolean) getQueryRunner().query(connection,
                "SELECT EXISTS ( SELECT variant_id FROM variant WHERE test_case_id = ? ) AS result ",
                new ScalarHandler("result"), new Object[] { testCaseId });
    } catch (SQLException e) {
        throw new VariantSearchDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}

From source file:com.ouc.cpss.dao.BaseDao.java

/**
 * //w w w  . j  av  a 2 s . c om
 *
 * @param sql
 * @param clazz
 * @return
 */
public Object get(String sql, Class clazz) {
    Object obj = null;
    Connection conn = null;
    try {
        conn = getConnection();
        QueryRunner qRunner = new QueryRunner();
        obj = qRunner.query(conn, sql, new BeanHandler(clazz));
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        DbUtils.closeQuietly(conn);
    }
    return obj;
}