List of usage examples for java.sql Connection getAutoCommit
boolean getAutoCommit() throws SQLException;
Connection
object. From source file:org.sakaiproject.event.impl.ClusterEventTracking.java
/** * Write a batch of events to the db//from ww w . j a v a2s.c o m * * @param events * The collection of event to write. */ protected void writeBatchEvents(Collection events) { // get a connection Connection conn = null; boolean wasCommit = true; try { conn = sqlService().borrowConnection(); wasCommit = conn.getAutoCommit(); if (wasCommit) { conn.setAutoCommit(false); } // Note: investigate batch writing via the jdbc driver: make sure we can still use prepared statements (check out host arrays, too) // -ggolden // common preparation for each insert String statement = insertStatement(); Object fields[] = new Object[6]; // write all events for (Iterator i = events.iterator(); i.hasNext();) { Event event = (Event) i.next(); bindValues(event, fields); // process the insert if (cachingEnabled) { conn = sqlService().borrowConnection(); if (conn.getAutoCommit()) { conn.setAutoCommit(false); } Long eventId = sqlService().dbInsert(conn, statement, fields, "EVENT_ID"); if (eventId != null) { // write event to cache writeEventToCluster(event, eventId); } } else { boolean ok = sqlService().dbWrite(conn, statement, fields); if (!ok) { M_log.warn(this + ".writeBatchEvents(): dbWrite failed: session: " + fields[3] + " event: " + event.toString()); } } } // commit if (!conn.isClosed()) { conn.commit(); } } catch (Exception e) { if (conn != null) { try { conn.rollback(); } catch (Exception ee) { M_log.warn(this + ".writeBatchEvents, while rolling back: " + ee); } } M_log.warn(this + ".writeBatchEvents: " + e, e); } finally { if (conn != null) { try { if (!conn.isClosed() && conn.getAutoCommit() != wasCommit) { conn.setAutoCommit(wasCommit); } } catch (Exception e) { M_log.warn(this + ".writeBatchEvents, while setting auto commit: " + e, e); } sqlService().returnConnection(conn); } } }
From source file:org.wso2.carbon.dashboard.portal.core.datasource.DataBaseHandler.java
/** * To check whether a dashboard related usage information is updated in database * * @param tenantId Id of the tenant which the dashboard belongs to * @param dashboardId Id of the dashboard * @return whether a dashboard related information exist in database * @throws DashboardPortalException//w ww . jav a 2 s .c o m */ public boolean checkDashboard(int tenantId, String dashboardId) throws DashboardPortalException { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = dataBaseInitializer.getDBConnection(); preparedStatement = connection.prepareStatement(DataSourceConstants.SQL_CHECK_DASHBOARD_OPERATION); preparedStatement.setInt(1, tenantId); preparedStatement.setString(2, dashboardId); resultSet = preparedStatement.executeQuery(); if (!connection.getAutoCommit()) { connection.commit(); } if (resultSet.first()) { return true; } } catch (SQLException e) { log.error("Cannot insert the gadget usage info ", e); } finally { closeDatabaseResources(connection, preparedStatement, null); } return false; }
From source file:org.wso2.carbon.dashboard.portal.core.datasource.DataBaseHandler.java
/** * To delete the gadget usage information of partciular gadget in particular dashboard * * @param tenantId Id of the tenant, dashboard belongs to * @param dashboardId Id of the dashboard * @param gadgetId Id of the gadget/*from ww w . jav a 2 s . co m*/ * @throws DashboardPortalException */ public void deleteGadgetUsageInformation(int tenantId, String dashboardId, String gadgetId) throws DashboardPortalException { Connection connection = null; PreparedStatement preparedStatement = null; try { connection = dataBaseInitializer.getDBConnection(); preparedStatement = connection.prepareStatement(DataSourceConstants.SQL_DELETE_GADGET_USAGE_OPERATION); preparedStatement.setInt(1, tenantId); preparedStatement.setString(2, dashboardId); preparedStatement.setString(3, gadgetId); preparedStatement.executeUpdate(); if (!connection.getAutoCommit()) { connection.commit(); } } catch (SQLException e) { log.error("Cannot insert the gadget usage info ", e); } finally { closeDatabaseResources(connection, preparedStatement, null); } }
From source file:org.wso2.carbon.dashboard.portal.core.datasource.DataBaseHandler.java
/** * To update the gadget state information * * @param tenantId Id of the tenant which gadget belongs to * @param gadgetId Id of the gadget//from w ww . j av a 2 s.c om * @param gadgetState State of the gadget, whether is it in active or delete state * @throws DashboardPortalException */ public void updateGadgetStateInformation(int tenantId, String gadgetId, String gadgetState) throws DashboardPortalException { Connection connection = null; PreparedStatement preparedStatement = null; try { connection = dataBaseInitializer.getDBConnection(); preparedStatement = connection.prepareStatement(DataSourceConstants.SQL_UPDATE_GADGET_STATE_OPERATION); preparedStatement.setString(1, gadgetState); preparedStatement.setInt(2, tenantId); preparedStatement.setString(3, gadgetId); preparedStatement.executeUpdate(); if (!connection.getAutoCommit()) { connection.commit(); } } catch (SQLException e) { log.error("Cannot insert the gadget usage info ", e); } finally { closeDatabaseResources(connection, preparedStatement, null); } }
From source file:org.wso2.carbon.identity.application.authentication.framework.store.SessionDataStore.java
private void deleteSTOREOperationsTask(Timestamp timestamp) { Connection connection = null; PreparedStatement statement = null; try {//from www .j av a 2s. c om connection = IdentityDatabaseUtil.getDBConnection(); } catch (IdentityRuntimeException e) { log.error(e.getMessage(), e); return; } try { statement = connection.prepareStatement(sqlDeleteSTORETask); statement.setLong(1, timestamp.getTime()); statement.execute(); if (!connection.getAutoCommit()) { connection.commit(); } return; } catch (SQLException e) { log.error("Error while removing STORE operation data from the database for the timestamp " + timestamp.toString(), e); } finally { IdentityDatabaseUtil.closeAllConnections(connection, null, statement); } }
From source file:org.wso2.carbon.identity.application.authentication.framework.store.SessionDataStore.java
private void deleteDELETEOperationsTask(Timestamp timestamp) { Connection connection = null; PreparedStatement statement = null; try {/*from w w w.j a va 2 s . com*/ connection = IdentityDatabaseUtil.getDBConnection(); } catch (IdentityRuntimeException e) { log.error(e.getMessage(), e); return; } try { statement = connection.prepareStatement(sqlDeleteDELETETask); statement.setLong(1, timestamp.getTime()); statement.execute(); if (!connection.getAutoCommit()) { connection.commit(); } return; } catch (SQLException e) { log.error("Error while removing DELETE operation data from the database for the timestamp " + timestamp.toString(), e); } finally { IdentityDatabaseUtil.closeAllConnections(connection, null, statement); } }
From source file:org.ralasafe.application.ApplicationManagerImpl.java
public void updateApplication(Application app) { loadIntoMemory();//from ww w.ja v a 2s. c om Application originalApplication = getApplication(app.getName()); if (originalApplication == null) { return; } // get a copy of original application Collection origUserTypes = originalApplication.getUserTypes(); Collection newUserTypes = app.getUserTypes(); Connection conn = null; boolean autoCommit = true; try { conn = DBPower.getConnection(table.getId()); autoCommit = conn.getAutoCommit(); conn.setAutoCommit(false); // delete original app-usertype ApplicationUserType hintUserType = new ApplicationUserType(); hintUserType.setAppName(app.getName()); applicationUserTypeDeletor.delete(conn, appNameUserTypeTableWhereEmt, hintUserType); // save updated app-usertype relationship Collection userTypes = app.getUserTypes(); if (userTypes != null && userTypes.size() > 0) { List appUserTypes = new ArrayList(userTypes.size()); for (Iterator iter = userTypes.iterator(); iter.hasNext();) { UserType userType = (UserType) iter.next(); ApplicationUserType appUserType = new ApplicationUserType(); appUserType.setAppName(app.getName()); appUserType.setUserTypeName(userType.getName()); String produceUserMetadataStr = produceUserMetadataStr(userType.getUserMetadata()); appUserType.setUserMetadataStr(produceUserMetadataStr); appUserTypes.add(appUserType); } applicationUserTypeSaver.batchSave(conn, appUserTypes); } // update app info try { updator.updateByIdColumns(conn, app); } catch (EntityExistException e) { e.printStackTrace(); throw new DBLevelException(e); } // update userrole tables // 1, find out which usertype(s) to be newly added and which to be deleted Iterator origItr = origUserTypes.iterator(); while (origItr.hasNext()) { UserType origUserType = (UserType) origItr.next(); Iterator newItr = newUserTypes.iterator(); while (newItr.hasNext()) { UserType newUserType = (UserType) newItr.next(); if (origUserType.getName().equals(newUserType.getName())) { // this usertype is updated, move out origItr.remove(); newItr.remove(); } } } Collection userTypesToBeDeleted = origUserTypes; Collection userTypesToBeAdded = newUserTypes; // 2, delete related userrole tables Iterator delItr = userTypesToBeDeleted.iterator(); while (delItr.hasNext()) { UserType delUserType = (UserType) delItr.next(); DBUtil.exec(conn, DBUtil.userRoleTableDropSql(app.getName(), delUserType.getName())); } // 3, create related userrole tables Iterator addItr = userTypesToBeAdded.iterator(); while (addItr.hasNext()) { UserType delUserType = (UserType) addItr.next(); delUserType = Factory.getUserTypeManager().getUserType(delUserType.getName()); TableMetadata userTable = delUserType.getUserMetadata().getMainTableMetadata(); DBUtil.exec(conn, DBUtil.userRoleTableCreateSql(app.getName(), delUserType.getName(), User.idFieldName, getIdColumnType(userTable))); } conn.commit(); } catch (SQLException e) { DBUtil.rollback(conn); throw new DBLevelException(e); } finally { DBUtil.setCommitMode(conn, autoCommit); DBUtil.close(conn); } changed = true; // notify Factory Factory.applicationChanged(app.getName()); }
From source file:org.wso2.carbon.identity.application.authentication.framework.store.SessionDataStore.java
public void removeExpiredSessionData(Timestamp timestamp) { Connection connection = null; PreparedStatement statement = null; try {// w ww . ja v a2 s . c o m connection = IdentityDatabaseUtil.getDBConnection(); } catch (IdentityRuntimeException e) { log.error(e.getMessage(), e); return; } try { statement = connection.prepareStatement(sqlDeleteExpiredDataTask); statement.setLong(1, timestamp.getTime()); statement.execute(); if (!connection.getAutoCommit()) { connection.commit(); } } catch (SQLException e) { log.error( "Error while removing session data from the database for the timestamp " + timestamp.toString(), e); } finally { IdentityDatabaseUtil.closeAllConnections(connection, null, statement); } }
From source file:io.github.retz.db.Database.java
public void deleteApplication(Connection conn, String appid) throws SQLException { if (conn.getAutoCommit()) { throw new AssertionError("autocommit must be false"); }/*from ww w . j ava2 s .com*/ try (PreparedStatement p = conn.prepareStatement("DELETE FROM applications where appid=?")) { p.setString(1, appid); p.execute(); } }
From source file:org.opendatakit.common.persistence.engine.mysql.TaskLockImpl.java
private TaskLockTable doTransaction(TaskLockTable entity, long l) throws ODKEntityNotFoundException, ODKTaskLockException { boolean first; final List<String> stmts = new ArrayList<String>(); final String uri = entity.getUri(); StringBuilder b = new StringBuilder(); String tableName = K_BQ + datastore.getDefaultSchemaName() + K_BQ + "." + K_BQ + TaskLockTable.TABLE_NAME + K_BQ;/*w ww. j av a 2 s. co m*/ // String tableName= TaskLockTable.TABLE_NAME; b.append("SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE"); stmts.add(b.toString()); b.setLength(0); b.append("START TRANSACTION WITH CONSISTENT SNAPSHOT"); stmts.add(b.toString()); b.setLength(0); b.append("SET @present := NOW(),"); b.append(" @uriUser := '"); b.append(user.getUriUser().replaceAll("'", "''")); b.append("',"); b.append(" @uriLock := '"); b.append(uri.replaceAll("'", "''")); b.append("',"); b.append(" @formId := '"); b.append(entity.getFormId().replaceAll("'", "''")); b.append("',"); b.append(" @taskType := '"); b.append(entity.getTaskType().replaceAll("'", "''")); b.append("',"); b.append(" @lifetimeMicroseconds := "); b.append(1000L * l); stmts.add(b.toString()); b.setLength(0); b.append("LOCK TABLES "); b.append(tableName); b.append(" WRITE "); stmts.add(b.toString()); b.setLength(0); dam.recordPutUsage(TaskLockTable.TABLE_NAME); if (!entity.isFromDatabase()) { // insert a new record b.append("REPLACE INTO "); b.append(tableName); b.append(" ("); first = true; for (DataField f : entity.getFieldList()) { if (!first) { b.append(","); } first = false; b.append(K_BQ); b.append(f.getName()); b.append(K_BQ); } first = true; b.append(") VALUES ( "); for (DataField f : entity.getFieldList()) { if (!first) { b.append(","); } first = false; if (f.equals(entity.creationDate) || f.equals(entity.lastUpdateDate)) { b.append("@present"); } else if (f.equals(entity.creatorUriUser) || f.equals(entity.lastUpdateUriUser)) { b.append("@uriUser"); } else if (f.equals(entity.formId)) { b.append("@formId"); } else if (f.equals(entity.taskType)) { b.append("@taskType"); } else if (f.equals(entity.primaryKey)) { b.append("@uriLock"); } else if (f.equals(entity.expirationDateTime)) { b.append(" DATE_ADD(CAST(@present AS DATETIME), INTERVAL @lifetimeMicroseconds MICROSECOND)"); } else { throw new IllegalStateException("unexpected case " + f.getName()); } } b.append(")"); stmts.add(b.toString()); b.setLength(0); } else { // update existing record b.append("UPDATE "); b.append(tableName); b.append(" SET "); first = true; for (DataField f : entity.getFieldList()) { if (f == entity.primaryKey) continue; if (!first) { b.append(","); } first = false; b.append(K_BQ); b.append(f.getName()); b.append(K_BQ); b.append(" = "); if (f.equals(entity.creationDate) || f.equals(entity.lastUpdateDate)) { b.append("@present"); } else if (f.equals(entity.creatorUriUser) || f.equals(entity.lastUpdateUriUser)) { b.append("@uriUser"); } else if (f.equals(entity.formId)) { b.append("@formId"); } else if (f.equals(entity.taskType)) { b.append("@taskType"); } else if (f.equals(entity.primaryKey)) { b.append("@uriLock"); } else if (f.equals(entity.expirationDateTime)) { b.append(" DATE_ADD(CAST(@present AS DATETIME), INTERVAL @lifetimeMicroseconds MICROSECOND)"); } else { throw new IllegalStateException("unexpected case " + f.getName()); } } b.append(" WHERE "); b.append(K_BQ); b.append(entity.primaryKey.getName()); b.append(K_BQ); b.append(" = "); b.append("@uriLock"); stmts.add(b.toString()); b.setLength(0); } // delete stale locks (don't care who's) dam.recordDeleteUsage(TaskLockTable.TABLE_NAME); b.append("DELETE FROM "); b.append(tableName); b.append(" WHERE "); b.append(K_BQ); b.append(entity.expirationDateTime.getName()); b.append(K_BQ); b.append(" <= CAST(@present AS DATETIME)"); stmts.add(b.toString()); b.setLength(0); // determine the time of the oldest lock for this resource and task type... // do this by querying for the minimum expiration time // BUT, first, set the minimum time to the present time in case there are no locks. b.append("SET @minExpiration = @present"); stmts.add(b.toString()); b.setLength(0); dam.recordQueryUsage(TaskLockTable.TABLE_NAME, 1); b.append("SELECT @minExpiration := MIN("); b.append(K_BQ); b.append(entity.expirationDateTime.getName()); b.append(K_BQ); b.append(") FROM "); b.append(tableName); b.append(" WHERE "); b.append(K_BQ); b.append(entity.formId.getName()); b.append(K_BQ); b.append(" = @formId AND "); b.append(K_BQ); b.append(entity.taskType.getName()); b.append(K_BQ); b.append(" = @taskType"); stmts.add(b.toString()); b.setLength(0); // determine if there are two or more records matching // the minimum expiration time. If there are, we must // release the locks and retry, as we cannot determine // which one is first. b.append("SET @uriCount = 0"); stmts.add(b.toString()); b.setLength(0); b.append("SELECT @uriCount := COUNT("); b.append(K_BQ); b.append(entity.primaryKey.getName()); b.append(K_BQ); b.append(") FROM "); b.append(tableName); b.append(" WHERE "); b.append(K_BQ); b.append(entity.formId.getName()); b.append(K_BQ); b.append(" = @formId AND "); b.append(K_BQ); b.append(entity.taskType.getName()); b.append(K_BQ); b.append(" = @taskType AND "); b.append(K_BQ); b.append(entity.expirationDateTime.getName()); b.append(K_BQ); b.append(" = CAST(@minExpiration AS DATETIME)"); stmts.add(b.toString()); b.setLength(0); // delete all locks except the oldest one for this resource and task type... // or, if we have two or more old locks, release ours // whatever lock exists identifies the owner of the resource. dam.recordDeleteUsage(TaskLockTable.TABLE_NAME); b.append("DELETE FROM "); b.append(tableName); b.append(" WHERE "); b.append(K_BQ); b.append(entity.formId.getName()); b.append(K_BQ); b.append(" = @formId AND "); b.append(K_BQ); b.append(entity.taskType.getName()); b.append(K_BQ); b.append(" = @taskType AND ( "); b.append(K_BQ); b.append(entity.expirationDateTime.getName()); b.append(K_BQ); b.append(" > CAST(@minExpiration AS DATETIME)"); b.append(" OR ( @uriCount > 1 AND "); b.append(K_BQ); b.append(entity.expirationDateTime.getName()); b.append(K_BQ); b.append(" = CAST(@minExpiration AS DATETIME)"); b.append(" AND "); b.append(K_BQ); b.append(entity.primaryKey.getName()); b.append(K_BQ); b.append(" = @uriLock ) )"); stmts.add(b.toString()); b.setLength(0); // and within the transaction, see if the primary key of the winning lock is ours... b.append("SELECT "); b.append(K_BQ); b.append(entity.primaryKey.getName()); b.append(K_BQ); b.append(" FROM "); b.append(tableName); b.append(" WHERE "); b.append(K_BQ); b.append(entity.formId.getName()); b.append(K_BQ); b.append(" = @formId AND "); b.append(K_BQ); b.append(entity.taskType.getName()); b.append(K_BQ); b.append(" = @taskType AND "); b.append(K_BQ); b.append(entity.expirationDateTime.getName()); b.append(K_BQ); b.append(" = CAST(@minExpiration AS DATETIME)"); stmts.add(b.toString()); b.setLength(0); b.append("UNLOCK TABLES"); stmts.add(b.toString()); b.setLength(0); b.append("COMMIT"); stmts.add(b.toString()); b.setLength(0); TaskLockTable relation; try { relation = TaskLockTable.assertRelation(datastore, user); } catch (ODKDatastoreException e) { throw new ODKTaskLockException(PERSISTENCE_LAYER_PROBLEM, e); } boolean success = false; try { JdbcTemplate jdbc = datastore.getJdbcConnection(); Object o = jdbc.execute(new ConnectionCallback<Object>() { @Override public Object doInConnection(Connection conn) throws SQLException, DataAccessException { boolean success = false; boolean oldValue = conn.getAutoCommit(); try { conn.setAutoCommit(false); conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); String lastResult = null; for (String s : stmts) { Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT); if (s.startsWith("SELECT")) { ResultSet rs = stmt.executeQuery(s); if (rs.first()) { lastResult = rs.getString(1); } rs.close(); } else { stmt.executeUpdate(s); } stmt.close(); } conn.commit(); success = uri.equals(lastResult); } catch (Exception e) { e.printStackTrace(); conn.rollback(); } finally { if (!success) { Statement stmt = conn.createStatement(); LogFactory.getLog(TaskLockImpl.class).info("UNLOCK TABLES"); stmt.execute("UNLOCK TABLES"); conn.commit(); } } conn.setAutoCommit(oldValue); return success ? uri : null; } }); success = o != null && uri.equals((String) o); } catch (Exception e) { throw new ODKTaskLockException(PERSISTENCE_LAYER_PROBLEM, e); } if (success) { return (TaskLockTable) datastore.getEntity(relation, uri, user); } else { throw new ODKEntityNotFoundException(); } }