List of usage examples for java.sql Connection setAutoCommit
void setAutoCommit(boolean autoCommit) throws SQLException;
From source file:com.autentia.tnt.bill.migration.BillToBillPaymentMigration.java
/** * executes an script received by parameter * @param script the script to be launched *//*w w w. j a v a 2 s.c om*/ private static void executeScript(String script) throws Exception { Connection con = null; Statement stmt = null; LineNumberReader file = null; String delimiter = ";"; try { log.debug("LOADING DATABASE SCRIPT" + script); // connect to database Class.forName(DATABASE_DRIVER); con = DriverManager.getConnection(DATABASE_CONNECTION, DATABASE_USER, DATABASE_PASS); //NOSONAR con.setAutoCommit(false); // DATABASE_PASS es nula stmt = con.createStatement(); // load file InputStream sqlScript = Thread.currentThread().getContextClassLoader().getResourceAsStream(script); if (sqlScript == null) { throw new FileNotFoundException(script); } file = new LineNumberReader(new InputStreamReader(new BufferedInputStream(sqlScript), "UTF-8")); // Add batched SQL sentences to statement StringBuilder sentence = new StringBuilder(); String line; while ((line = file.readLine()) != null) { line = line.trim(); if (!line.startsWith("--")) { // Interpret "DELIMITER" sentences if (line.trim().toUpperCase(Locale.ENGLISH).startsWith("DELIMITER")) { delimiter = line.trim().substring("DELIMITER".length()).trim(); } else { // Add line to sentence if (line.endsWith(delimiter)) { // Remove delimiter String lastLine = line.substring(0, line.length() - delimiter.length()); // Append line to sentence sentence.append(lastLine); // Execute sentence log.debug(" " + sentence.toString()); stmt.addBatch(sentence.toString()); // Prepare new sentence sentence = new StringBuilder(); } else { // Append line to sentence sentence.append(line); // Append separator for next line sentence.append(" "); } } } } // Execute batch log.debug("upgradeDatabase - executing batch of commands"); stmt.executeBatch(); // Commit transaction log.debug("upgradeDatabase - commiting changes to database"); con.commit(); // Report end of migration log.debug("END LOADING DATABASE SCRIPT"); } catch (Exception e) { log.error("FAILED: WILL BE ROLLED BACK: ", e); if (con != null) { con.rollback(); } } finally { cierraFichero(file); liberaConexion(con, stmt, null); } }
From source file:com.concursive.connect.web.modules.profile.utils.ProjectCopier.java
public static Project clone(CloneBean bean, Connection db, int groupId, int userId) throws SQLException { Project project = null;/*from www .j a va 2s. co m*/ try { db.setAutoCommit(false); int oldProjectId = bean.getProjectId(); // Load permissions and resources for this member LOG.debug("ProjectCopier-> ProjectId: " + oldProjectId); LOG.debug("ProjectCopier-> UserId: " + userId); User user = UserUtils.loadUser(userId); LookupList roleList = new LookupList(db, "lookup_project_role"); // Load old project, change some values, save as new project project = new Project(db, oldProjectId); TeamMember member = null; if (!project.getPortal()) { member = new TeamMember(db, oldProjectId, userId); } // Offset in days long offset = 0; if (bean.getResetActivityDates() && bean.getRequestDate() != null && project.getRequestDate() != null) { offset = bean.getRequestDate().getTime() - project.getRequestDate().getTime(); } project.setId(-1); project.setUniqueId(null); project.setGroupId(groupId); project.setEnteredBy(userId); project.setModifiedBy(userId); project.setEntered((Timestamp) null); project.setModified((Timestamp) null); if (bean.getTitle() != null) { project.setTitle(bean.getTitle()); } else { project.setTitle(project.getTitle() + " (copy)"); } if (!hasPermission(db, project, user, member, "project-details-view", roleList)) { project.setRequestedBy(""); project.setRequestedByDept(""); project.setBudget(0); } if (bean.getRequestDate() != null) { project.setRequestDate(bean.getRequestDate()); } else { project.setRequestDate(new Timestamp(System.currentTimeMillis())); } project.setClosed(false); project.setCloseDate((Timestamp) null); project.setEstimatedCloseDate((Timestamp) null); project.setApprovalDate((Timestamp) null); project.setApproved(false); project.setClone(true); project.buildPermissionList(db); project.insert(db); if (project.getId() == -1) { throw new SQLException("Project object validation failed"); } project.updateFeatures(db); // Permissions PermissionList permissions = new PermissionList(); permissions.setProjectId(oldProjectId); permissions.buildList(db); permissions.setProjectId(project.getId()); permissions.insert(db); // Team if (bean.getCloneTeam() && hasPermission(db, project, user, member, "project-team-view", roleList)) { TeamMemberList team = new TeamMemberList(); team.setProjectId(oldProjectId); team.buildList(db); team.setProjectId(project.getId()); team.setEnteredBy(userId); team.setModifiedBy(userId); team.removeTeamMember(userId); team.insert(db); } // Add the current user to the team as Project Lead int roleUserLevel = roleList.getIdFromLevel(TeamMember.PROJECT_ADMIN); TeamMember thisMember = new TeamMember(); thisMember.setProjectId(project.getId()); thisMember.setUserId(userId); thisMember.setUserLevel(roleUserLevel); thisMember.setEnteredBy(userId); thisMember.setModifiedBy(userId); thisMember.insert(db); // News if (bean.getCloneNewsCategories() || bean.getCloneNews()) { HashMap categoryMap = new HashMap(); if (bean.getCloneNewsCategories() && hasPermission(db, project, user, member, "project-news-view", roleList)) { // Copy the news categories BlogPostCategoryList categoryList = new BlogPostCategoryList(); categoryList.setProjectId(oldProjectId); categoryList.buildList(db); categoryList.setProjectId(project.getId()); categoryList.insert(db, categoryMap); } if (bean.getCloneNews() && hasPermission(db, project, user, member, "project-news-view", roleList)) { // Copy the news BlogPostList news = new BlogPostList(); news.setProjectId(oldProjectId); news.buildList(db); news.setProjectId(project.getId()); news.setEnteredBy(userId); news.setModifiedBy(userId); news.remapCategories(categoryMap); // TODO: Adjust startDate and endDate based on today? news.insert(db); // TODO: Need to copy the news image library } } // Discussion Forums if (bean.getCloneForums() && hasPermission(db, project, user, member, "project-discussion-forums-view", roleList)) { ForumList forums = new ForumList(); forums.setProjectId(oldProjectId); forums.buildList(db); // TODO: Discussion Topics forums.setProjectId(project.getId()); forums.setEnteredBy(userId); forums.setModifiedBy(userId); forums.insert(db); } // Document Folders if (bean.getCloneDocumentFolders() && hasPermission(db, project, user, member, "project-documents-view", roleList)) { FileFolderHierarchy hierarchy = new FileFolderHierarchy(); hierarchy.setLinkModuleId(Constants.PROJECTS_FILES); hierarchy.setLinkItemId(oldProjectId); hierarchy.build(db); FileFolderList folders = hierarchy.getHierarchy(); folders.setLinkItemId(project.getId()); folders.setEnteredBy(userId); folders.setModifiedBy(userId); folders.insert(db); } // Lists if (bean.getCloneLists() && hasPermission(db, project, user, member, "project-lists-view", roleList)) { TaskCategoryList lists = new TaskCategoryList(); lists.setProjectId(oldProjectId); lists.buildList(db); lists.setProjectId(project.getId()); lists.setEnteredBy(userId); lists.setModifiedBy(userId); lists.setOwner(userId); if (bean.getCloneListItems()) { lists.insert(db, true); } else { lists.insert(db, false); } } if (System.getProperty("DEBUG") != null) { System.out.println("ProjectCopier-> before wiki"); } // Wiki if (bean.getCloneWiki() && hasPermission(db, project, user, member, "project-wiki-view", roleList)) { LOG.debug("ProjectCopier-> Inserting wiki"); // The wiki items WikiList wikiList = new WikiList(); wikiList.setProjectId(oldProjectId); wikiList.buildList(db); wikiList.setEnteredBy(userId); wikiList.setModifiedBy(userId); wikiList.setProjectId(project.getId()); wikiList.insert(db); wikiList = null; // TODO: The wiki images -- references and files /*FileItemList wikiImages = new FileItemList(); wikiImages.setLinkModuleId(Constants.PROJECT_WIKI_FILES); wikiImages.setLinkItemId(oldProjectId); wikiImages.buildList(db); wikiImages.setLinkItemId(project.getId()); wikiImages.copyTo(newPath); wikiImages.insert(db); wikiImages = null;*/ } // Ticket Configuration if (bean.getCloneTicketConfig() && hasPermission(db, project, user, member, "project-tickets-view", roleList)) { // Ticket Categories HashMap categoryMap = new HashMap(); TicketCategoryList categoryList = new TicketCategoryList(); categoryList.setProjectId(oldProjectId); categoryList.buildList(db); categoryList.setProjectId(project.getId()); categoryList.insert(db, categoryMap); // Ticket Defect Lookup ProjectItemList defectList = new ProjectItemList(); defectList.setProjectId(oldProjectId); defectList.setEnabled(Constants.TRUE); defectList.buildList(db, ProjectItemList.TICKET_DEFECT); defectList.setProjectId(project.getId()); defectList.insert(db, null, ProjectItemList.TICKET_DEFECT); // Ticket States Lookup ProjectItemList stateList = new ProjectItemList(); stateList.setProjectId(oldProjectId); stateList.setEnabled(Constants.TRUE); stateList.buildList(db, ProjectItemList.TICKET_STATE); stateList.setProjectId(project.getId()); stateList.insert(db, null, ProjectItemList.TICKET_STATE); // Ticket Causes Lookup ProjectItemList causeList = new ProjectItemList(); causeList.setProjectId(oldProjectId); causeList.setEnabled(Constants.TRUE); causeList.buildList(db, ProjectItemList.TICKET_CAUSE); causeList.setProjectId(project.getId()); causeList.insert(db, null, ProjectItemList.TICKET_CAUSE); // Ticket Resolution Lookup ProjectItemList resolutionList = new ProjectItemList(); resolutionList.setProjectId(oldProjectId); resolutionList.setEnabled(Constants.TRUE); resolutionList.buildList(db, ProjectItemList.TICKET_RESOLUTION); resolutionList.setProjectId(project.getId()); resolutionList.insert(db, null, ProjectItemList.TICKET_RESOLUTION); // Ticket Escalation Lookup ProjectItemList escalationList = new ProjectItemList(); escalationList.setProjectId(oldProjectId); escalationList.setEnabled(Constants.TRUE); escalationList.buildList(db, ProjectItemList.TICKET_ESCALATION); escalationList.setProjectId(project.getId()); escalationList.insert(db, null, ProjectItemList.TICKET_ESCALATION); } // Outlines, Activities, Activity Folders (no notes yet) if (bean.getCloneActivities() && hasPermission(db, project, user, member, "project-plan-view", roleList)) { RequirementList outlines = new RequirementList(); outlines.setProjectId(oldProjectId); outlines.buildList(db); outlines.setProjectId(project.getId()); outlines.setEnteredBy(userId); outlines.setModifiedBy(userId); outlines.setOffset(offset); if (bean.getResetActivityStatus()) { outlines.setResetStatus(true); } outlines.insert(db, oldProjectId); } db.commit(); } catch (Exception e) { LOG.error("clone", e); db.rollback(); } finally { db.setAutoCommit(true); } return project; }
From source file:ips1ap101.lib.core.db.util.DB.java
public static boolean setAutoCommit(Connection connection, boolean autoCommit) { if (connection != null) { try {/*from w w w .j a va 2 s .c om*/ if (!connection.isClosed()) { if (connection.getAutoCommit() == autoCommit) { Bitacora.trace("autocommit is already " + autoCommit); } else { Bitacora.trace("setting autocommit to " + autoCommit); connection.setAutoCommit(autoCommit); } return true; } } catch (SQLException ex) { Bitacora.logFatal(ex); } } return false; }
From source file:org.silverpeas.dbbuilder.DBBuilder.java
private static void processDB(DBXmlDocument xmlFile, UninstallInformations processesToCacheIntoDB, MetaInstructions sqlMetaInstructions, String[] tagsToProcess) throws Exception { Element root = xmlFile.getDocument().getRootElement(); @SuppressWarnings("unchecked") List<Element> modules = root.getChildren(DBXmlDocument.ELT_MODULE); for (Element module : modules) { Connection connection = null; try {//from w ww.j a va2 s . com connection = ConnectionFactory.getConnection(); connection.setAutoCommit(false); processSQLFiles(connection, module, tagsToProcess, sqlMetaInstructions); cacheIntoDb(connection, processesToCacheIntoDB .getInformations(module.getAttributeValue(DBXmlDocument.ATT_MODULE_ID))); if (params.isSimulate()) { DbUtils.rollback(connection); } else { connection.commit(); } } catch (Exception e) { DbUtils.rollback(connection); throw e; } finally { DbUtils.closeQuietly(connection); } } console.printMessage("DB Status after build :"); checkDBStatus(); }
From source file:com.zimbra.cs.db.DbPool.java
public static DbConnection getConnection(Mailbox mbox) throws ServiceException { if (!isInitialized()) { throw ServiceException.FAILURE("Database connection pool not initialized.", null); }/* w ww .j av a 2s. c om*/ Integer mboxId = mbox != null ? mbox.getId() : -1; //-1 == zimbra db and/or initialization where mbox isn't known yet try { Db.getInstance().preOpen(mboxId); long start = ZimbraPerf.STOPWATCH_DB_CONN.start(); // If the connection pool is overutilized, warn about potential leaks PoolingDataSource pool = getPool(); checkPoolUsage(); Connection dbconn = null; DbConnection conn = null; try { dbconn = pool.getConnection(); if (dbconn.getAutoCommit() != false) dbconn.setAutoCommit(false); // We want READ COMMITTED transaction isolation level for duplicate // handling code in BucketBlobStore.newBlobInfo(). if (Db.supports(Db.Capability.READ_COMMITTED_ISOLATION)) dbconn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); conn = new DbConnection(dbconn, mboxId); Db.getInstance().postOpen(conn); } catch (SQLException e) { try { if (dbconn != null && !dbconn.isClosed()) dbconn.close(); } catch (SQLException e2) { ZimbraLog.sqltrace.warn("DB connection close caught exception", e); } throw ServiceException.FAILURE("getting database connection", e); } // If we're debugging, update the counter with the current stack trace if (ZimbraLog.dbconn.isDebugEnabled()) { Throwable t = new Throwable(); conn.setStackTrace(t); String stackTrace = SystemUtil.getStackTrace(t); synchronized (sConnectionStackCounter) { sConnectionStackCounter.increment(stackTrace); } } if (mbox != null) Db.registerDatabaseInterest(conn, mbox); ZimbraPerf.STOPWATCH_DB_CONN.stop(start); return conn; } catch (ServiceException se) { //if connection open fails unlock Db.getInstance().abortOpen(mboxId); throw se; } }
From source file:com.concursive.connect.web.modules.common.social.rating.dao.Rating.java
/** * Deletes just a specific user's rating, and updates the parent table with a proper calculation * * @param db/*w w w. ja va 2 s. com*/ * @param userId * @param objectId * @param table * @param uniqueField * @throws SQLException */ public static synchronized void delete(Connection db, int userId, int objectId, String table, String uniqueField) throws SQLException { boolean commit = false; try { commit = db.getAutoCommit(); if (commit) { db.setAutoCommit(false); } // Get the project's rating int ratingCount = queryObjectRatingCount(db, objectId, table, uniqueField); // Get the user's rating int thisRating = queryUserRating(db, userId, objectId, table, uniqueField); // Delete the user's rating PreparedStatement pst = db.prepareStatement( "DELETE FROM " + table + "_rating " + "WHERE " + uniqueField + " = ? " + "AND enteredby = ? "); pst.setInt(1, objectId); pst.setInt(2, userId); int deleteCount = pst.executeUpdate(); pst.close(); if (deleteCount > 0 && thisRating != INAPPROPRIATE_COMMENT) { // Update the parent table's rating information // NOTE: make sure not to divide by 0 pst = db.prepareStatement("UPDATE " + table + " " + "SET rating_count = rating_count - ?, rating_value = rating_value - ?, " + (ratingCount == 0 ? "rating_avg = 0 " : "rating_avg = ((rating_value - ?) / (rating_count - ?)) ") + "WHERE " + uniqueField + " = ? "); int i = 0; pst.setInt(++i, 1); pst.setInt(++i, thisRating); if (ratingCount > 1) { pst.setInt(++i, thisRating); pst.setInt(++i, 1); } pst.execute(); pst.close(); } } catch (Exception e) { if (commit) { db.rollback(); } throw new SQLException(e.getMessage()); } finally { if (commit) { db.setAutoCommit(true); } } }
From source file:com.autentia.tnt.bill.migration.support.MigratedInformationRecoverer.java
/** * Recupera la suma total de todos los conceptos de todas las facturas del tipo que se envie por parametro * @param billType tipo de factura//from w w w .j a v a 2 s .c o m */ public static double getTotalFacturasMigrated(String billType) throws Exception { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; LineNumberReader file = null; double result = -1; try { log.info("RECOVERING TOTAL FACTURAS " + billType + " MIGRADAS"); // connect to database Class.forName(BillToBillPaymentMigration.DATABASE_DRIVER); con = DriverManager.getConnection(BillToBillPaymentMigration.DATABASE_CONNECTION, BillToBillPaymentMigration.DATABASE_USER, BillToBillPaymentMigration.DATABASE_PASS); //NOSONAR con.setAutoCommit(false); // DATABASE_PASS es nula String sql = "SELECT sum(bp.amount) FROM BillPayment bp, Bill b where bp.billId = b.id and b.billType = ?"; pstmt = con.prepareStatement(sql); pstmt.setString(1, billType); rs = pstmt.executeQuery(); while (rs.next()) { result = rs.getDouble(1); log.info("\t" + result); } } catch (Exception e) { log.error("FAILED: WILL BE ROLLED BACK: ", e); if (con != null) { con.rollback(); } } finally { cierraFichero(file); liberaConexion(con, pstmt, rs); } return result; }
From source file:com.autentia.tnt.bill.migration.support.OriginalInformationRecoverer.java
/** * Recupera la suma total de todos los conceptos de todas las facturas del tipo que se envie por parametro * @param billType tipo de factura/*from w ww. ja v a2 s . com*/ */ public static double getTotalFacturasOriginal(String billType) throws Exception { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; LineNumberReader file = null; double result = -1; try { log.info("RECOVERING TOTAL FACTURAS " + billType + " ORIGINALES"); // connect to database Class.forName(BillToBillPaymentMigration.DATABASE_DRIVER); con = DriverManager.getConnection(BillToBillPaymentMigration.DATABASE_CONNECTION, BillToBillPaymentMigration.DATABASE_USER, BillToBillPaymentMigration.DATABASE_PASS); //NOSONAR con.setAutoCommit(false); // DATABASE_PASS vacio String sql = "SELECT sum((bb.units*bb.amount)*(1+(bb.iva/100))) as total from Bill b left join BillBreakDown bb on b.id=bb.billId, Organization o, Project p where b.projectId = p.id and p.organizationId = o.id and b.billType= ?"; pstmt = con.prepareStatement(sql); pstmt.setString(1, billType); rs = pstmt.executeQuery(); while (rs.next()) { result = rs.getDouble(1); log.info("\t" + result); } con.commit(); } catch (Exception e) { log.error("FAILED: WILL BE ROLLED BACK: ", e); if (con != null) { con.rollback(); } } finally { cierraFichero(file); liberaConexion(con, pstmt, rs); } return result; }
From source file:com.autentia.tnt.bill.migration.support.OriginalInformationRecoverer.java
/** * Recupera la fecha de pago o cobro de cada una de las facturas cuyo tipo se envia por parametro * @param billType tipo de factura//from w w w . j a v a2s . com */ public static Date[] getFechaFacturaOriginal(String billType) throws Exception { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; LineNumberReader file = null; Date[] result = new Date[0]; try { log.info("RECOVERING FECHAS " + billType + " ORIGINALES"); // connect to database Class.forName(BillToBillPaymentMigration.DATABASE_DRIVER); con = DriverManager.getConnection(BillToBillPaymentMigration.DATABASE_CONNECTION, BillToBillPaymentMigration.DATABASE_USER, BillToBillPaymentMigration.DATABASE_PASS); //NOSONAR con.setAutoCommit(false); // DATABASE_PASS vacia String sql = "SELECT date_add(creationDate, INTERVAL expiration DAY) as date FROM Bill B where billType = ? order by date"; pstmt = con.prepareStatement(sql); pstmt.setString(1, billType); rs = pstmt.executeQuery(); rs.last(); result = new Date[rs.getRow()]; rs.beforeFirst(); int counter = 0; while (rs.next()) { result[counter] = rs.getDate(1); log.info("\t" + result[counter]); counter++; } con.commit(); } catch (Exception e) { log.error("FAILED: WILL BE ROLLED BACK: ", e); if (con != null) { con.rollback(); } } finally { cierraFichero(file); liberaConexion(con, pstmt, rs); } return result; }
From source file:com.autentia.tnt.bill.migration.support.MigratedInformationRecoverer.java
/** * Recupera la fecha de pago o cobro de cada una de las facturas cuyo tipo se envia por parametro * @param billType tipo de factura//from w w w.ja v a 2 s .c om */ public static Date[] getFechaFacturaMigrated(String billType) throws Exception { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; LineNumberReader file = null; Date[] result = new Date[0]; try { log.info("RECOVERING FECHAS " + billType + " MIGRADAS"); // connect to database Class.forName(BillToBillPaymentMigration.DATABASE_DRIVER); con = DriverManager.getConnection(BillToBillPaymentMigration.DATABASE_CONNECTION, BillToBillPaymentMigration.DATABASE_USER, BillToBillPaymentMigration.DATABASE_PASS); //NOSONAR con.setAutoCommit(false); // DATABASE_PASS vacio. String sql = "SELECT bp.expirationDate FROM BillPayment bp, Bill b where bp.billId = b.id and b.billType = ? order by bp.expirationDate"; pstmt = con.prepareStatement(sql); pstmt.setString(1, billType); rs = pstmt.executeQuery(); rs.last(); result = new Date[rs.getRow()]; rs.beforeFirst(); int counter = 0; while (rs.next()) { result[counter] = rs.getDate(1); log.info("\t" + result[counter]); counter++; } } catch (Exception e) { log.error("FAILED: WILL BE ROLLED BACK: ", e); if (con != null) { con.rollback(); } } finally { cierraFichero(file); liberaConexion(con, pstmt, rs); } return result; }