List of usage examples for java.sql Connection isClosed
boolean isClosed() throws SQLException;
Connection
object has been closed. From source file:org.lockss.db.SqlDbManager.java
/** * Closes a connection without throwing exceptions. * //from ww w .j a v a 2 s . co m * @param conn * A Connection with the database connection to be closed. */ public static void safeCloseConnection(Connection conn) { try { if ((conn != null) && !conn.isClosed()) { conn.close(); } } catch (SQLException sqle) { log.error("Cannot close connection", sqle); } }
From source file:edu.uga.cs.fluxbuster.db.PostgresDBInterface.java
/** * Executes a PostgresSQL copy command./*from w w w . j a v a 2 s . c om*/ * * @param query the copy command to execute * @param reader the containing the data to be copied */ private void executeCopyIn(String query, Reader reader) { Connection con = null; CopyManager manager = null; try { con = this.getConnection(); con.setAutoCommit(false); if (con instanceof com.jolbox.bonecp.ConnectionHandle) { ConnectionHandle handle = (ConnectionHandle) con; manager = new CopyManager((BaseConnection) handle.getInternalConnection()); } else { manager = new CopyManager((BaseConnection) con); } manager.copyIn(query, reader); con.commit(); } catch (Exception e) { if (log.isErrorEnabled()) { log.error(query, e); } if (con != null) { try { con.rollback(); } catch (SQLException e1) { if (log.isErrorEnabled()) { log.error("Error during rollback.", e1); } } } } finally { try { if (con != null && !con.isClosed()) { con.setAutoCommit(true); con.close(); } } catch (SQLException e) { if (log.isErrorEnabled()) { log.error("Error during close.", e); } } } }
From source file:org.lockss.db.SqlDbManager.java
/** * Rolls back and closes a connection without throwing exceptions. * // w ww . ja v a 2s . c o m * @param conn * A Connection with the database connection to be rolled back * and closed. */ public static void safeRollbackAndClose(Connection conn) { // Roll back the connection. try { if ((conn != null) && !conn.isClosed()) { conn.rollback(); } } catch (SQLException sqle) { log.error("Cannot roll back the connection", sqle); } // Close it. safeCloseConnection(conn); }
From source file:org.apache.syncope.core.persistence.jpa.content.XMLContentExporter.java
@Override public void export(final String domain, final OutputStream os, final String uwfPrefix, final String gwfPrefix, final String awfPrefix) throws SAXException, TransformerConfigurationException { if (StringUtils.isNotBlank(uwfPrefix)) { TABLE_PREFIXES_TO_BE_EXCLUDED.add(uwfPrefix); }// w ww . java 2 s . c o m if (StringUtils.isNotBlank(gwfPrefix)) { TABLE_PREFIXES_TO_BE_EXCLUDED.add(gwfPrefix); } if (StringUtils.isNotBlank(awfPrefix)) { TABLE_PREFIXES_TO_BE_EXCLUDED.add(awfPrefix); } StreamResult streamResult = new StreamResult(os); final SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory .newInstance(); transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true); TransformerHandler handler = transformerFactory.newTransformerHandler(); Transformer serializer = handler.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, StandardCharsets.UTF_8.name()); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); handler.setResult(streamResult); handler.startDocument(); handler.startElement("", "", ROOT_ELEMENT, new AttributesImpl()); DataSource dataSource = domainsHolder.getDomains().get(domain); if (dataSource == null) { throw new IllegalArgumentException("Could not find DataSource for domain " + domain); } String dbSchema = ApplicationContextProvider.getBeanFactory().getBean(domain + "DatabaseSchema", String.class); Connection conn = null; ResultSet rs = null; try { conn = DataSourceUtils.getConnection(dataSource); final DatabaseMetaData meta = conn.getMetaData(); rs = meta.getTables(null, StringUtils.isBlank(dbSchema) ? null : dbSchema, null, new String[] { "TABLE" }); final Set<String> tableNames = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); while (rs.next()) { String tableName = rs.getString("TABLE_NAME"); LOG.debug("Found table {}", tableName); if (isTableAllowed(tableName)) { tableNames.add(tableName); } } LOG.debug("Tables to be exported {}", tableNames); // then sort tables based on foreign keys and dump for (String tableName : sortByForeignKeys(dbSchema, conn, tableNames)) { try { doExportTable(handler, dbSchema, conn, tableName, TABLES_TO_BE_FILTERED.get(tableName.toUpperCase())); } catch (Exception e) { LOG.error("Failure exporting table {}", tableName, e); } } } catch (SQLException e) { LOG.error("While exporting database content", e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { LOG.error("While closing tables result set", e); } } DataSourceUtils.releaseConnection(conn, dataSource); if (conn != null) { try { if (!conn.isClosed()) { conn.close(); } } catch (SQLException e) { LOG.error("While releasing connection", e); } } } handler.endElement("", "", ROOT_ELEMENT); handler.endDocument(); }
From source file:jdbc.pool.JDBCPoolTestCase.java
/** * Tests Inactive Timeout for -1 or 0 value. * This pool has different set of parameters as compared to MYSQL pool and this forces the behaviour changes * in the pool. The connections will not be pooled and therefore the connections will be closed upon release. *///from w w w . j a v a 2 s.c o m public void testTIT() { System.out.println("testTIT Start."); CConnectionPoolManager manager = null; try { manager = create(); CPoolAttribute attrib = manager.getPoolAttributes("TIT"); assertEquals("Driver", "com.mysql.jdbc.Driver", attrib.getDriver()); assertEquals("Vendor", "MySQL", attrib.getVendor()); assertEquals("URL", "jdbc:mysql://localhost/newpre", attrib.getURL()); assertEquals("User", "root", attrib.getUser()); assertEquals("Password", "=?UTF-8?B?cm9vdA==?=", attrib.getPassword()); assertEquals("Initial Pool Size", 3, attrib.getInitialPoolSize()); assertEquals("Capacity Increament", 2, attrib.getCapacityIncreament()); assertEquals("Maximum Capacity", 50, attrib.getMaximumCapacity()); assertEquals("Connection Idle Timeout", -1, attrib.getConnectionIdleTimeout()); assertEquals("Shrink Pool Interval", 1, attrib.getShrinkPoolInterval()); assertEquals("Critical Operation Timelimit", 10000, attrib.getCriticalOperationTimeLimit()); assertEquals("In Use wait time", 10, attrib.getInUseWaitTime()); assertFalse("load-on-startup", attrib.isLoadOnStartup()); Connection conOra1 = manager.getConnection("TIT"); Connection realCon = null; if (conOra1 instanceof ConnectionWrapper) { ConnectionWrapper wrapper = (ConnectionWrapper) conOra1; realCon = wrapper.realConnection(); } else { fail("Connection returned is not an instance of ConnectionWrapper"); } conOra1.close(); assertTrue("Connection must get closed as the inactive-time-out <= 0", realCon.isClosed()); attrib = manager.getPoolAttributes("TIT"); assertEquals("Driver", "com.mysql.jdbc.Driver", attrib.getDriver()); assertEquals("Vendor", "MySQL", attrib.getVendor()); assertEquals("URL", "jdbc:mysql://localhost/newpre", attrib.getURL()); assertEquals("User", "root", attrib.getUser()); assertEquals("Password", "=?UTF-8?B?cm9vdA==?=", attrib.getPassword()); assertEquals("Initial Pool Size", 0, attrib.getInitialPoolSize()); assertEquals("Capacity Increament", 1, attrib.getCapacityIncreament()); assertEquals("Maximum Capacity", 50, attrib.getMaximumCapacity()); assertEquals("Connection Idle Timeout", -1, attrib.getConnectionIdleTimeout()); assertEquals("Shrink Pool Interval", -1, attrib.getShrinkPoolInterval()); assertEquals("Critical Operation Timelimit", 10000, attrib.getCriticalOperationTimeLimit()); assertEquals("In Use wait time", 10, attrib.getInUseWaitTime()); assertFalse("load-on-startup", attrib.isLoadOnStartup()); } catch (ConfigurationException e) { e.printStackTrace(); fail("Caught ConfigurationException"); } catch (ParseException e) { e.printStackTrace(); fail("Caught ParseException"); } catch (IOException e) { e.printStackTrace(); fail("Caught IOException"); } catch (SQLException e) { e.printStackTrace(); fail("Caught SQLException"); } catch (ClassNotFoundException e) { e.printStackTrace(); fail("Caught ClassNotFoundException"); } finally { manager.destroy(true); } System.out.println("testTIT end."); }
From source file:jdbc.pool.JDBCPoolTestCase.java
/** * Test if JDBC connection is getting closed after crossing the maximum * usage per JDBC connection.// w w w .j a v a2 s. c om * */ public void testMaxUsagePerJDBCConnection() { System.out.println("testMaxUsagePerJDBCConnection start."); try { CConnectionPoolManager manager = create(); Connection realCon = null; Connection con = manager.getConnection("ORACLE"); if (con instanceof ConnectionWrapper) { ConnectionWrapper wrapper = (ConnectionWrapper) con; realCon = wrapper.realConnection(); } else { fail("Connection returned is not an instance of ConnectionWrapper"); } con.close(); assertFalse("Connection must be active", realCon.isClosed()); // 2 con = manager.getConnection("ORACLE"); con.close(); assertFalse("Connection must be active", realCon.isClosed()); // 3 con = manager.getConnection("ORACLE"); con.close(); assertFalse("Connection must be active", realCon.isClosed()); // 4 con = manager.getConnection("ORACLE"); con.close(); assertTrue("Connection must be closed", realCon.isClosed()); manager.destroy(true); } catch (ConfigurationException e) { e.printStackTrace(); fail("Caught ConfigurationException"); } catch (ParseException e) { e.printStackTrace(); fail("Caught ParseException"); } catch (IOException e) { e.printStackTrace(); fail("Caught IOException"); } catch (SQLException e) { e.printStackTrace(); fail("Caught SQLException"); } catch (ClassNotFoundException e) { e.printStackTrace(); fail("Caught ClassNotFoundException"); } System.out.println("testMaxUsagePerJDBCConnection end."); }
From source file:org.rti.zcore.dar.struts.action.DeleteAdminRecordAction.java
/** * Deletes all admin records except user_info. * This assumes that an admin record has a null patient_id * @param mapping//from w w w . jav a2s . co m * @param form * @param request * @param response * @return * @throws Exception * @deprecated - use zcore version instead. */ protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); Site site = SessionUtil.getInstance(session).getClientSettings().getSite(); String siteAbbrev = site.getAbbreviation(); Principal user = request.getUserPrincipal(); String username = user.getName(); Connection conn = null; ResultSet rs; StringBuffer sbuf = new StringBuffer(); try { // using the super special root connection for this one mate! // conn = DatabaseUtils.getSpecialRootConnection(username); // use zeprs conn for derby conn = DatabaseUtils.getZEPRSConnection(username); try { rs = EncountersDAO.getAllEncounters(conn); String message = ""; StringBuffer sbufLog = new StringBuffer(); while (rs.next()) { Long encounterId = rs.getLong("id"); Long formId = rs.getLong("form_id"); String formName = DynaSiteObjects.getFormIdClassNameMap().get(formId); Long patientId = rs.getLong("patient_id"); EncounterData vo = new EncounterData(); // dummy EncounterData is OK. if ((patientId == 0) && ((!formName.equals("UserInfo")) && (!formName.equals("ArtRegimen")) && (!formName.equals("Item")) && (!formName.equals("ItemGroup")) && (!formName.equals("RegimenGroup")) && (!formName.equals("Regimen")) && (!formName.equals("RegimenItem_bridge")))) { try { PatientRecordUtils.deleteEncounter(conn, formId, encounterId, username, site, vo, null); } catch (Exception e) { request.setAttribute("exception", e); return mapping.findForward("error"); } } } message = sbufLog.toString(); request.setAttribute("message", message); } catch (Exception e) { e.printStackTrace(); request.setAttribute("exception", e); return mapping.findForward("error"); } finally { // } } finally { if (conn != null && !conn.isClosed()) { conn.close(); } } return mapping.findForward("home"); }
From source file:jdbc.pool.JDBCPoolOracleConnectionTest.java
/** * Tests Inactive Timeout for -1 or 0 value. * This pool has different set of parameters as compared to MYSQL pool and this forces the behaviour changes * in the pool. The connections will not be pooled and therefore the connections will be closed upon release. */// www .j av a 2 s . co m public void testTIT() { System.out.println("testTIT Start."); testGetInstanceNull(); CConnectionPoolManager manager = null; try { manager = create(); CPoolAttribute attrib = manager.getPoolAttributes("TIT"); assertEquals("Driver", "com.mysql.jdbc.Driver", attrib.getDriver()); assertEquals("Vendor", "MySQL", attrib.getVendor()); assertEquals("URL", "jdbc:mysql://localhost/newpre", attrib.getURL()); assertEquals("User", "root", attrib.getUser()); assertEquals("Password", "=?UTF-8?B?cm9vdA==?=", attrib.getPassword()); assertEquals("Initial Pool Size", 3, attrib.getInitialPoolSize()); assertEquals("Capacity Increament", 2, attrib.getCapacityIncreament()); assertEquals("Maximum Capacity", 50, attrib.getMaximumCapacity()); assertEquals("Connection Idle Timeout", -1, attrib.getConnectionIdleTimeout()); assertEquals("Shrink Pool Interval", 1, attrib.getShrinkPoolInterval()); assertEquals("Critical Operation Timelimit", 10000, attrib.getCriticalOperationTimeLimit()); assertEquals("In Use wait time", 10, attrib.getInUseWaitTime()); assertFalse("load-on-startup", attrib.isLoadOnStartup()); Connection conOra1 = manager.getConnection("TIT"); Connection realCon = null; if (conOra1 instanceof ConnectionWrapper) { ConnectionWrapper wrapper = (ConnectionWrapper) conOra1; realCon = wrapper.realConnection(); } else { fail("Connection returned is not an instance of ConnectionWrapper"); } conOra1.close(); assertTrue("Connection must get closed as the inactive-time-out <= 0", realCon.isClosed()); attrib = manager.getPoolAttributes("TIT"); assertEquals("Driver", "com.mysql.jdbc.Driver", attrib.getDriver()); assertEquals("Vendor", "MySQL", attrib.getVendor()); assertEquals("URL", "jdbc:mysql://localhost/newpre", attrib.getURL()); assertEquals("User", "root", attrib.getUser()); assertEquals("Password", "=?UTF-8?B?cm9vdA==?=", attrib.getPassword()); assertEquals("Initial Pool Size", 0, attrib.getInitialPoolSize()); assertEquals("Capacity Increament", 1, attrib.getCapacityIncreament()); assertEquals("Maximum Capacity", 50, attrib.getMaximumCapacity()); assertEquals("Connection Idle Timeout", -1, attrib.getConnectionIdleTimeout()); assertEquals("Shrink Pool Interval", -1, attrib.getShrinkPoolInterval()); assertEquals("Critical Operation Timelimit", 10000, attrib.getCriticalOperationTimeLimit()); assertEquals("In Use wait time", 10, attrib.getInUseWaitTime()); assertFalse("load-on-startup", attrib.isLoadOnStartup()); } catch (ConfigurationException e) { e.printStackTrace(); fail("Caught ConfigurationException"); } catch (ParseException e) { e.printStackTrace(); fail("Caught ParseException"); } catch (IOException e) { e.printStackTrace(); fail("Caught IOException"); } catch (SQLException e) { e.printStackTrace(); fail("Caught SQLException"); } catch (ClassNotFoundException e) { e.printStackTrace(); fail("Caught ClassNotFoundException"); } finally { manager.destroy(true); } System.out.println("testTIT end."); }
From source file:jdbc.pool.JDBCPoolOracleConnectionTest.java
/** * Test if JDBC connection is getting closed after crossing the maximum * usage per JDBC connection.// w ww . ja v a 2 s . c o m * */ public void testMaxUsagePerJDBCConnection() { System.out.println("testMaxUsagePerJDBCConnection start."); testGetInstanceNull(); try { CConnectionPoolManager manager = create(); Connection realCon = null; Connection con = manager.getConnection("ORACLE"); if (con instanceof ConnectionWrapper) { ConnectionWrapper wrapper = (ConnectionWrapper) con; realCon = wrapper.realConnection(); } else { fail("Connection returned is not an instance of ConnectionWrapper"); } con.close(); assertFalse("Connection must be active", realCon.isClosed()); // 2 con = manager.getConnection("ORACLE"); con.close(); assertFalse("Connection must be active", realCon.isClosed()); // 3 con = manager.getConnection("ORACLE"); con.close(); assertFalse("Connection must be active", realCon.isClosed()); // 4 con = manager.getConnection("ORACLE"); con.close(); assertTrue("Connection must be closed", realCon.isClosed()); manager.destroy(true); } catch (ConfigurationException e) { e.printStackTrace(); fail("Caught ConfigurationException"); } catch (ParseException e) { e.printStackTrace(); fail("Caught ParseException"); } catch (IOException e) { e.printStackTrace(); fail("Caught IOException"); } catch (SQLException e) { e.printStackTrace(); fail("Caught SQLException"); } catch (ClassNotFoundException e) { e.printStackTrace(); fail("Caught ClassNotFoundException"); } System.out.println("testMaxUsagePerJDBCConnection end."); }
From source file:jdbc.pool.JDBCPoolTestCase.java
/** * Test case for LIFO Algorithm with Maximum JDBC Usage parameter. *//*w ww. ja va 2 s.co m*/ public void testLIFOAlgorithm() { System.out.println("testLIFOAlgorithm with Maximum Usage Counter Start."); try { CConnectionPoolManager manager = create(); Connection realCon = null; Connection con = manager.getConnection("LIFO"); //It has 3 iniital connections. if (con instanceof ConnectionWrapper) { ConnectionWrapper wrapper = (ConnectionWrapper) con; realCon = wrapper.realConnection(); } else { fail("Connection returned is not an instance of ConnectionWrapper"); } con.close(); con = manager.getConnection("LIFO"); con.close(); assertFalse("Connection must be active", realCon.isClosed()); con = manager.getConnection("LIFO"); con.close(); assertFalse("Connection must be active", realCon.isClosed()); con = manager.getConnection("LIFO"); con.close(); assertTrue("Connection must be active", realCon.isClosed()); manager.destroy(true); } catch (ConfigurationException e) { e.printStackTrace(); fail("Caught ConfigurationException"); } catch (ParseException e) { e.printStackTrace(); fail("Caught ParseException"); } catch (IOException e) { e.printStackTrace(); fail("Caught IOException"); } catch (SQLException e) { e.printStackTrace(); fail("Caught SQLException"); } catch (ClassNotFoundException e) { e.printStackTrace(); fail("Caught ClassNotFoundException"); } System.out.println("testLIFOAlgorithm with Maximum Usage Counter End."); }