List of usage examples for java.sql Connection rollback
void rollback() throws SQLException;
Connection
object. From source file:com.concursive.connect.web.modules.activity.utils.ProjectHistoryUtils.java
public synchronized static void insertReply(Connection db, ProjectHistory parentProjectHistory, ProjectHistoryReplyBean reply, User user) throws SQLException { // Construct a project history based on the parent project history and the reply bean ProjectHistory projectHistory = new ProjectHistory(); projectHistory.setEnteredBy(user.getId()); projectHistory.setProjectId(parentProjectHistory.getProjectId()); projectHistory.setEventType(ProjectHistoryList.ADD_ACTIVITY_ENTRY_EVENT); if (ProjectHistoryList.SITE_CHATTER_OBJECT.equals(parentProjectHistory.getLinkObject())) { // Maintain the site-chatter value projectHistory.setLinkObject(ProjectHistoryList.SITE_CHATTER_OBJECT); } else {// w w w .ja va 2s. c o m // Default to a user-entry value projectHistory.setLinkObject(ProjectHistoryList.ACTIVITY_ENTRY_OBJECT); } projectHistory.setLinkItemId(user.getId()); // @todo move to application.xml projectHistory .setDescription(WikiLink.generateLink(user.getProfileProject()) + (parentProjectHistory.getProjectId() != user.getProfileProject().getId() ? " @" + WikiLink.generateLink(parentProjectHistory.getProject()) : "") + (user.getId() != parentProjectHistory.getEnteredBy() ? " in reply to " + WikiLink.generateLink( UserUtils.loadUser(parentProjectHistory.getEnteredBy()).getProfileProject()) : "") + ": " + WikiUtils.addWikiLinks(reply.getDescription())); projectHistory.setParentId(parentProjectHistory.getId()); if (parentProjectHistory.getTopId() > -1) { projectHistory.setTopId(parentProjectHistory.getTopId()); } else { projectHistory.setTopId(parentProjectHistory.getId()); } projectHistory.setPosition(ProjectHistoryUtils.findNextPosition(db, projectHistory.getTopId())); projectHistory.setThreadPosition(ProjectHistoryUtils.findNextThreadPosition(db, parentProjectHistory)); projectHistory.setIndent(parentProjectHistory.getIndent() + 1); projectHistory.setRelativeEnteredby(parentProjectHistory.getEnteredBy()); projectHistory.setLineage(parentProjectHistory.getLineage() + parentProjectHistory.getId() + "/"); // Reply transaction try { db.setAutoCommit(false); projectHistory.updateThreadPosition(db); projectHistory.updateChildCount(db); projectHistory.insert(db); projectHistory.updateRelativeDate(db); db.commit(); } catch (Exception e) { db.rollback(); } finally { db.setAutoCommit(true); } }
From source file:com.anyuan.thomweboss.persistence.jdbcimpl.user.UserDaoJdbcImpl.java
@Override public boolean save(User entity) { Connection conn = getConnection(); boolean result = false; String userSql = "insert into t_user (f_username, f_nickname, f_loginname, f_password, " + "f_birthday, f_gender, f_createtime, f_logintime, f_roleid, f_contactid, " + "f_description) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; try {// w w w .java 2 s . c om conn.setAutoCommit(false); Contact contact = entity.getContact(); Address address = contact.getAddress(); saveAddress(conn, address); // address id not modify, Addressgettersetter Phone phone = contact.getPhone(); savePhone(conn, phone); saveContact(conn, contact); PreparedStatement preState = conn.prepareStatement(userSql); preState.setObject(1, entity.getUsername()); preState.setString(2, entity.getNickname()); preState.setString(3, entity.getLoginname()); preState.setString(4, entity.getPassword()); preState.setObject(5, entity.getBirthday()); preState.setObject(6, entity.getGender()); preState.setObject(7, entity.getCreatetime()); preState.setObject(8, entity.getLogintime()); // ? preState.setObject(9, null); preState.setObject(10, entity.getContact().getId()); preState.setObject(11, entity.getDescription()); result = preState.execute(); conn.commit(); } catch (SQLException e) { e.printStackTrace(); try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } finally { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return result; }
From source file:org.sakaiproject.genericdao.springjdbc.JdbcGenericDao.java
/** * This will do a rollback on the DB Connection on this thread, * allows the developer to force an immediate rollback <br/> * Remember to close your connection if you are completely done with it * /*from w w w . j a v a2 s . com*/ * @return true if the rollback executed successfully */ public boolean rollbackTransaction() { boolean success = false; Connection conn = getConnection(); boolean previousAutocommit = false; try { previousAutocommit = conn.getAutoCommit(); conn.rollback(); conn.setAutoCommit(previousAutocommit); success = true; } catch (SQLException e) { logWarn("Could not rollback sucessfully: " + e.getMessage()); success = false; try { conn.setAutoCommit(previousAutocommit); } catch (SQLException e1) { // nothing to do here but continue } } // removed: try-finally-releaseConnection(conn); return success; }
From source file:com.hangum.tadpole.importdb.core.dialog.importdb.sql.SQLToDBImportDialog.java
/** * select? execute ./* w w w . ja v a2 s . c om*/ * * @param listQuery * @throws Exception */ private int runSQLExecuteBatch(List<String> listQuery) throws Exception { java.sql.Connection conn = null; Statement statement = null; int result = 0; try { SqlMapClient client = TadpoleSQLManager.getInstance(userDB); conn = client.getDataSource().getConnection(); conn.setAutoCommit(false); statement = conn.createStatement(); int count = 0; for (String strQuery : listQuery) { if ("".equals(StringUtils.trimToEmpty(strQuery))) //$NON-NLS-1$ continue; statement.addBatch(strQuery); if (++count % batchSize == 0) { try { statement.executeBatch(); } catch (SQLException e) { logger.error("Execute Batch error", e); //$NON-NLS-1$ bufferBatchResult.append(e.getMessage() + "\n"); //$NON-NLS-1$ SQLException ne = e.getNextException(); while (ne != null) { logger.error("NEXT SQLException is ", ne);//$NON-NLS-1$ bufferBatchResult.append(ne.getMessage() + "\n"); ne = ne.getNextException(); } if (btnIgnore.getSelection()) { conn.commit(); continue; } else { conn.rollback(); result = -1; break; } } } } statement.executeBatch(); conn.commit(); conn.setAutoCommit(true); if (result < 0 && !"".equals(bufferBatchResult.toString())) { //$NON-NLS-1$ MessageDialog.openError(null, Messages.CsvToRDBImportDialog_4, bufferBatchResult.toString()); } } catch (SQLException e) { logger.error("Execute Batch error", e); //$NON-NLS-1$ bufferBatchResult.append(e.getMessage() + "\n"); //$NON-NLS-1$ if (btnIgnore.getSelection()) { conn.commit(); } else { conn.rollback(); } SQLException ne = e.getNextException(); while (ne != null) { logger.error("Execute Batch error", e); //$NON-NLS-1$ bufferBatchResult.append(e.getMessage() + "\n"); //$NON-NLS-1$ ne = ne.getNextException(); } } catch (Exception e) { result = -1; logger.error("Execute Batch error", e); //$NON-NLS-1$ bufferBatchResult.append(e.getMessage() + "\n"); //$NON-NLS-1$ conn.rollback(); throw e; } finally { try { if (statement != null) statement.close(); } catch (Exception e) { } try { if (conn != null) conn.close(); } catch (Exception e) { } } return result; }
From source file:com.hangum.tadpole.importexport.core.dialogs.SQLToDBImportDialog.java
/** * select? execute ./*from w w w . j ava 2s. c o m*/ * * @param listQuery * @throws Exception */ private int runSQLExecuteBatch(List<String> listQuery) throws Exception { java.sql.Connection conn = null; Statement statement = null; int result = 0; try { SqlMapClient client = TadpoleSQLManager.getInstance(userDB); conn = client.getDataSource().getConnection(); conn.setAutoCommit(false); statement = conn.createStatement(); int count = 0; for (String strQuery : listQuery) { if ("".equals(StringUtils.trimToEmpty(strQuery))) //$NON-NLS-1$ continue; statement.addBatch(strQuery); if (++count % batchSize == 0) { try { statement.executeBatch(); } catch (SQLException e) { logger.error("Execute Batch error", e); //$NON-NLS-1$ bufferBatchResult.append(e.getMessage() + "\n"); //$NON-NLS-1$ SQLException ne = e.getNextException(); while (ne != null) { logger.error("NEXT SQLException is ", ne);//$NON-NLS-1$ bufferBatchResult.append(ne.getMessage() + "\n"); //$NON-NLS-1$ ne = ne.getNextException(); } if (btnIgnore.getSelection()) { conn.commit(); continue; } else { conn.rollback(); result = -1; break; } } } } statement.executeBatch(); conn.commit(); conn.setAutoCommit(true); if (result < 0 && !"".equals(bufferBatchResult.toString())) { //$NON-NLS-1$ MessageDialog.openWarning(null, Messages.get().Warning, bufferBatchResult.toString()); } } catch (SQLException e) { logger.error("Execute Batch error", e); //$NON-NLS-1$ bufferBatchResult.append(e.getMessage() + "\n"); //$NON-NLS-1$ if (btnIgnore.getSelection()) { conn.commit(); } else { conn.rollback(); } SQLException ne = e.getNextException(); while (ne != null) { logger.error("Execute Batch error", e); //$NON-NLS-1$ bufferBatchResult.append(e.getMessage() + "\n"); //$NON-NLS-1$ ne = ne.getNextException(); } } catch (Exception e) { result = -1; logger.error("Execute Batch error", e); //$NON-NLS-1$ bufferBatchResult.append(e.getMessage() + "\n"); //$NON-NLS-1$ conn.rollback(); throw e; } finally { try { if (statement != null) statement.close(); } catch (Exception e) { } try { if (conn != null) conn.close(); } catch (Exception e) { } } return result; }
From source file:gridool.db.sql.ParallelSQLMapTask.java
@Override protected ParallelSQLMapTaskResult execute() throws GridException { assert (registry != null); final File tmpFile; try {/*www . j a va2 s . co m*/ tmpFile = File.createTempFile("PSQLMap" + taskNumber + '_', '_' + NetUtils.getLocalHostAddress()); } catch (IOException e) { throw new GridException(e); } final QueryString[] queries = SQLTranslator.divideQuery(query, true); final boolean singleStatement = (queries.length == 1); final String selectQuery = singleStatement ? query : SQLTranslator.selectFirstSelectQuery(queries); GridNode localNode = config.getLocalNode(); GridNode senderNode = getSenderNode(); assert (senderNode != null); final boolean useCreateTableAS = senderNode.equals(localNode); final int fetchedRows; final LockManager lockMgr = registry.getLockManager(); final ReadWriteLock rwlock = lockMgr.obtainLock(DBAccessor.SYS_TABLE_SYMBOL); final Lock lock = rwlock.writeLock(); // REVIEWME tips: exclusive lock for system table in MonetDB long startQueryTime = System.currentTimeMillis(); final Connection dbConn = getDbConnection(taskMasterNode, registry); try { lock.lock(); if (singleStatement) { // #1 invoke COPY INTO file if (useCreateTableAS) { dbConn.setAutoCommit(true); fetchedRows = executeCreateTableAs(dbConn, selectQuery, taskTableName); } else { dbConn.setAutoCommit(false); fetchedRows = executeCopyIntoFile(dbConn, selectQuery, taskTableName, tmpFile); dbConn.commit(); } } else { dbConn.setAutoCommit(false); // #1-1 DDL before map SELECT queries (e.g., create view) issueDDLBeforeSelect(dbConn, queries); // #1-2 invoke COPY INTO file if (useCreateTableAS) { fetchedRows = executeCreateTableAs(dbConn, selectQuery, taskTableName); } else { fetchedRows = executeCopyIntoFile(dbConn, selectQuery, taskTableName, tmpFile); } // #1-3 DDL after map SELECT queries (e.g., drop view) issueDDLAfterSelect(dbConn, queries); dbConn.commit(); } assert (fetchedRows != -1); } catch (SQLException sqle) { String errmsg = "Failed to execute a query: \n" + query; LOG.error(errmsg, sqle); if (singleStatement) { try { dbConn.rollback(); } catch (SQLException rbe) { LOG.warn("Rollback failed", rbe); } } new FileDeletionThread(tmpFile, LOG).start(); throw new GridException(errmsg, sqle); } catch (Throwable e) { String errmsg = "Failed to execute a query: \n" + query; LOG.fatal(errmsg, e); if (singleStatement) { try { dbConn.rollback(); } catch (SQLException rbe) { LOG.warn("Rollback failed", rbe); } } new FileDeletionThread(tmpFile, LOG).start(); throw new GridException(errmsg, e); } finally { lock.unlock(); JDBCUtils.closeQuietly(dbConn); } long queryExecTime = System.currentTimeMillis() - startQueryTime; String sentFileName = null; long sendResultTime = -1L; // would be null for a local task if (fetchedRows > 0) { // #2 send file long startResultTime = System.currentTimeMillis(); try { TransferUtils.sendfile(tmpFile, dstAddr, dstPort, false, true); sendResultTime = System.currentTimeMillis() - startResultTime; sentFileName = tmpFile.getName(); } catch (IOException e) { throw new GridException("failed to sending a file", e); } finally { new FileDeletionThread(tmpFile, LOG).start(); } } return new ParallelSQLMapTaskResult(taskMasterNode, sentFileName, taskNumber, fetchedRows, queryExecTime, sendResultTime); }
From source file:backtype.storm.scheduler.adaptive.DataManager.java
public void removeTopologies(List<String> topologies) throws Exception { Connection connection = null; Statement statement = null;//from w w w. ja v a 2 s . c o m logger.debug("Going to remove these topologies: " + Utils.collectionToString(topologies)); try { connection = getConnection(); connection.setAutoCommit(false); statement = connection.createStatement(); for (String topology : topologies) { logger.debug("Removing load stats of topology " + topology); String sql = "delete from `load` where topology_id in (select id from topology where storm_id = '" + topology + "')"; logger.debug("SQL script: " + sql); statement.execute(sql); logger.debug("Removing traffic stats of topology " + topology); sql = "delete from traffic where topology_id in (select id from topology where storm_id = '" + topology + "')"; logger.debug("SQL script: " + sql); statement.execute(sql); logger.debug("Removing topology " + topology); sql = "delete from topology where storm_id = '" + topology + "'"; logger.debug("SQL script: " + sql); statement.execute(sql); } connection.commit(); } catch (Exception e) { logger.error("An error occurred removing topologies", e); connection.rollback(); throw e; } finally { if (statement != null) statement.close(); if (connection != null) { connection.setAutoCommit(true); connection.close(); } } }
From source file:com.clustercontrol.platform.infra.InfraJdbcExecutorSupport.java
public static String execSelectFileContent(String fileId, String fileName) throws HinemosUnknown { Connection conn = null; JpaTransactionManager tm = null;//from w ww . ja v a 2 s .c o m PGCopyInputStream pgStream = null; OutputStream fos = null; try { tm = new JpaTransactionManager(); tm.begin(); conn = tm.getEntityManager().unwrap(java.sql.Connection.class); conn.setAutoCommit(false); String exportDirectory = HinemosPropertyUtil.getHinemosPropertyStr("infra.export.dir", HinemosPropertyDefault.getString(HinemosPropertyDefault.StringKey.INFRA_EXPORT_DIR)); String filepath = exportDirectory + "/" + fileName; pgStream = new PGCopyInputStream((PGConnection) conn, "COPY (select file_content from binarydata.cc_infra_file_content where file_id = '" + fileId + "') TO STDOUT WITH (FORMAT BINARY)"); fos = Files.newOutputStream(Paths.get(filepath)); // ????(?21byte)????? long skipLen = pgStream.skip(21); if (skipLen != 21) { String message = "error in the binary format file parsing (skip tuple from sign) skipLen = " + skipLen; log.warn(message); throw new HinemosUnknown(message); } byte[] lenBuf = new byte[4]; int ret = pgStream.read(lenBuf, 0, lenBuf.length); if (ret == -1) { String message = "error in the binary format file parsing (read file length)"; log.warn(message); throw new HinemosUnknown(message); } int len = ByteBuffer.wrap(lenBuf).getInt(); byte[] buf = new byte[1024 * 1024]; int read; int readTotalSize = 0; while ((read = pgStream.read(buf)) != -1) { readTotalSize += read; if (readTotalSize > len) { // ? if ((readTotalSize - len) == 2) { fos.write(buf, 0, read - 2); break; } else { fos.write(buf, 0, read - 1); break; } } else { fos.write(buf, 0, read); } } if (!tm.isNestedEm()) { conn.commit(); } tm.commit(); return filepath; } catch (SQLException | IOException | RuntimeException e) { log.warn(e.getMessage(), e); if (conn != null) { try { conn.rollback(); } catch (SQLException e1) { log.warn(e1); } } throw new HinemosUnknown(e.getMessage(), e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { log.warn(e.getMessage(), e); throw new HinemosUnknown(e.getMessage(), e); } } if (pgStream != null) { try { pgStream.close(); } catch (IOException e) { log.warn(e.getMessage(), e); throw new HinemosUnknown(e.getMessage(), e); } } if (tm != null) { tm.close(); } } }
From source file:com.concursive.connect.web.modules.documents.dao.FileFolder.java
/** * Deletes the folder and any enclosed files * * @param db Description of the Parameter * @return Description of the Return Value * @throws SQLException Description of the Exception *//*from w w w .j ava 2 s. c o m*/ public boolean delete(Connection db, String baseFilePath) throws SQLException { if (id == -1) { return false; } boolean result = false; boolean commit = db.getAutoCommit(); try { if (commit) { db.setAutoCommit(false); } // Build a list of files to delete FileItemList fileItemList = new FileItemList(); fileItemList.setFolderId(id); fileItemList.buildList(db); fileItemList.delete(db, baseFilePath); // Build a list of folders to delete FileFolderList folderList = new FileFolderList(); folderList.setParentId(id); folderList.buildList(db); folderList.delete(db, baseFilePath); // Delete this folder PreparedStatement pst = db.prepareStatement("DELETE FROM project_folders " + "WHERE folder_id = ?"); pst.setInt(1, id); pst.execute(); pst.close(); if (commit) { db.commit(); } result = true; } catch (Exception e) { LOG.error("Could not delete folder", e); if (commit) { db.rollback(); } } finally { if (commit) { db.setAutoCommit(true); } } return result; }
From source file:com.moss.schematrax.SchemaUpdater.java
public void updateSchema(DatabaseType databaseType, Connection sqlConnection, String schema, String schemaVersion) throws SchematraxException { try {/* w w w . j a va 2s.c o m*/ if (manageTransactions) sqlConnection.setAutoCommit(false); List appliedUpdates = listAppliedUpdates(sqlConnection, schema); /* * PROCESS THE SQL UPDATES */ List<SchemaVersion> versionsList = new ArrayList<SchemaVersion>(); // Create an array of all prior versions SchemaVersion version = schemaData.getVersion(schemaVersion); versionsList.add(version); while (version.getPriorVersion() != null) { version = version.getPriorVersion(); versionsList.add(version); } for (int x = versionsList.size() - 1; x > -1; x--) { version = (SchemaVersion) versionsList.get(x); applyUpdatesForVersion(version, appliedUpdates, databaseType, schema, sqlConnection); } // WE'RE DONE! NOTIFY THE INJECTORS for (Injector injector : injectors) { injector.updateComplete(); } if (manageTransactions) sqlConnection.commit(); } catch (Exception e) { try { if (manageTransactions) sqlConnection.rollback(); if (e instanceof SchematraxException) throw (SchematraxException) e; throw new SchemaUpdateException(e); } catch (SQLException e1) { log.fatal("An update failed.", e); // this is so that we still get the root cause somewhere throw new SchemaUpdateException(e1); } } }