List of usage examples for java.sql Connection rollback
void rollback() throws SQLException;
Connection
object. From source file:dao.CollabrumDaoDb.java
/** * This deletes all messages belonging to a collabrum * @throws BaseDaoException If we have a problem interpreting the data *///from www . ja v a 2s . c o m private void deleteCollMessages(String collabrumId, List tidList) throws BaseDaoException { /** * Get scalability datasource, for messages partitioned on tid * - collmessages * - collmsgattr */ for (int i = 0; i < tidList.size(); i++) { String tid = (String) ((ColTopic) tidList.get(i)).getValue(DbConstants.TID); String sourceName = scalabilityManager.getWriteScalability(tid); ds = scalabilityManager.getSource(sourceName); if (ds == null) { throw new BaseDaoException("ds null, deleteCollMessages() " + sourceName + " tid = " + tid); } Connection conn = null; try { conn = ds.getConnection(); conn.setAutoCommit(false); deleteColMessagesQuery.run(conn, tid); deleteColMsgAttrQuery.run(conn, tid); } catch (Exception e) { try { conn.rollback(); } catch (Exception e1) { try { if (conn != null) { conn.setAutoCommit(true); conn.close(); } } catch (Exception e2) { throw new BaseDaoException( "conn.close exception for rollback(), for deleteCollMessages() tid = " + tid + " collabrumId = " + collabrumId, e2); } throw new BaseDaoException(" rollback() exception deleteCollMessages(), tid=" + tid + "collabrumId = " + collabrumId, e1); } throw new BaseDaoException( "delete exception deleteCollMessages(), tid=" + tid + " collabrumId = " + collabrumId, e); } // connection commit try { conn.commit(); } catch (Exception e3) { throw new BaseDaoException( "commit() exception, for deleteCollMessages() collabrumId = " + collabrumId, e3); } try { if (conn != null) { conn.setAutoCommit(true); conn.close(); } } catch (Exception e4) { throw new BaseDaoException( "conn.close() exception, for commit(), deleteCollMessages() collabrumId = ", e4); } } }
From source file:com.twosigma.beaker.sqlsh.utils.QueryExecutor.java
private QueryResult executeQuery(int currentIterationIndex, BeakerParseResult queryLine, Connection conn, NamespaceClient namespaceClient) throws SQLException, ReadVariableException { QueryResult queryResult = new QueryResult(); String sql = queryLine.getResultQuery(); try (Statement statement = conn.createStatement()) { this.statement = statement; for (BeakerInputVar parameter : queryLine.getInputVars()) { if (parameter.getErrorMessage() != null) throw new ReadVariableException(parameter.getErrorMessage()); Object obj;//from www . ja va2s .com try { obj = namespaceClient.get(parameter.objectName); if (!parameter.isArray() && !parameter.isObject()) { sql = setObject(sql, obj); } else if (!parameter.isArray() && parameter.isObject()) { sql = setObject(sql, getValue(obj, parameter.getFieldName())); } else if (parameter.isArray()) { int index; if (currentIterationIndex > 0 && parameter.isAll()) { index = currentIterationIndex; } else { index = parameter.index; } if (!parameter.isObject()) { if (obj instanceof List) { sql = setObject(sql, ((List) obj).get(index)); } else if (obj.getClass().isArray()) { Object arrayElement = Array.get(obj, index); sql = setObject(sql, arrayElement); } } else { if (obj instanceof List) { sql = setObject(sql, getValue(((List) obj).get(index), parameter.getFieldName())); } else if (obj.getClass().isArray()) { Object arrayElement = Array.get(obj, index); sql = setObject(sql, getValue(arrayElement, parameter.getFieldName())); } } } } catch (Exception e) { throw new ReadVariableException(parameter.objectName, e); } } boolean hasResultSet = statement.execute(sql); if (hasResultSet) { ResultSet rs = statement.getResultSet(); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { queryResult.getColumns().add(rs.getMetaData().getColumnName(i)); queryResult.getTypes().add(rs.getMetaData().getColumnClassName(i)); } while (rs.next()) { if (rs.getMetaData().getColumnCount() != 0) { List<Object> row = new ArrayList<Object>(); queryResult.getValues().add(row); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { if (java.sql.Date.class.getName().equals(rs.getMetaData().getColumnClassName(i))) { java.sql.Date sqlDate = rs.getDate(i); row.add(sqlDate == null ? null : new Date(sqlDate.getTime())); } else { row.add(rs.getObject(i)); } } } } } } catch (SQLException e) { //Logger.getLogger(QueryExecutor.class.getName()).log(Level.SEVERE, null, e); try { conn.rollback(); } catch (Exception e1) { //Logger.getLogger(QueryExecutor.class.getName()).log(Level.SEVERE, null, e1); } throw e; } return queryResult; }
From source file:dao.CollabrumDaoDb.java
/** * @param idList the list of the collabrum ids * @param memberId the memberId to be deleted * @throws BaseDaoException If we have a problem interpreting the data or the data is missing or incorrect *//*from ww w. jav a2 s. co m*/ public void deleteMemberFromCollabrums(ArrayList idList, String memberId) throws BaseDaoException { if ((idList == null) || RegexStrUtil.isNull(memberId)) { throw new BaseDaoException("params are null, deleteMemberFromCollabrums"); } /** * Get scalability datasource, collmembers is not partitioned **/ String sourceName = scalabilityManager.getWriteZeroScalability(); ds = scalabilityManager.getSource(sourceName); if (ds == null) { StringBuffer sb = new StringBuffer("ds is null for deleteMemberFromCollabrums() in collabrumDaoDb "); sb.append(sourceName); sb.append(" memberId "); sb.append(memberId); throw new BaseDaoException(sb.toString()); } Connection conn = null; try { conn = ds.getConnection(); conn.setAutoCommit(false); for (int i = 0; i < idList.size(); i++) { deleteMemberQuery.run(conn, (String) idList.get(i), memberId); } } catch (Exception e) { try { conn.rollback(); } catch (Exception e1) { try { if (conn != null) { conn.setAutoCommit(true); conn.close(); } } catch (Exception e2) { throw new BaseDaoException( "conn.close() error, deleteMemberFromCollabrums, memberId" + memberId, e2); } throw new BaseDaoException( " rollback() exception, for deleteMemberFromCollabrums(), memberId = " + memberId, e1); } } // connection commit try { conn.commit(); } catch (Exception e3) { throw new BaseDaoException( " commit() exception, for deleteMemberFromCollabrums() memberId = " + memberId, e3); } try { if (conn != null) { conn.setAutoCommit(true); conn.close(); } } catch (Exception e4) { throw new BaseDaoException( " conn.close() exception, for commit(), addBlockMemberQuery() memberId = " + memberId, e4); } /** * Jboss methods * fqn - full qualified name * check if the collabrum already exists in the cache * If it exists, remove the collabrum from the cache. * This will enable to get the updated collabrum when the user does getCollabrum(); */ Fqn fqn = cacheUtil.fqn(DbConstants.BLOCKED_COLLABRUM_LIST); if (treeCache.exists(fqn, memberId)) { treeCache.remove(fqn, memberId); } for (int i = 0; i < idList.size(); i++) { fqn = cacheUtil.fqn(DbConstants.COLLABRUM); String collabrumId = (String) idList.get(i); if (treeCache.exists(fqn, collabrumId)) { treeCache.remove(fqn, collabrumId); } fqn = cacheUtil.fqn(DbConstants.COLLABRUM_EDIT); if (treeCache.exists(fqn, collabrumId)) { treeCache.remove(fqn, collabrumId); } } Hdlogin hdlogin = getLogin(memberId); if (hdlogin != null) { String userLogin = hdlogin.getValue(DbConstants.LOGIN); fqn = cacheUtil.fqn(DbConstants.MEM_AS_MODERATOR_LIST); if (treeCache.exists(fqn, userLogin)) { treeCache.remove(fqn, userLogin); } fqn = cacheUtil.fqn(DbConstants.MEM_AS_ORGANIZER_LIST); if (treeCache.exists(fqn, userLogin)) { treeCache.remove(fqn, userLogin); } } }
From source file:mom.trd.opentheso.bdd.helper.ConceptHelper.java
/** * Cette fonction permet de ractiver un concept (!hidden) * * @param ds//from w ww . j a v a2s . co m * @param idConcept * @param idTheso * @param idUser * @return */ public boolean reactiveConcept(HikariDataSource ds, String idConcept, String idTheso, int idUser) { Connection conn; Statement stmt; try { // Get connection from pool conn = ds.getConnection(); try { stmt = conn.createStatement(); try { Concept concept = getThisConcept(ds, idConcept, idTheso); concept.setStatus("D"); if (!addConceptHistorique(conn, concept, idUser)) { conn.rollback(); conn.close(); return false; } String query = "UPDATE concept " + "set status='D'" + " WHERE id_concept ='" + idConcept + "'" + " AND id_thesaurus='" + idTheso + "'"; stmt.executeUpdate(query); } finally { stmt.close(); } } finally { conn.close(); } } catch (SQLException sqle) { // Log exception log.error("Error during reactivation of Concept : " + idConcept, sqle); return false; } return true; }
From source file:com.twosigma.beakerx.sql.QueryExecutor.java
private QueryResult executeQuery(int currentIterationIndex, BeakerParseResult queryLine, Connection conn, BeakerXClient namespaceClient) throws SQLException, ReadVariableException { QueryResult queryResult = new QueryResult(); try (PreparedStatement statement = conn.prepareStatement(queryLine.getResultQuery())) { this.statement = statement; int n = 1; for (BeakerInputVar parameter : queryLine.getInputVars()) { if (parameter.getErrorMessage() != null) throw new ReadVariableException(parameter.getErrorMessage()); Object obj;/* w ww . ja v a2 s . c o m*/ try { obj = namespaceClient.get(parameter.objectName); if (!parameter.isArray() && !parameter.isObject()) { statement.setObject(n, obj); } else if (!parameter.isArray() && parameter.isObject()) { statement.setObject(n, getValue(obj, parameter.getFieldName())); } else if (parameter.isArray()) { int index; if (currentIterationIndex > 0 && parameter.isAll()) { index = currentIterationIndex; } else { index = parameter.index; } if (!parameter.isObject()) { if (obj instanceof List) { statement.setObject(n, ((List) obj).get(index)); } else if (obj.getClass().isArray()) { Object arrayElement = Array.get(obj, index); statement.setObject(n, arrayElement); } } else { if (obj instanceof List) { statement.setObject(n, getValue(((List) obj).get(index), parameter.getFieldName())); } else if (obj.getClass().isArray()) { Object arrayElement = Array.get(obj, index); statement.setObject(n, getValue(arrayElement, parameter.getFieldName())); } } } n++; } catch (Exception e) { throw new ReadVariableException(parameter.objectName, e); } } boolean hasResultSet = statement.execute(); if (hasResultSet) { ResultSet rs = statement.getResultSet(); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { queryResult.getColumns().add(rs.getMetaData().getColumnName(i)); queryResult.getTypes().add(rs.getMetaData().getColumnClassName(i)); } while (rs.next()) { if (rs.getMetaData().getColumnCount() != 0) { List<Object> row = new ArrayList<Object>(); queryResult.getValues().add(row); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { if (java.sql.Date.class.getName().equals(rs.getMetaData().getColumnClassName(i))) { java.sql.Date sqlDate = rs.getDate(i); row.add(sqlDate == null ? null : new Date(sqlDate.getTime())); } else { row.add(rs.getObject(i)); } } } } } } catch (SQLException e) { //Logger.getLogger(QueryExecutor.class.getName()).log(Level.SEVERE, null, e); try { conn.rollback(); } catch (Exception e1) { //Logger.getLogger(QueryExecutor.class.getName()).log(Level.SEVERE, null, e1); } throw e; } return queryResult; }
From source file:com.twosigma.beaker.sql.QueryExecutor.java
private QueryResult executeQuery(int currentIterationIndex, BeakerParseResult queryLine, Connection conn, NamespaceClient namespaceClient) throws SQLException, ReadVariableException { QueryResult queryResult = new QueryResult(); try (PreparedStatement statement = conn.prepareStatement(queryLine.getResultQuery())) { this.statement = statement; int n = 1; for (BeakerInputVar parameter : queryLine.getInputVars()) { if (parameter.getErrorMessage() != null) throw new ReadVariableException(parameter.getErrorMessage()); Object obj;/*from www. ja va 2 s .c om*/ try { obj = namespaceClient.get(parameter.objectName); if (!parameter.isArray() && !parameter.isObject()) { statement.setObject(n, obj); } else if (!parameter.isArray() && parameter.isObject()) { statement.setObject(n, getValue(obj, parameter.getFieldName())); } else if (parameter.isArray()) { int index; if (currentIterationIndex > 0 && parameter.isAll()) { index = currentIterationIndex; } else { index = parameter.index; } if (!parameter.isObject()) { if (obj instanceof List) { statement.setObject(n, ((List) obj).get(index)); } else if (obj.getClass().isArray()) { Object arrayElement = Array.get(obj, index); statement.setObject(n, arrayElement); } } else { if (obj instanceof List) { statement.setObject(n, getValue(((List) obj).get(index), parameter.getFieldName())); } else if (obj.getClass().isArray()) { Object arrayElement = Array.get(obj, index); statement.setObject(n, getValue(arrayElement, parameter.getFieldName())); } } } n++; } catch (Exception e) { throw new ReadVariableException(parameter.objectName, e); } } boolean hasResultSet = statement.execute(); if (hasResultSet) { ResultSet rs = statement.getResultSet(); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { queryResult.getColumns().add(rs.getMetaData().getColumnName(i)); queryResult.getTypes().add(rs.getMetaData().getColumnClassName(i)); } while (rs.next()) { if (rs.getMetaData().getColumnCount() != 0) { List<Object> row = new ArrayList<Object>(); queryResult.getValues().add(row); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { if (java.sql.Date.class.getName().equals(rs.getMetaData().getColumnClassName(i))) { java.sql.Date sqlDate = rs.getDate(i); row.add(sqlDate == null ? null : new Date(sqlDate.getTime())); } else { row.add(rs.getObject(i)); } } } } } } catch (SQLException e) { //Logger.getLogger(QueryExecutor.class.getName()).log(Level.SEVERE, null, e); try { conn.rollback(); } catch (Exception e1) { //Logger.getLogger(QueryExecutor.class.getName()).log(Level.SEVERE, null, e1); } throw e; } return queryResult; }
From source file:com.autentia.tnt.manager.data.MigrationManager.java
/** * @return the original database version * @throws com.autentia.tnt.manager.data.exception.DataException *///from w w w . j a v a 2 s .c o m public Version upgradeDatabase() throws DataException { Version ret = null; Version db = null; Version code = Version.getApplicationVersion(); Session ses = HibernateUtil.getSessionFactory().openSession(); Connection con = ses.connection(); Statement stmt = null; LineNumberReader file = null; String delimiter = ";"; try { db = Version.getDatabaseVersion(); ret = db.clone(); log.info("upgradeDatabase - >>>> STARTING MIGRATION FROM " + db + " TO " + code + " <<<<"); // Disable auto-commit (just in case...) log.info("upgradeDatabase - disabling auto commit"); con.setAutoCommit(false); // Create statement stmt = con.createStatement(); // While necessary, upgrade database while (db.compareTo(code, Version.MINOR) < 0) { log.info("upgradeDatabase - " + db); // Compose script name and open it String script = SCRIPT_PREFIX + db.toString(Version.MINOR) + SCRIPT_SUFFIX; log.info("upgradeDatabase - loading script " + script); InputStream sqlScript = Thread.currentThread().getContextClassLoader().getResourceAsStream(script); if (sqlScript == null) { throw FileNotFoundException(script); } file = new LineNumberReader(new InputStreamReader(new BufferedInputStream(sqlScript), "UTF-8")); int _c; // 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.info(" " + 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.info("upgradeDatabase - executing batch of commands"); stmt.executeBatch(); // Re-read database version Version old = db; db = Version.getDatabaseVersion(con); if (old.equals(db)) { throw new DataException("Script was applied but did not upgrade database: " + script); } log.info("upgradeDatabase - database upgraded to version " + db); } // Commit transaction log.info("upgradeDatabase - commiting changes to database"); con.commit(); // Report end of migration log.info("upgradeDatabase - >>>> MIGRATION SUCCESSFULLY FINISHED <<<<"); } catch (Exception e) { log.error("upgradeDatabase - >>>> MIGRATION FAILED: WILL BE ROLLED BACK <<<<", e); try { con.rollback(); } catch (SQLException e2) { log.error("upgradeDatabase - Error al realizar el rollback"); } throw new DataException("Script was applied but did not upgrade database: ", e); } finally { if (file != null) { try { file.close(); } catch (IOException e2) { log.error("upgradeDatabase - Error al cerrar el fichero de script ", e2); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e2) { log.error("upgradeDatabase - Error al cerrar el statement"); } } ses.close(); } return ret; }
From source file:dao.CollabrumDaoDb.java
/** * This deletes all topics belonging to a collabrum * @throws BaseDaoException If we have a problem interpreting the data */// w ww .ja v a 2s. c o m private void deleteCollTopics(String collabrumId, List tidList) { /** * tidList */ for (int i = 0; i < tidList.size(); i++) { String tid = (String) ((ColTopic) tidList.get(i)).getValue(DbConstants.TID); if (RegexStrUtil.isNull(tid)) { continue; } String sourceName = scalabilityManager.getWriteScalability(tid); ds = scalabilityManager.getSource(sourceName); if (ds == null) { throw new BaseDaoException("ds null, deleteCollTopics() " + sourceName + " tid = " + tid); } Connection conn = null; try { conn = ds.getConnection(); conn.setAutoCommit(false); deleteColTopicsAttrQuery.run(conn, tid); } catch (Exception e) { /** * conn.rollback() */ try { conn.rollback(); } catch (Exception e1) { try { if (conn != null) { conn.setAutoCommit(true); conn.close(); } } catch (Exception e2) { throw new BaseDaoException( "conn.close(), deleteColtopicsAttrQuery() collabrumId = " + collabrumId, e2); } throw new BaseDaoException( " rollback() exception, deleteColTopicsAttrQuery(), collabrumId= " + collabrumId, e1); } throw new BaseDaoException("conn.close()", e); } /** * AutoCommit(true) */ try { if (conn != null) { conn.setAutoCommit(true); conn.close(); } } catch (Exception e4) { throw new BaseDaoException( "conn.close() exception, for commit(), deleteColTopicsAttrQuery() collabrumId = ", e4); } } /** * Get scalability datasource for colltopic partitioned on collabrumid */ String sourceName = scalabilityManager.getWriteScalability(collabrumId); ds = scalabilityManager.getSource(sourceName); if (ds == null) { throw new BaseDaoException( "ds null, deleteColTopicsAttrQuery() " + sourceName + " collabrumId = " + collabrumId); } /** * Partitioned on collabrumId * colltopics (deleteColTopicsQuery) * colltopicattr (deleteColTopicsAttrQuery) * colltraffic (deleteColTrafficQuery) * collcobrand (deleteCollCobrandQuery) * collblob (deleteCollBlobsQuery) */ Connection conn = null; try { conn = ds.getConnection(); if (conn == null) { throw new BaseDaoException("conn is null" + collabrumId); } conn.setAutoCommit(false); deleteColTopicsQuery.run(conn, collabrumId); deleteColCobrandQuery.run(conn, collabrumId); deleteAllCollBlobs.run(conn, collabrumId); /* not required any more * deleteColTrafficQuery.run(conn,collabrumId); */ } catch (Exception e) { try { conn.rollback(); } catch (Exception e1) { try { if (conn != null) { conn.setAutoCommit(true); conn.close(); } } catch (Exception e2) { throw new BaseDaoException( "conn.close() exception for rollback(), for deleteCollTopics() collabrumId = " + collabrumId, e2); } throw new BaseDaoException(" rollback() exception, deleteCollTopics(), collabrumId= " + collabrumId, e1); } throw new BaseDaoException("delete exception deleteCollTopics(), collabrumId= " + collabrumId, e); } // connection commit try { conn.commit(); } catch (Exception e3) { throw new BaseDaoException("commit() exception, for deleteCollTopics() collabrumId = " + collabrumId, e3); } try { if (conn != null) { conn.setAutoCommit(true); conn.close(); } } catch (Exception e4) { throw new BaseDaoException("conn.close() exception, for commit(), deleteCollTopics() collabrumId = ", e4); } }
From source file:mom.trd.opentheso.bdd.helper.ConceptHelper.java
/** * Cette fonction permet d'ajouter une traduction un terme * * @param ds//from ww w. j a v a 2 s. co m * @param term * @param idUser * @return null si le term existe ou si erreur, sinon le numero de Concept */ public boolean addConceptTraduction(HikariDataSource ds, Term term, int idUser) { Connection conn = null; try { conn = ds.getConnection(); conn.setAutoCommit(false); TermHelper termHelper = new TermHelper(); // controle si le term existe avant de rajouter un concept if (termHelper.isTermExist(ds, term.getLexical_value(), term.getId_thesaurus(), term.getLang())) { return false; } if (!termHelper.addTermTraduction(conn, term, idUser)) { conn.rollback(); conn.close(); return false; } conn.commit(); conn.close(); // cette fonction permet de remplir la table Permute termHelper.splitConceptForPermute(ds, term.getId_concept(), getGroupIdOfConcept(ds, term.getId_concept(), term.getId_thesaurus()), term.getId_thesaurus(), term.getLang(), term.getLexical_value()); return true; } catch (SQLException ex) { Logger.getLogger(ConceptHelper.class.getName()).log(Level.SEVERE, null, ex); try { if (conn != null) { conn.close(); } } catch (SQLException ex1) { Logger.getLogger(ConceptHelper.class.getName()).log(Level.SEVERE, null, ex1); } } return false; }
From source file:mom.trd.opentheso.bdd.helper.ConceptHelper.java
/** * Cette fonction permet de dsactiver un concept (hidden) * * @param ds//from w w w . j a va 2 s . c om * @param idConcept * @param idTheso * @param idUser * @return */ public boolean desactiveConcept(HikariDataSource ds, String idConcept, String idTheso, int idUser) { Connection conn; Statement stmt; try { // Get connection from pool conn = ds.getConnection(); conn.setAutoCommit(false); try { stmt = conn.createStatement(); try { Concept concept = getThisConcept(ds, idConcept, idTheso); concept.setStatus("hidden"); if (!addConceptHistorique(conn, concept, idUser)) { conn.rollback(); conn.close(); return false; } String query = "UPDATE concept " + "set status='hidden'" + " WHERE id_concept ='" + idConcept + "'" + " AND id_thesaurus='" + idTheso + "'"; stmt.executeUpdate(query); conn.commit(); } finally { stmt.close(); } } finally { conn.close(); } } catch (SQLException sqle) { // Log exception log.error("Error during desactivation of Concept : " + idConcept, sqle); return false; } return true; }