List of usage examples for java.sql Statement setQueryTimeout
void setQueryTimeout(int seconds) throws SQLException;
Statement
object to execute to the given number of seconds. From source file:org.guzz.transaction.AbstractTranSessionImpl.java
/** * Apply the current query timeout, if any, to the current <code>Statement</code>. * /*from w ww. ja v a2 s . c o m*/ * @param stmt Statement * @see java.sql.Statement#setQueryTimeout */ public void applyQueryTimeout(Statement stmt) { if (hasQueryTimeout()) { try { stmt.setQueryTimeout(getQueryTimeoutInSeconds()); } catch (SQLException e) { throw new JDBCException("failed to setQueryTimeout to :" + getQueryTimeoutInSeconds(), e, e.getSQLState()); } } }
From source file:org.locationtech.udig.tools.jgrass.geopaparazzi.ImportGeopaparazziFolderWizard.java
private void gpsLogToShapefiles(Connection connection, File outputFolderFile, IProgressMonitor pm) throws Exception { File outputLinesShapeFile = new File(outputFolderFile, "gpslines.shp"); Statement statement = connection.createStatement(); statement.setQueryTimeout(30); // set timeout to 30 sec. List<GpsLog> logsList = new ArrayList<ImportGeopaparazziFolderWizard.GpsLog>(); // first get the logs ResultSet rs = statement.executeQuery("select _id, startts, endts, text from gpslogs"); while (rs.next()) { long id = rs.getLong("_id"); String startDateTimeString = rs.getString("startts"); String endDateTimeString = rs.getString("endts"); String text = rs.getString("text"); GpsLog log = new GpsLog(); log.id = id;/* w w w .j a v a2 s .com*/ log.startTime = startDateTimeString; log.endTime = endDateTimeString; log.text = text; logsList.add(log); } statement.close(); try { // then the log data for (GpsLog log : logsList) { long logId = log.id; String query = "select lat, lon, altim, ts from gpslog_data where logid = " + logId + " order by ts"; Statement newStatement = connection.createStatement(); newStatement.setQueryTimeout(30); ResultSet result = newStatement.executeQuery(query); while (result.next()) { double lat = result.getDouble("lat"); double lon = result.getDouble("lon"); double altim = result.getDouble("altim"); String dateTimeString = result.getString("ts"); GpsPoint gPoint = new GpsPoint(); gPoint.lon = lon; gPoint.lat = lat; gPoint.altim = altim; gPoint.utctime = dateTimeString; log.points.add(gPoint); } newStatement.close(); } } catch (Exception e) { e.printStackTrace(); String message = "An error occurred while reading the gps logs."; ExceptionDetailsDialog.openError(null, message, IStatus.ERROR, JGrassToolsPlugin.PLUGIN_ID, e); return; } /* * create the lines shapefile */ SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder(); b.setName("geopaparazzinotes"); b.setCRS(mapCrs); b.add("the_geom", MultiLineString.class); b.add("STARTDATE", String.class); b.add("ENDDATE", String.class); b.add("DESCR", String.class); SimpleFeatureType featureType = b.buildFeatureType(); try { MathTransform transform = CRS.findMathTransform(DefaultGeographicCRS.WGS84, mapCrs); pm.beginTask("Import gps to lines...", logsList.size()); DefaultFeatureCollection newCollection = new DefaultFeatureCollection(); int index = 0; for (GpsLog log : logsList) { List<GpsPoint> points = log.points; List<Coordinate> coordList = new ArrayList<Coordinate>(); String startDate = log.startTime; String endDate = log.endTime; for (GpsPoint gpsPoint : points) { Coordinate c = new Coordinate(gpsPoint.lon, gpsPoint.lat); coordList.add(c); } Coordinate[] coordArray = (Coordinate[]) coordList.toArray(new Coordinate[coordList.size()]); if (coordArray.length < 2) { continue; } LineString lineString = gF.createLineString(coordArray); LineString reprojectLineString = (LineString) JTS.transform(lineString, transform); MultiLineString multiLineString = gF .createMultiLineString(new LineString[] { reprojectLineString }); SimpleFeatureBuilder builder = new SimpleFeatureBuilder(featureType); Object[] values = new Object[] { multiLineString, startDate, endDate, log.text }; builder.addAll(values); SimpleFeature feature = builder.buildFeature(featureType.getTypeName() + "." + index++); newCollection.add(feature); pm.worked(1); } pm.done(); ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory(); Map<String, Serializable> params = new HashMap<String, Serializable>(); params.put("url", outputLinesShapeFile.toURI().toURL()); params.put("create spatial index", Boolean.TRUE); ShapefileDataStore dStore = (ShapefileDataStore) factory.createNewDataStore(params); dStore.createSchema(featureType); dStore.forceSchemaCRS(mapCrs); JGrassToolsPlugin.getDefault().writeToShapefile(dStore, newCollection); JGrassToolsPlugin.getDefault().addServiceToCatalogAndMap(outputLinesShapeFile.getAbsolutePath(), true, true, new NullProgressMonitor()); } catch (Exception e1) { JGrassToolsPlugin.log(e1.getLocalizedMessage(), e1); e1.printStackTrace(); } /* * create the points shapefile */ File outputPointsShapeFile = new File(outputFolderFile, "gpspoints.shp"); b = new SimpleFeatureTypeBuilder(); b.setName("geopaparazzinotes"); b.setCRS(mapCrs); b.add("the_geom", Point.class); b.add("ALTIMETRY", String.class); b.add("DATE", String.class); featureType = b.buildFeatureType(); try { MathTransform transform = CRS.findMathTransform(DefaultGeographicCRS.WGS84, mapCrs); pm.beginTask("Import gps to points...", logsList.size()); DefaultFeatureCollection newCollection = new DefaultFeatureCollection(); int index = 0; for (GpsLog log : logsList) { List<GpsPoint> gpsPointList = log.points; for (GpsPoint gpsPoint : gpsPointList) { Coordinate c = new Coordinate(gpsPoint.lon, gpsPoint.lat); Point point = gF.createPoint(c); Point reprojectPoint = (Point) JTS.transform(point, transform); Object[] values = new Object[] { reprojectPoint, String.valueOf(gpsPoint.altim), gpsPoint.utctime }; SimpleFeatureBuilder builder = new SimpleFeatureBuilder(featureType); builder.addAll(values); SimpleFeature feature = builder.buildFeature(featureType.getTypeName() + "." + index++); newCollection.add(feature); } pm.worked(1); } pm.done(); ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory(); Map<String, Serializable> params = new HashMap<String, Serializable>(); params.put("url", outputPointsShapeFile.toURI().toURL()); params.put("create spatial index", Boolean.TRUE); ShapefileDataStore dStore = (ShapefileDataStore) factory.createNewDataStore(params); dStore.createSchema(featureType); dStore.forceSchemaCRS(mapCrs); JGrassToolsPlugin.getDefault().writeToShapefile(dStore, newCollection); JGrassToolsPlugin.getDefault().addServiceToCatalogAndMap(outputPointsShapeFile.getAbsolutePath(), true, true, new NullProgressMonitor()); } catch (Exception e1) { JGrassToolsPlugin.log(e1.getLocalizedMessage(), e1); e1.printStackTrace(); } }
From source file:eu.udig.tools.jgrass.geopaparazzi.ImportGeopaparazziFolderWizard.java
private void gpsLogToShapefiles(Connection connection, File outputFolderFile, IProgressMonitor pm) throws Exception { File outputLinesShapeFile = new File(outputFolderFile, "gpslines.shp"); Statement statement = connection.createStatement(); statement.setQueryTimeout(30); // set timeout to 30 sec. List<GpsLog> logsList = new ArrayList<ImportGeopaparazziFolderWizard.GpsLog>(); // first get the logs ResultSet rs = statement.executeQuery("select _id, startts, endts, text from gpslogs"); while (rs.next()) { long id = rs.getLong("_id"); String startDateTimeString = rs.getString("startts"); String endDateTimeString = rs.getString("endts"); String text = rs.getString("text"); GpsLog log = new GpsLog(); log.id = id;/* w w w . ja v a 2 s . c o m*/ log.startTime = startDateTimeString; log.endTime = endDateTimeString; log.text = text; logsList.add(log); } statement.close(); try { // then the log data for (GpsLog log : logsList) { long logId = log.id; String query = "select lat, lon, altim, ts from gpslog_data where logid = " + logId + " order by ts"; Statement newStatement = connection.createStatement(); newStatement.setQueryTimeout(30); ResultSet result = newStatement.executeQuery(query); while (result.next()) { double lat = result.getDouble("lat"); double lon = result.getDouble("lon"); double altim = result.getDouble("altim"); String dateTimeString = result.getString("ts"); GpsPoint gPoint = new GpsPoint(); gPoint.lon = lon; gPoint.lat = lat; gPoint.altim = altim; gPoint.utctime = dateTimeString; log.points.add(gPoint); } newStatement.close(); } } catch (Exception e) { e.printStackTrace(); String message = "An error occurred while reading the gps logs."; ExceptionDetailsDialog.openError(null, message, IStatus.ERROR, JGrassToolsPlugin.PLUGIN_ID, e); return; } /* * create the lines shapefile */ SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder(); b.setName("geopaparazzinotes"); b.setCRS(mapCrs); b.add("the_geom", MultiLineString.class); b.add("STARTDATE", String.class); b.add("ENDDATE", String.class); b.add("DESCR", String.class); SimpleFeatureType featureType = b.buildFeatureType(); try { MathTransform transform = CRS.findMathTransform(DefaultGeographicCRS.WGS84, mapCrs); pm.beginTask("Import gps to lines...", logsList.size()); FeatureCollection<SimpleFeatureType, SimpleFeature> newCollection = FeatureCollections.newCollection(); int index = 0; for (GpsLog log : logsList) { List<GpsPoint> points = log.points; List<Coordinate> coordList = new ArrayList<Coordinate>(); String startDate = log.startTime; String endDate = log.endTime; for (GpsPoint gpsPoint : points) { Coordinate c = new Coordinate(gpsPoint.lon, gpsPoint.lat); coordList.add(c); } Coordinate[] coordArray = (Coordinate[]) coordList.toArray(new Coordinate[coordList.size()]); if (coordArray.length < 2) { continue; } LineString lineString = gF.createLineString(coordArray); LineString reprojectLineString = (LineString) JTS.transform(lineString, transform); MultiLineString multiLineString = gF .createMultiLineString(new LineString[] { reprojectLineString }); SimpleFeatureBuilder builder = new SimpleFeatureBuilder(featureType); Object[] values = new Object[] { multiLineString, startDate, endDate, log.text }; builder.addAll(values); SimpleFeature feature = builder.buildFeature(featureType.getTypeName() + "." + index++); newCollection.add(feature); pm.worked(1); } pm.done(); ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory(); Map<String, Serializable> params = new HashMap<String, Serializable>(); params.put("url", outputLinesShapeFile.toURI().toURL()); params.put("create spatial index", Boolean.TRUE); ShapefileDataStore dStore = (ShapefileDataStore) factory.createNewDataStore(params); dStore.createSchema(featureType); dStore.forceSchemaCRS(mapCrs); JGrassToolsPlugin.getDefault().writeToShapefile(dStore, newCollection); JGrassToolsPlugin.getDefault().addServiceToCatalogAndMap(outputLinesShapeFile.getAbsolutePath(), true, true, new NullProgressMonitor()); } catch (Exception e1) { JGrassToolsPlugin.log(e1.getLocalizedMessage(), e1); e1.printStackTrace(); } /* * create the points shapefile */ File outputPointsShapeFile = new File(outputFolderFile, "gpspoints.shp"); b = new SimpleFeatureTypeBuilder(); b.setName("geopaparazzinotes"); b.setCRS(mapCrs); b.add("the_geom", Point.class); b.add("ALTIMETRY", String.class); b.add("DATE", String.class); featureType = b.buildFeatureType(); try { MathTransform transform = CRS.findMathTransform(DefaultGeographicCRS.WGS84, mapCrs); pm.beginTask("Import gps to points...", logsList.size()); FeatureCollection<SimpleFeatureType, SimpleFeature> newCollection = FeatureCollections.newCollection(); int index = 0; for (GpsLog log : logsList) { List<GpsPoint> gpsPointList = log.points; for (GpsPoint gpsPoint : gpsPointList) { Coordinate c = new Coordinate(gpsPoint.lon, gpsPoint.lat); Point point = gF.createPoint(c); Point reprojectPoint = (Point) JTS.transform(point, transform); Object[] values = new Object[] { reprojectPoint, String.valueOf(gpsPoint.altim), gpsPoint.utctime }; SimpleFeatureBuilder builder = new SimpleFeatureBuilder(featureType); builder.addAll(values); SimpleFeature feature = builder.buildFeature(featureType.getTypeName() + "." + index++); newCollection.add(feature); } pm.worked(1); } pm.done(); ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory(); Map<String, Serializable> params = new HashMap<String, Serializable>(); params.put("url", outputPointsShapeFile.toURI().toURL()); params.put("create spatial index", Boolean.TRUE); ShapefileDataStore dStore = (ShapefileDataStore) factory.createNewDataStore(params); dStore.createSchema(featureType); dStore.forceSchemaCRS(mapCrs); JGrassToolsPlugin.getDefault().writeToShapefile(dStore, newCollection); JGrassToolsPlugin.getDefault().addServiceToCatalogAndMap(outputPointsShapeFile.getAbsolutePath(), true, true, new NullProgressMonitor()); } catch (Exception e1) { JGrassToolsPlugin.log(e1.getLocalizedMessage(), e1); e1.printStackTrace(); } }
From source file:org.magdaaproject.analysis.rhizome.tasks.ImportData.java
/** * undertake the task of importing the data */// w w w .ja va 2 s . c o m public void doTask() throws TaskException { // get a connection to the source database Statement sourceStatement = null; ResultSet sourceResultSet = null; //reset the insert count insertCount = 0; if (sourceConnection != null) { try { sourceConnection.close(); sourceConnection = null; } catch (SQLException e) { throw new TaskException("unable to close existing connection to a rhizome database"); } } try { sourceConnection = DriverManager.getConnection("jdbc:sqlite:" + inputFile.getCanonicalPath()); sourceStatement = sourceConnection.createStatement(); sourceStatement.setQueryTimeout(30); } catch (SQLException e) { throw new TaskException("unable to open connection to the Rhizome database", e); } catch (IOException e) { throw new TaskException("unable to open connection to the Rhizome database", e); } // get the data try { sourceResultSet = sourceStatement .executeQuery("select id, name, author, inserttime, filesize from manifests;"); } catch (SQLException e) { throw new TaskException("unable to query the database", e); } // get a connection to the destination database if required if (destConnection == null) { try { destConnection = DatabaseUtils.getMysqlConnection(config); } catch (SQLException e) { throw new TaskException("unable to open connection to the MySQL database", e); } // check if the table already exists try { if (DatabaseUtils.doesTableExist(destConnection, tableName) == false) { throw new TaskException("the specified table '" + tableName + "' doesn't exist"); } } catch (SQLException e) { throw new TaskException("unable to communicate with the the database:\n" + e.getMessage()); } } String sql = "INSERT INTO " + tableName + " (tablet_id, file_id, file_name, file_author_sid, file_insert_time, file_size) VALUES (?,?,?,?,?,?)"; // define a prepared statement PreparedStatement destStatement = null; try { destStatement = destConnection.prepareStatement(sql); } catch (SQLException e) { throw new TaskException("unable to create insert statement", e); } // import the data try { while (sourceResultSet.next() == true) { destStatement.setString(1, tabletId); destStatement.setString(2, sourceResultSet.getString("id")); destStatement.setString(3, sourceResultSet.getString("name")); destStatement.setString(4, sourceResultSet.getString("author")); destStatement.setLong(5, sourceResultSet.getLong("inserttime")); destStatement.setLong(6, sourceResultSet.getLong("filesize")); destStatement.executeUpdate(); insertCount++; } } catch (SQLException e) { throw new TaskException("error in inserting data: '" + e.getMessage()); } }
From source file:com.taobao.tddl.jdbc.group.TGroupStatement.java
/** * setBaseStatementStatement//from www. j ava2s . c o m */ private Statement createStatementInternal(Connection conn, boolean isBatch) throws SQLException { Statement stmt; if (isBatch) stmt = conn.createStatement(); else { int resultSetHoldability = this.resultSetHoldability; if (resultSetHoldability == -1) //setResultSetHoldability resultSetHoldability = conn.getHoldability(); stmt = conn.createStatement(this.resultSetType, this.resultSetConcurrency, resultSetHoldability); } setBaseStatement(stmt); //Statement stmt.setQueryTimeout(queryTimeout); // stmt.setFetchSize(fetchSize); stmt.setMaxRows(maxRows); return stmt; }
From source file:org.apache.jmeter.protocol.jdbc.AbstractJDBCTestElement.java
/** * Execute the test element./*from www .j av a 2 s. c o m*/ * * @param conn a {@link SampleResult} in case the test should sample; <code>null</code> if only execution is requested * @return the result of the execute command * @throws SQLException if a database error occurs * @throws UnsupportedEncodingException when the result can not be converted to the required charset * @throws IOException when I/O error occurs * @throws UnsupportedOperationException if the user provided incorrect query type */ protected byte[] execute(Connection conn) throws SQLException, UnsupportedEncodingException, IOException, UnsupportedOperationException { log.debug("executing jdbc"); Statement stmt = null; try { // Based on query return value, get results String _queryType = getQueryType(); if (SELECT.equals(_queryType)) { stmt = conn.createStatement(); stmt.setQueryTimeout(getIntegerQueryTimeout()); ResultSet rs = null; try { rs = stmt.executeQuery(getQuery()); return getStringFromResultSet(rs).getBytes(ENCODING); } finally { close(rs); } } else if (CALLABLE.equals(_queryType)) { CallableStatement cstmt = getCallableStatement(conn); int[] out = setArguments(cstmt); // A CallableStatement can return more than 1 ResultSets // plus a number of update counts. boolean hasResultSet = cstmt.execute(); String sb = resultSetsToString(cstmt, hasResultSet, out); return sb.getBytes(ENCODING); } else if (UPDATE.equals(_queryType)) { stmt = conn.createStatement(); stmt.setQueryTimeout(getIntegerQueryTimeout()); stmt.executeUpdate(getQuery()); int updateCount = stmt.getUpdateCount(); String results = updateCount + " updates"; return results.getBytes(ENCODING); } else if (PREPARED_SELECT.equals(_queryType)) { PreparedStatement pstmt = getPreparedStatement(conn); setArguments(pstmt); ResultSet rs = null; try { rs = pstmt.executeQuery(); return getStringFromResultSet(rs).getBytes(ENCODING); } finally { close(rs); } } else if (PREPARED_UPDATE.equals(_queryType)) { PreparedStatement pstmt = getPreparedStatement(conn); setArguments(pstmt); pstmt.executeUpdate(); String sb = resultSetsToString(pstmt, false, null); return sb.getBytes(ENCODING); } else if (ROLLBACK.equals(_queryType)) { conn.rollback(); return ROLLBACK.getBytes(ENCODING); } else if (COMMIT.equals(_queryType)) { conn.commit(); return COMMIT.getBytes(ENCODING); } else if (AUTOCOMMIT_FALSE.equals(_queryType)) { conn.setAutoCommit(false); return AUTOCOMMIT_FALSE.getBytes(ENCODING); } else if (AUTOCOMMIT_TRUE.equals(_queryType)) { conn.setAutoCommit(true); return AUTOCOMMIT_TRUE.getBytes(ENCODING); } else { // User provided incorrect query type throw new UnsupportedOperationException("Unexpected query type: " + _queryType); } } finally { close(stmt); } }
From source file:org.jumpmind.db.sql.JdbcSqlTemplate.java
public int update(final String sql, final Object[] args, final int[] types) { logSql(sql, args);// w ww.jav a 2 s . c o m return execute(new IConnectionCallback<Integer>() { public Integer execute(Connection con) throws SQLException { if (args == null) { Statement stmt = null; try { stmt = con.createStatement(); stmt.setQueryTimeout(settings.getQueryTimeout()); stmt.execute(sql); return stmt.getUpdateCount(); } finally { close(stmt); } } else { PreparedStatement ps = null; try { ps = con.prepareStatement(sql); ps.setQueryTimeout(settings.getQueryTimeout()); if (types != null) { setValues(ps, args, types, getLobHandler().getDefaultHandler()); } else { setValues(ps, args); } ps.execute(); return ps.getUpdateCount(); } finally { close(ps); } } } }); }
From source file:com.hp.test.framework.generatejellytess.GenerateJellyTests.java
public static void genjellyTests(String Parent_model_gid, String Feature_name) { Statement statement = null; try {/*from ww w . j ava 2s . c o m*/ statement = connection.createStatement(); String sql_query = "SELECT DR.GID as MODEL_GID,DSR.GID AS SCENARIO_GID,DT.GID AS TEST_GID,DR.MODEL_PATH,DT.TESTCASE,DT.RESULTS FROM DM_TESTCASE DT, DM_MODELXML_REF DR, DM_SCENARIO_REF DSR where DT.TEMPLATE_GID=DSR.GID and DSR.MODEL_GID_REF=DR.GID AND DR.MASTER_GID=" + Integer.parseInt(Parent_model_gid) + " ORDER BY DR.GID"; ResultSet rs = statement.executeQuery(sql_query); String GID_temp = ""; String Test_case = ""; String Model_xml_path = ""; int results = 0; CreateReadableTestCase.fw = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(alm_test_location + Feature_name + ".csv"), "UTF-8")); CreateReadableTestCase.fw.write("TestCaseNumber,StepName,Step Description,ExpectedResults\n"); while (rs.next()) { GID_temp = Parent_model_gid + "_" + rs.getString("MODEL_GID") + "_" + rs.getString("SCENARIO_GID") + "_" + rs.getString("TEST_GID"); // rs.getInt("GID"); log.info("Generating Jelly Testcase for MasterModel GID::" + Parent_model_gid + " MODEL XML GID::" + rs.getString("MODEL_GID") + " TEST SCENARIO GID::" + rs.getString("SCENARIO_GID") + " TESTCASE GID::" + rs.getString("TEST_GID")); Test_case = rs.getString("TESTCASE"); results = rs.getInt("RESULTS"); Model_xml_path = rs.getString("MODEL_PATH"); maptestcasesapi(GID_temp, Test_case, results, Model_xml_path); // break; } CreateReadableTestCase.fw.close(); CreateReadableTestCase.fw = null; statement.setQueryTimeout(30); // set timeout to 30 sec. if (statement != null) { statement.close(); } } catch (SQLException e) { log.error("Error in getting records from DM_TESTCASE to Execute API or to generate Jelly tests"); } catch (IOException e) { log.error("exception in IO" + e.getMessage()); } catch (ClassNotFoundException e) { log.error("" + e.getMessage()); } }
From source file:org.panbox.desktop.common.sharemgmt.ShareManagerImpl.java
@Override public List<String> getInstalledShares() throws ShareManagerException { logger.debug("ShareManager : getInstalledShares"); List<String> shares = new ArrayList<String>(); ResultSet rs = null;/*from w w w. ja v a2s .com*/ Statement statement = null; try { statement = connection.createStatement(); statement.setQueryTimeout(30); // set timeout to 30 sec. rs = statement.executeQuery("select * from " + TABLE_SHARES); while (rs.next()) { String shareName = rs.getString("name"); shares.add(shareName); } } catch (SQLException ex) { throw new ShareManagerException("Failed to run getInstalledShares: ", ex); } finally { try { if (rs != null) rs.close(); } catch (Exception e) { } try { if (statement != null) statement.close(); } catch (Exception e) { } } return shares; }
From source file:com.thinkbiganalytics.nifi.v2.thrift.RefreshableDataSource.java
/** * test the connection to see if it can be used to communicate with the JDBC source * * @param username a username to connect with if needed * @param password a password to connect with if needed * @return true if the connection is alive *//*from www.ja v a 2 s . c om*/ public synchronized boolean testConnection(String username, String password) { // Get a connection to test final Connection connection; try { connection = (StringUtils.isNotBlank(username) || StringUtils.isNotBlank(password)) ? getConnectionForValidation(username, password) : getConnectionForValidation(); log.info("connection obtained by RefreshableDatasource"); } catch (final SQLException e) { log.warn("A database access error occurred when getting a connection for JDBC URL: ", url, e); return false; } // Test the connection using different methods boolean asyncCleanup = false; Statement statement = null; try { // Method 1: Test using driver method try { // can throw "java.sql.SQLException: Method not supported"; ignore and try other methods if so final boolean isValid = connection.isValid(validationQueryTimeout.intValue()); if (!isValid) { log.info("Connection obtained for JDBC URL was not valid: {}", url); return false; } } catch (final SQLException e) { log.debug("The isValid() method is not supported for the JDBC URL: {}", url); } // Method 2: Test with a statement and query timeout try { statement = connection.createStatement(); } catch (final SQLException e) { log.warn("A database access error occurred when getting a statement for JDBC URL: {}", url, e); return false; } try { statement.setQueryTimeout(validationQueryTimeout.intValue()); // throws method not supported if Hive driver try { statement.execute(validationQuery); // executes if no exception from setQueryTimeout return true; } catch (final SQLException e) { log.debug("Failed to execute validation query for JDBC URL: {}", url, e); log.info("Connection obtained for JDBC URL was not valid: {}", url); return false; } } catch (final SQLException e) { log.warn("The Statement.setQueryTimeout() method is not supported for the JDBC URL: {}", url); } // Method 3: Test with a statement and a timer asyncCleanup = true; boolean isValid; try { isValid = validateQueryWithTimeout(statement, validationQuery, validationQueryTimeout.intValue()); } catch (final SQLException e) { log.debug("Failed to execute validation query for JDBC URL: {}", url, e); isValid = false; } if (!isValid) { log.info("Connection obtained for JDBC URL was not valid: {}", url); } return isValid; } finally { connectionCleanup(connection, statement, asyncCleanup); } }