List of usage examples for org.apache.commons.dbutils DbUtils closeQuietly
public static void closeQuietly(Statement stmt)
Statement
, avoid closing if null and hide any SQLExceptions that occur. From source file:com.che.software.testato.domain.dao.jdbc.impl.IterationDAO.java
/** * Iteration search from a bean of criterions. * //from ww w . j a v a 2 s . 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 IterationSearchDAOException if an error occurs during the search. */ @Override public List<Iteration> searchIteration(IterationSearch searchBean) throws IterationSearchDAOException { LOGGER.debug("searchIteration()."); Connection connection = null; try { connection = getDataSource().getConnection(); List<Object> params = new ArrayList<Object>(); return getQueryRunner().query(connection, getIterationSearchQueryFromCriterion(searchBean, params), new BeanListHandler<Iteration>(Iteration.class), params.toArray()); } catch (SQLException e) { throw new IterationSearchDAOException(e); } finally { if (null != connection) { DbUtils.closeQuietly(connection); } } }
From source file:com.mirth.connect.connectors.jdbc.JdbcMessageReceiver.java
public List getMessages() throws Exception { monitoringController.updateStatus(connector, connectorType, Event.CONNECTED); try {/*from ww w .j a v a2 s. c o m*/ if (connector.isUseScript()) { Context context = Context.enter(); Scriptable scope = new ImporterTopLevel(context); // load variables in JavaScript scope JavaScriptScopeUtil.buildScope(scope, connector.getChannelId(), scriptLogger); // each time we poll, we want to clear the map. // we need to document this jdbcMap = new HashMap(); scope.put("dbMap", scope, jdbcMap); // get the script from the cache and execute it Script compiledScript = compiledScriptCache.getCompiledScript(connector.getScriptId()); if (compiledScript == null) { logger.error("Database script could not be found in cache"); throw new Exception("Database script could not be found in cache"); } else { Object result = null; try { result = compiledScript.exec(context, scope); } catch (Exception e) { logger.error(e); alertController.sendAlerts(connector.getChannelId(), Constants.ERROR_406, null, e); return null; } if (result instanceof NativeJavaObject) { Object javaRetVal = ((NativeJavaObject) result).unwrap(); if (javaRetVal instanceof CachedRowSet) { MapListHandler handler = new MapListHandler(); Object rows = handler.handle((CachedRowSet) javaRetVal); return (List) rows; } else if (javaRetVal instanceof RowSet) { MapListHandler handler = new MapListHandler(); Object rows = handler.handle((RowSet) javaRetVal); return (List) rows; } else if (javaRetVal instanceof List) { return (List) javaRetVal; } else { logger.error("Got a result of: " + javaRetVal.toString()); } } else { logger.error("Got a result of: " + result.toString()); } return null; } } else { if (connection.isClosed()) { try { connection = connector.getConnection(null); } catch (Exception e) { logger.error( "Error trying to establish a connection to the datatabase receiver in channel: " + connector.getChannelId(), e); return new ArrayList(); } } try { return new QueryRunner().query(connection, readStmt, new MapListHandler(), JdbcUtils.getParams(getEndpointURI(), readParams, null)); } catch (SQLException e) { /* * Check if the connection is still valid. Apache pools * throws an unexpected error when calling isValid for some * drivers (i.e. informix), so assume the connection is not * valid if an exception occurs */ boolean validConnection = true; try { validConnection = connection.isValid(10000); } catch (Throwable t) { validConnection = false; } /* * If the connection is not valid, then get a new connection * and retry the query now. */ if (!validConnection) { try { DbUtils.closeQuietly(connection); connection = connector.getConnection(null); return new QueryRunner().query(connection, readStmt, new MapListHandler(), JdbcUtils.getParams(getEndpointURI(), readParams, null)); } catch (SQLException e2) { e = e2; } } throw e; } } } catch (Exception e) { alertController.sendAlerts(connector.getChannelId(), Constants.ERROR_406, null, e); throw e; } finally { monitoringController.updateStatus(connector, connectorType, Event.DONE); } }
From source file:com.splicemachine.derby.utils.SpliceAdminIT.java
@Test public void testGetSetLogLevel() throws Exception { String logger = "com.splicemachine.derby.iapi.sql.execute.SpliceOperationContext"; String origLevel = "FRED"; String newLogLevel = "INFO"; CallableStatement cs = methodWatcher.prepareCall("call SYSCS_UTIL.SYSCS_GET_LOGGER_LEVEL(?)"); cs.setString(1, logger);/*from w w w. j av a 2s.co m*/ ResultSet rs = cs.executeQuery(); while (rs.next()) { origLevel = rs.getString(1); } try { cs = methodWatcher.prepareCall("call SYSCS_UTIL.SYSCS_SET_LOGGER_LEVEL(?,?)"); cs.setString(1, logger); cs.setString(2, newLogLevel); cs.execute(); cs = methodWatcher.prepareCall("call SYSCS_UTIL.SYSCS_GET_LOGGER_LEVEL(?)"); cs.setString(1, logger); rs = cs.executeQuery(); String currentLogLevel = "FRED"; while (rs.next()) { currentLogLevel = rs.getString(1); } Assert.assertNotEquals("FRED", currentLogLevel); Assert.assertEquals(newLogLevel, currentLogLevel); } finally { // reset to orig value cs = methodWatcher.prepareCall("call SYSCS_UTIL.SYSCS_SET_LOGGER_LEVEL(?,?)"); cs.setString(1, logger); cs.setString(2, origLevel); cs.execute(); } DbUtils.closeQuietly(rs); }
From source file:com.mirth.connect.server.migration.ServerMigrator.java
/** * It is assumed that for each migratable class that uses this an "id" column exists in the * database, which is used as the primary key when updating the row. It's also assumed that for * the time being, any additional columns besides the ID and serialized XML (e.g. name, * revision) will not change during migration. *///w w w . jav a 2 s . c o m private void migrateSerializedData(String selectSql, String updateSql, Class<?> expectedClass) { ObjectXMLSerializer serializer = ObjectXMLSerializer.getInstance(); Connection connection = null; Statement selectStatement = null; PreparedStatement updateStatement = null; ResultSet resultSet = null; try { connection = getConnection(); selectStatement = connection.createStatement(); resultSet = selectStatement.executeQuery(selectSql); while (resultSet.next()) { try { String id = resultSet.getString(1); String serializedData = resultSet.getString(2); String migratedData = serializer .serialize(serializer.deserialize(serializedData, expectedClass)); if (!migratedData.equals(serializedData)) { updateStatement = connection.prepareStatement(updateSql); updateStatement.setString(1, migratedData); updateStatement.setString(2, id); updateStatement.executeUpdate(); } } catch (Exception e) { logger.error("Failed to migrate serialized data", e); } } } catch (SQLException e) { logger.error("Failed to migrate serialized data", e); } finally { DbUtils.closeQuietly(resultSet); DbUtils.closeQuietly(selectStatement); DbUtils.closeQuietly(updateStatement); } }
From source file:io.personium.diff.App.java
private List<String> listMySQLDatabases(Connection connection, String prefix, String unitUserName, List<String> excludeUnitUser) { List<String> databases = new ArrayList<String>(); PreparedStatement stmt = null; ResultSet resultSet = null;// w w w .j av a 2 s . c o m try { String sql = "show databases"; stmt = connection.prepareStatement(sql); resultSet = stmt.executeQuery(); while (resultSet.next()) { String database = resultSet.getString(1); if (unitUserName != null) { if (database.equalsIgnoreCase(prefix + "_" + unitUserName)) { databases.add(database); break; } } else { if (database.startsWith(prefix + "_") && !excludeUnitUser.contains(database)) { databases.add(database); } } } } catch (SQLException e) { log.warn("Failed to show databases"); log.info(e.getMessage()); } finally { DbUtils.closeQuietly(resultSet); DbUtils.closeQuietly(stmt); } return databases; }
From source file:dbutils.DbUtilsTemplate.java
/** * ??Bean?Bean?List//www . j a va 2 s. c o m * * @param entityClass ?? * @param sql sql? * @param params ? * @param page ? * @param pageSize ?? * @return */ @SuppressWarnings("unchecked") public <T> List<T> find(Class<T> entityClass, String sql, Object[] params, int page, int pageSize) { queryRunner = new QueryRunner(); Connection conn = null; List<T> list = new ArrayList<T>(); int startFlag = (((page < 1 ? 1 : page) - 1) * pageSize); String pageSql = " limit " + startFlag + " , " + startFlag + pageSize; try { conn = dataSource.getConnection(); if (params == null) { list = (List<T>) queryRunner.query(conn, sql + pageSql, new BeanListHandler(entityClass)); } else { list = (List<T>) queryRunner.query(conn, sql + pageSql, new BeanListHandler(entityClass), params); } } catch (SQLException e) { LOG.error("Error occured while attempting to query data", e); } finally { if (conn != null) { DbUtils.closeQuietly(conn); } } return list; }
From source file:com.norconex.collector.core.data.store.impl.jdbc.JDBCCrawlDataStore.java
private boolean ensureTablesExist() throws SQLException { ArrayListHandler arrayListHandler = new ArrayListHandler(); Connection conn = null;//from ww w. java 2 s.c om try { conn = datasource.getConnection(); List<Object[]> tables = arrayListHandler .handle(conn.getMetaData().getTables(null, null, null, new String[] { "TABLE" })); if (tables.size() == NUMBER_OF_TABLES) { LOG.debug(" Re-using existing tables."); return true; } } finally { DbUtils.closeQuietly(conn); } LOG.debug(" Creating new crawl tables..."); sqlCreateTable(TABLE_QUEUE); sqlCreateTable(TABLE_ACTIVE); sqlCreateTable(TABLE_PROCESSED_VALID); sqlCreateTable(TABLE_PROCESSED_INVALID); sqlCreateTable(TABLE_CACHE); return false; }
From source file:com.splicemachine.derby.utils.SpliceAdminIT.java
@Test public void testGetSpliceVersion() throws Exception { CallableStatement cs = methodWatcher.prepareCall("call SYSCS_UTIL.SYSCS_GET_VERSION_INFO()"); ResultSet rs = cs.executeQuery(); TestUtils.FormattedResult fr = TestUtils.FormattedResult.ResultFactory .convert("call SYSCS_UTIL.SYSCS_GET_VERSION_INFO()", rs); System.out.println(fr.toString()); Assert.assertTrue(fr.size() >= 1); DbUtils.closeQuietly(rs); }
From source file:com.che.software.testato.domain.dao.jdbc.impl.IterationDAO.java
/** * Updates an iteration from his object. * //from www . j av a 2 s. c o m * @author Clement HELIOU (clement.heliou@che-software.com). * @param iterationToUpdate the iteration object to update in the database. * @since July, 2011. * @throws IterationUpdateDAOException if an error occurs during the update. */ @Override public void updateIteration(Iteration iterationToUpdate) throws IterationUpdateDAOException { LOGGER.debug("updateIteration(" + iterationToUpdate.getIterationAssignmentId() + ")."); Connection connection = null; try { connection = getDataSource().getConnection(); List<Object> params = new ArrayList<Object>(); getQueryRunner().update(connection, getIterationUpdateQueryFromCriterion(iterationToUpdate, params), params.toArray()); } catch (SQLException e) { throw new IterationUpdateDAOException(e); } finally { if (null != connection) { DbUtils.closeQuietly(connection); } } }
From source file:com.splicemachine.derby.utils.SpliceAdminIT.java
@Test public void testUpdateSchemaOwner() throws Exception { String schemaName = "SPLICEADMINITSCHEMAFOO"; String userName = "SPLICEADMINITUSERFRED"; try {/*from w ww . j a v a 2s.c om*/ methodWatcher.executeUpdate(String.format("CREATE SCHEMA %s", schemaName)); } catch (Exception e) { // Allow schema exists error } CallableStatement cs = null; try { cs = methodWatcher.prepareCall( String.format("call SYSCS_UTIL.SYSCS_CREATE_USER('%s', '%s')", userName, userName)); cs.execute(); } catch (Exception e) { // Allow user exists error } finally { DbUtils.closeQuietly(cs); } CallableStatement cs2 = null; ResultSet rs = null; try { cs2 = methodWatcher.prepareCall( String.format("call SYSCS_UTIL.SYSCS_UPDATE_SCHEMA_OWNER('%s', '%s')", schemaName, userName)); cs2.execute(); rs = methodWatcher.executeQuery( String.format("SELECT AUTHORIZATIONID FROM SYS.SYSSCHEMAS WHERE SCHEMANAME='%s'", schemaName)); Assert.assertTrue(rs.next()); Assert.assertEquals(userName, rs.getString(1)); } finally { DbUtils.closeQuietly(rs); } try { methodWatcher.executeUpdate(String.format("DROP SCHEMA %s RESTRICT", schemaName)); } catch (Exception e) { // Allow error } }