List of usage examples for java.sql Connection isClosed
boolean isClosed() throws SQLException;
Connection
object has been closed. From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCLogsDAO.java
private void addLogRecords(LogRecord[] logRecords, JDBCDataAccessManager dataAccessManager) throws RegistryException { PreparedStatement s = null;//from w w w .j a va 2s . c o m Connection conn = null; try { conn = dataAccessManager.getDataSource().getConnection(); if (conn.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); } conn.setAutoCommit(false); String sql = "INSERT INTO REG_LOG (REG_PATH, REG_USER_ID, REG_LOGGED_TIME, " + "REG_ACTION, REG_ACTION_DATA, REG_TENANT_ID) " + "VALUES (?, ?, ?, ?, ?, ?)"; s = conn.prepareStatement(sql); for (LogRecord logRecord : logRecords) { s.clearParameters(); s.setString(1, logRecord.getResourcePath()); s.setString(2, logRecord.getUserName()); s.setTimestamp(3, new Timestamp(logRecord.getTimestamp().getTime())); s.setInt(4, logRecord.getAction()); s.setString(5, logRecord.getActionData()); s.setInt(6, logRecord.getTenantId()); s.addBatch(); } int[] status = s.executeBatch(); if (log.isDebugEnabled()) { log.debug("Successfully added " + status.length + " log records."); } conn.commit(); } catch (SQLException e) { try { if (conn != null) { conn.rollback(); } } catch (SQLException e1) { log.error("Failed to rollback log insertion.", e); } String msg = "Failed to update log batch records " + ". " + e.getMessage(); log.error(msg, e); throw new RegistryException(msg, e); } finally { try { if (s != null) { s.close(); } if (conn != null && !(conn.isClosed())) { conn.close(); } } catch (SQLException ex) { String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR; log.error(msg, ex); } } }
From source file:jdbc.pool.JDBCPoolMySQLTest.java
public void testUpdatePoolAttributesCPoolAttribute() { testGetInstanceNull();/*from ww w . j a v a2 s.c o m*/ logger.debug("testUpdatePoolAttributesCPoolAttribute Started"); try { CConnectionPoolManager manager = null; manager = create(); CPoolAttribute attribMySQL = manager.getPoolAttributes("MYSQL"); Connection con = manager.getConnection("MYSQL"); int iOriginalInitialPoolSize = attribMySQL.getInitialPoolSize(); attribMySQL.setPassword("root"); attribMySQL.setInitialPoolSize(10); try { manager.updatePoolAttributes(attribMySQL, false); } catch (InvalidPoolAttributeException e) { e.printStackTrace(); } CPoolAttribute attributes = manager.getPoolAttributes("MYSQL"); assertFalse("Initial Pool size should not be same as the updated ones", (attributes.getInitialPoolSize() == 10)); assertTrue("Initial pool size should be same as the original ones", (attributes.getInitialPoolSize() == iOriginalInitialPoolSize)); assertFalse("Connection is not closed ", con.isClosed()); manager.destroy(true); testGetInstanceNull(); manager = create(); con = manager.getConnection("MYSQL"); attribMySQL = manager.getPoolAttributes("MYSQL"); assertEquals("Initial Size should be same as the updated ones", 10, attribMySQL.getInitialPoolSize()); assertFalse("Initial pool size should not be same as the original ones", (attribMySQL.getInitialPoolSize() == iOriginalInitialPoolSize)); attribMySQL.setPassword("root"); attribMySQL.setInitialPoolSize(iOriginalInitialPoolSize); try { manager.updatePoolAttributes(attribMySQL, true); attributes = manager.getPoolAttributes("MYSQL"); assertEquals("Initial Pool size should be same as the updated ones", iOriginalInitialPoolSize, attributes.getInitialPoolSize()); assertTrue("Connection is closed ", ((ConnectionWrapper) con).realConnection().isClosed()); } catch (InvalidPoolAttributeException e) { e.printStackTrace(); } con = manager.getConnection("MYSQL"); assertNotNull(con); 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"); } try { CConnectionPoolManager manager = null; manager = create(); CPoolAttribute attribMySQL = manager.getPoolAttributes("MYSQL"); attribMySQL.setPoolName("NOTEXISTANT"); attribMySQL.setPassword("root"); attribMySQL.setInitialPoolSize(10); try { manager.updatePoolAttributes(attribMySQL, true); // Raises // configuration // exception. fail("did not throw Configuration Exception"); } catch (ConfigurationException e) { e.printStackTrace(); assertTrue("Caught ConfigurationException", true); } catch (InvalidPoolAttributeException e) { e.printStackTrace(); fail("Invalid Pool Attribute Exception caught"); } manager.destroy(true); testGetInstanceNull(); } 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"); } logger.debug("testUpdatePoolAttributesCPoolAttribute ended"); }
From source file:org.wso2.carbon.repository.core.jdbc.dao.JDBCLogsDAO.java
private void addLogRecords(LogRecord[] logRecords, JDBCDataAccessManager dataAccessManager) throws RepositoryException { PreparedStatement s = null;/*from w ww .j a v a 2 s . co m*/ Connection conn = null; try { conn = dataAccessManager.getDataSource().getConnection(); if (conn.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); } conn.setAutoCommit(false); String sql = "INSERT INTO REG_LOG (REG_PATH, REG_USER_ID, REG_LOGGED_TIME, " + "REG_ACTION, REG_ACTION_DATA, REG_TENANT_ID) " + "VALUES (?, ?, ?, ?, ?, ?)"; s = conn.prepareStatement(sql); for (LogRecord logRecord : logRecords) { s.clearParameters(); s.setString(1, logRecord.getResourcePath()); s.setString(2, logRecord.getUserName()); s.setTimestamp(3, new Timestamp(logRecord.getTimestamp().getTime())); s.setInt(4, logRecord.getAction().getId()); s.setString(5, logRecord.getActionData()); s.setInt(6, logRecord.getTenantId()); s.addBatch(); } int[] status = s.executeBatch(); if (log.isDebugEnabled()) { log.debug("Successfully added " + status.length + " log records."); } conn.commit(); } catch (SQLException e) { try { if (conn != null) { conn.rollback(); } } catch (SQLException e1) { log.error("Failed to rollback log insertion.", e); } String msg = "Failed to update log batch records " + ". " + e.getMessage(); log.error(msg, e); throw new RepositoryDBException(msg, e); } finally { try { if (s != null) { s.close(); } if (conn != null && !(conn.isClosed())) { conn.close(); } } catch (SQLException ex) { String msg = InternalConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR; log.error(msg, ex); } } }
From source file:org.apache.hadoop.hive.metastore.txn.TxnHandler.java
static void rollbackDBConn(Connection dbConn) { try {//from www .ja va2 s.c o m if (dbConn != null && !dbConn.isClosed()) dbConn.rollback(); } catch (SQLException e) { LOG.warn("Failed to rollback db connection " + getMessage(e)); } }
From source file:org.apache.hadoop.hive.metastore.txn.TxnHandler.java
protected static void closeDbConn(Connection dbConn) { try {//from w w w .j a v a2 s . c o m if (dbConn != null && !dbConn.isClosed()) { dbConn.close(); } } catch (SQLException e) { LOG.warn("Failed to close db connection " + getMessage(e)); } }
From source file:org.rti.zcore.dar.struts.action.PatientItemListAction.java
/** * Process the specified HTTP request, and create the corresponding HTTP * response (or forward to another web component that will create it). * Return an <code>ActionForward</code> instance describing where and how * control should be forwarded, or <code>null</code> if the response has * already been completed.//from w w w. j a v a2 s . c o m * * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return Action to forward to * @throws Exception if an input/output error or servlet exception occurs */ protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Extract attributes we will need HttpSession session = request.getSession(); Principal user = request.getUserPrincipal(); String username = user.getName(); Connection conn = null; try { conn = DatabaseUtils.getZEPRSConnection(username); SessionSubject sessionPatient = null; try { sessionPatient = (SessionSubject) SessionUtil.getInstance(session).getSessionPatient(); } catch (SessionUtil.AttributeNotFoundException e) { log.error("Unable to get TimsSessionSubject"); } Long patientId = null; //Long eventId = null; String eventUuid = null; Long currentFlowId = null; try { assert sessionPatient != null; patientId = sessionPatient.getId(); //eventId = sessionPatient.getCurrentEventId(); eventUuid = sessionPatient.getCurrentEventUuid(); currentFlowId = sessionPatient.getCurrentFlowId(); } catch (Exception e) { log.error("Unable to get TimsSessionSubject field" + e); } if (eventUuid == null) { String forwardString = "/listEvents.do?patientId=" + patientId; ActionForward forwardForm = new ActionForward(forwardString); forwardForm.setRedirect(true); return forwardForm; } Long viewFlowId = null; // if flowId is in the request, set sessionPatient's flowId if (request.getParameter("flowId") != null) { viewFlowId = Long.decode(request.getParameter("flowId")); } else if (request.getAttribute("flowId") != null) { viewFlowId = Long.decode(request.getAttribute("flowId").toString()); } else { try { viewFlowId = currentFlowId; assert viewFlowId != null; if (viewFlowId.intValue() == 9) { // if it's new patient registration viewFlowId = new Long("132"); // send to history } } catch (Exception e) { // a test user w/ no flo - send to history. viewFlowId = new Long("132"); } } List items = null; Long formId = (Long) DynaSiteObjects.getFormNameMap().get("PatientItem"); Long flowId = Long.valueOf(2); items = PatientItemDAO.getPatientItemList(conn, patientId, eventUuid, flowId, formId); request.setAttribute("items", items); Boolean status = Boolean.valueOf(true); List activeProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid, status, sessionPatient); request.setAttribute("activeProblems", activeProblems); // now get inactive problems status = Boolean.valueOf(false); List inactiveProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid, status, sessionPatient); request.setAttribute("inactiveProblems", inactiveProblems); conn.close(); } catch (ServletException e) { log.error(e); } finally { if (conn != null && !conn.isClosed()) { conn.close(); } } return mapping.findForward("success"); }
From source file:com.aurel.track.admin.customize.localize.LocalizeBL.java
/** * Update the resources based on the properties * @param properties// www . jav a 2s.c o m * @param strLocale * @param overwrite whether to overwrite the edited resources * @param withPrimaryKey whether the used to be BoxResources are imported or the ApplicationResources */ static synchronized void uploadResources(Properties properties, String strLocale, boolean overwrite, boolean withPrimaryKey, boolean initBoxResources) { List<TLocalizedResourcesBean> resourceBeans = getResourcesForLocale(strLocale, withPrimaryKey); SortedMap<String, List<TLocalizedResourcesBean>> existingLabels = new TreeMap<String, List<TLocalizedResourcesBean>>(); for (TLocalizedResourcesBean localizedResourcesBean : resourceBeans) { String key = localizedResourcesBean.getFieldName(); if (withPrimaryKey) { if (key.startsWith(LocalizationKeyPrefixes.FIELD_LABEL_KEY_PREFIX) || key.startsWith(LocalizationKeyPrefixes.FIELD_TOOLTIP_KEY_PREFIX)) { key += "."; } key = key + localizedResourcesBean.getPrimaryKeyValue(); } List<TLocalizedResourcesBean> localizedResources = existingLabels.get(key); if (localizedResources == null) { localizedResources = new LinkedList<TLocalizedResourcesBean>(); existingLabels.put(key, localizedResources); } localizedResources.add(localizedResourcesBean); } Enumeration propertyNames = properties.keys(); Connection connection = null; try { connection = Transaction.begin(); connection.setAutoCommit(false); while (propertyNames.hasMoreElements()) { String key = (String) propertyNames.nextElement(); String localizedText = LocalizeBL.correctString(properties.getProperty(key)); Integer primaryKey = null; String fieldName = null; if (withPrimaryKey) { int primaryKeyIndex = key.lastIndexOf("."); if (primaryKeyIndex != -1) { try { primaryKey = Integer.valueOf(key.substring(primaryKeyIndex + 1)); } catch (Exception e) { LOGGER.warn("The last part after . can't be converted to integer " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } fieldName = key.substring(0, primaryKeyIndex + 1); if (fieldName.startsWith(LocalizationKeyPrefixes.FIELD_LABEL_KEY_PREFIX) || fieldName.startsWith(LocalizationKeyPrefixes.FIELD_TOOLTIP_KEY_PREFIX)) { //do not have . at the end (legacy) fieldName = fieldName.substring(0, fieldName.length() - 1); } } } else { fieldName = key; } List<TLocalizedResourcesBean> localizedResources = existingLabels.get(key); if (localizedResources != null && localizedResources.size() > 1) { //remove all duplicates (as a consequence of previous erroneous imports) localizedResourcesDAO.deleteLocalizedResourcesForFieldNameAndKeyAndLocale(fieldName, primaryKey, strLocale); localizedResources = null; } if (localizedResources == null || localizedResources.isEmpty()) { //new resource TLocalizedResourcesBean localizedResourcesBean = new TLocalizedResourcesBean(); localizedResourcesBean.setFieldName(fieldName); localizedResourcesBean.setPrimaryKeyValue(primaryKey); localizedResourcesBean.setLocalizedText(localizedText); localizedResourcesBean.setLocale(strLocale); localizedResourcesDAO.insert(localizedResourcesBean); } else { //existing resource if (localizedResources.size() == 1) { TLocalizedResourcesBean localizedResourcesBean = localizedResources.get(0); if (EqualUtils.notEqual(localizedText, localizedResourcesBean .getLocalizedText()) /*&& locale.equals(localizedResourcesBean.getLocale())*/) { //text changed locally by the customer boolean textChanged = localizedResourcesBean.getTextChangedBool(); if ((textChanged == false && !initBoxResources) || (textChanged && overwrite)) { localizedResourcesBean.setLocalizedText(localizedText); localizedResourcesDAO.save(localizedResourcesBean); } } else { } } } } Transaction.commit(connection); if (!connection.isClosed()) { connection.close(); } } catch (Exception e) { LOGGER.error("Problem filling locales: " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); if (connection != null) { Transaction.safeRollback(connection); } } //delete the existing ones not found in the properties Locale locale; if (strLocale != null) { locale = LocaleHandler.getLocaleFromString(strLocale); } else { locale = Locale.getDefault(); } if (withPrimaryKey) { //not sure that all is needed but to be sure we do not miss imported localizations LookupContainer.resetLocalizedLookupMap(SystemFields.INTEGER_ISSUETYPE, locale); LookupContainer.resetLocalizedLookupMap(SystemFields.INTEGER_STATE, locale); LookupContainer.resetLocalizedLookupMap(SystemFields.INTEGER_PRIORITY, locale); LookupContainer.resetLocalizedLookupMap(SystemFields.INTEGER_SEVERITY, locale); } ResourceBundle.clearCache(); }
From source file:org.rti.zcore.dar.struts.action.CreateTestPatientAction.java
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); Principal user = request.getUserPrincipal(); String username = user.getName(); Connection conn = null; try {/* ww w . j a va2s . c om*/ conn = DatabaseUtils.getZEPRSConnection(username); ModuleConfig cfg = mapping.getModuleConfig(); String patientType = request.getParameter("patientType"); String number = request.getParameter("number"); EncounterData enc; // setup clock Calendar cal = new GregorianCalendar(); Date starttime = cal.getTime(); long long_starttime = starttime.getTime(); Site site = SessionUtil.getInstance(session).getClientSettings().getSite(); Long siteId = site.getId(); if (patientType != null & number == null) { enc = TestPatientUtils.populate(conn, siteId, patientType, username); request.setAttribute("patientId", enc.getPatientId()); } else if (number != null) { int numberI = new Integer(number); int numTestPatients = numberI * 10; if (patientType != null) { log.debug("Start Time for generating " + numTestPatients + " " + patientType + " patients: " + starttime.toString()); numberI = numberI * 10; for (int i = 0; i < numberI; i++) { TestPatientUtils.populate(conn, siteId, patientType, username); } } else { log.debug("Start Time for generating " + numTestPatients + " test patients: " + starttime.toString()); for (int i = 0; i < numTestPatients; i++) { patientType = "basic"; TestPatientUtils.populate(conn, siteId, patientType, username); /* patientType = "full"; TestPatientUtils.populate(conn, siteId, patientType, username); patientType = "docket"; TestPatientUtils.populate(conn, siteId, patientType, username); patientType = "courtPrep1"; TestPatientUtils.populate(conn, siteId, patientType, username); patientType = "referral1"; TestPatientUtils.populate(conn, siteId, patientType, username); patientType = "consult2"; TestPatientUtils.populate(conn, siteId, patientType, username); patientType = "courtPrep2final"; TestPatientUtils.populate(conn, siteId, patientType, username);*/ } } // Stop clock and calculate time elapsed Calendar cal2 = new GregorianCalendar(); Date endtime = cal2.getTime(); long long_endtime = endtime.getTime(); long difference = (long_endtime - long_starttime); log.debug("Time to generate " + numTestPatients + " test patients: " + difference / 1000 + " seconds"); } else { enc = TestPatientUtils.populate(conn, siteId, "basic", username); request.setAttribute("patientId", enc.getPatientId()); } } catch (ServletException e) { log.error(e); } finally { if (conn != null && !conn.isClosed()) { conn.close(); } } return mapping.findForward("home"); }
From source file:com.mirth.connect.connectors.jdbc.JdbcMessageDispatcher.java
public void doDispatch(UMOEvent event) throws Exception { monitoringController.updateStatus(connector, connectorType, Event.BUSY); if (logger.isDebugEnabled()) { logger.debug("Dispatch event: " + event); }/*from ww w. j a v a 2s. c om*/ Connection connection = null; MessageObject messageObject = messageObjectController.getMessageObjectFromEvent(event); if (messageObject == null) { return; } try { // execute the database script if selected if (connector.isUseScript()) { Context context = Context.enter(); Scriptable scope = new ImporterTopLevel(context); // load variables in JavaScript scope JavaScriptScopeUtil.buildScope(scope, messageObject, scriptLogger); // get the script from the cache and execute it Script compiledScript = compiledScriptCache.getCompiledScript(this.connector.getScriptId()); if (compiledScript == null) { logger.warn("Database script could not be found in cache"); messageObjectController.setError(messageObject, Constants.ERROR_406, "Database script not found in cache", null, null); } else { compiledScript.exec(context, scope); String response = "Database write success"; // the user could write Javascript that sets the response // for this connector // if that's the case, then let's save it if (messageObject.getResponseMap().containsKey(messageObject.getConnectorName())) { response = (String) messageObject.getResponseMap().get(messageObject.getConnectorName()); } messageObjectController.setSuccess(messageObject, response, null); } } else { // otherwise run the SQL insert/update/delete statement UMOEndpoint endpoint = event.getEndpoint(); UMOEndpointURI endpointURI = endpoint.getEndpointURI(); String writeStmt = endpointURI.getAddress(); String str; if ((str = connector.getQuery(endpoint, writeStmt)) != null) { writeStmt = str; } writeStmt = JdbcUtils.stripSqlComments(writeStmt); if (writeStmt == null) { throw new IllegalArgumentException("Write statement should not be NULL"); } else if (!writeStmt.toLowerCase().startsWith("insert") && !writeStmt.toLowerCase().startsWith("update") && !writeStmt.toLowerCase().startsWith("delete")) { throw new IllegalArgumentException( "Write statement should be an INSERT, UPDATE, or DELETE SQL statement."); } List<String> paramNames = new ArrayList<String>(); writeStmt = JdbcUtils.parseStatement(writeStmt, paramNames); Object[] paramValues = JdbcUtils.getParams(endpointURI, paramNames, messageObject); connection = connector.getConnection(messageObject); int numRows = -1; try { numRows = new QueryRunner().update(connection, writeStmt, paramValues); } catch (SQLException e) { // If the connection was closed, get a new connection and // try again if (connection.isClosed()) { connection = connector.getConnection(messageObject); numRows = new QueryRunner().update(connection, writeStmt, paramValues); } else { throw e; } } JdbcUtils.commitAndClose(connection); messageObjectController.setSuccess(messageObject, "Database write success, " + numRows + " rows updated", null); logger.debug("Event dispatched succesfuly"); } } catch (Exception e) { logger.debug("Error dispatching event", e); JdbcUtils.rollbackAndClose(connection); alertController.sendAlerts(connector.getChannelId(), Constants.ERROR_406, "Error writing to database", e); messageObjectController.setError(messageObject, Constants.ERROR_406, "Error writing to database: ", e, null); connector.handleException(e); } finally { monitoringController.updateStatus(connector, connectorType, Event.DONE); } }
From source file:org.apache.hadoop.hive.metastore.txn.TxnHandler.java
private LockResponse checkLockWithRetry(Connection dbConn, long extLockId, long txnId) throws NoSuchLockException, NoSuchTxnException, TxnAbortedException, MetaException { try {//from w w w . java 2 s .c o m try { lockInternal(); if (dbConn.isClosed()) { //should only get here if retrying this op dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED); } return checkLock(dbConn, extLockId); } catch (SQLException e) { LOG.debug("Going to rollback"); rollbackDBConn(dbConn); checkRetryable(dbConn, e, "checkLockWithRetry(" + extLockId + "," + txnId + ")"); throw new MetaException( "Unable to update transaction database " + StringUtils.stringifyException(e)); } finally { unlockInternal(); closeDbConn(dbConn); } } catch (RetryException e) { return checkLockWithRetry(dbConn, extLockId, txnId); } }