List of usage examples for java.sql Connection rollback
void rollback() throws SQLException;
Connection
object. From source file:gridool.db.sql.ParallelSQLExecJob.java
private static String invokeCsvOutputReduce(final Connection conn, final String reduceQuery, final String outputTableName, final ReadWriteLock rwlock, final Timings timings) throws GridException { File colDir = GridUtils.getWorkDir(true); final File outFile = new File(colDir, outputTableName + ".csv"); final CsvWriter writer = new CsvWriter(outFile); final MutableBoolean first = new MutableBoolean(true); final MutableLong ansGenStart = new MutableLong(-1L); final ResultSetHandler rsh = new ResultSetHandler() { public Object handle(ResultSet rs) throws SQLException { if (first.getBoolean()) { ansGenStart.setValue(System.currentTimeMillis()); first.setBoolean(false); }//from w w w . ja va2 s . c om int numRows = writer.writeAll(rs, MONETDB_NULL_STRING, false); if (LOG.isInfoEnabled()) { LOG.info("Result row count: " + numRows); } return null; } }; if (LOG.isInfoEnabled()) { LOG.info("Executing a Reduce SQL query: \n" + reduceQuery); } final Lock rlock = rwlock.readLock(); try { rlock.lock(); conn.setReadOnly(true); JDBCUtils.query(conn, reduceQuery, rsh); } catch (SQLException e) { String errmsg = "failed running a reduce query: " + reduceQuery; LOG.error(errmsg, e); try { conn.rollback(); } catch (SQLException rbe) { LOG.warn("Rollback failed", rbe); } throw new GridException(errmsg, e); } finally { rlock.unlock(); writer.close(); } long answerGenStart = ansGenStart.getValue(); long answerGenTime = (answerGenStart == -1L) ? 0L : System.currentTimeMillis() - answerGenStart; timings.setAnswerGenerationTime(answerGenTime); if (!outFile.exists()) { throw new IllegalStateException("Output file does not exist:" + outFile.getAbsolutePath()); } return outFile.getAbsolutePath(); }
From source file:ca.sqlpower.matchmaker.address.AddressPool.java
public void clear() throws SQLException { SQLTable resultTable = project.getResultTable(); Connection con = null; Statement stmt = null;/*from w w w .ja v a2s . c o m*/ try { con = project.createResultTableConnection(); stmt = con.createStatement(); con.setAutoCommit(false); String sql = "DELETE FROM " + DDLUtils.toQualifiedName(resultTable) + " WHERE 1=1"; stmt.execute(sql); con.commit(); } catch (Exception ex) { if (con != null) { con.rollback(); } if (ex instanceof SQLException) { throw (SQLException) ex; } else { throw new RuntimeException("An unexpected error occured while clearing the Address Pool", ex); } } finally { if (stmt != null) stmt.close(); if (con != null) con.close(); } addresses.clear(); }
From source file:net.sf.jabref.sql.exporter.DBExporter.java
/** * Accepts the BibDatabase and MetaData, generates the DML required to create and populate SQL database tables, * and writes this DML to the specified SQL database. * * @param database The BibDatabase to export * @param metaData The MetaData object containing the groups information * @param keySet The set of IDs of the entries to export. * @param databaseStrings The necessary database connection information *///w ww .j a v a 2 s.c o m public void exportDatabaseToDBMS(final BibDatabase database, final MetaData metaData, Set<String> keySet, DBStrings databaseStrings, JabRefFrame frame) throws Exception { String dbName; Connection conn = null; boolean redisplay = false; try { conn = this.connectToDB(databaseStrings); createTables(conn); Vector<Vector<String>> matrix = createExistentDBNamesMatrix(databaseStrings); DBImportExportDialog dialogo = new DBImportExportDialog(frame, matrix, DBImportExportDialog.DialogType.EXPORTER); if (dialogo.removeAction) { dbName = getDBName(matrix, databaseStrings, frame, dialogo); removeDB(dialogo, dbName, conn, metaData); redisplay = true; } else if (dialogo.hasDBSelected) { dbName = getDBName(matrix, databaseStrings, frame, dialogo); performExport(database, metaData, keySet, conn, dbName); } if (!conn.getAutoCommit()) { conn.commit(); conn.setAutoCommit(true); } if (redisplay) { exportDatabaseToDBMS(database, metaData, keySet, databaseStrings, frame); } } catch (SQLException ex) { if ((conn != null) && !conn.getAutoCommit()) { conn.rollback(); } throw ex; } finally { if (conn != null) { conn.close(); } } }
From source file:com.servoy.j2db.util.Utils.java
public static void rollback(Connection connection) { try {/*w w w .j a v a 2 s . co m*/ if (connection != null) { connection.rollback(); } } catch (SQLException e) { Debug.error(e); } }
From source file:com.clustercontrol.platform.infra.InfraJdbcExecutorSupport.java
public static void execInsertFileContent(String fileId, DataHandler handler) throws HinemosUnknown, InfraFileTooLarge { Connection conn = null; JpaTransactionManager tm = null;/*from w w w .j a v a 2 s . c om*/ PGCopyOutputStream pgStream = null; FileOutputStream fos = null; BufferedInputStream bis = null; File tempFile = null; try { tm = new JpaTransactionManager(); conn = tm.getEntityManager().unwrap(java.sql.Connection.class); conn.setAutoCommit(false); pgStream = new PGCopyOutputStream((PGConnection) conn, "COPY binarydata.cc_infra_file_content(file_id, file_content) FROM STDIN WITH (FORMAT BINARY)"); String exportDirectory = HinemosPropertyUtil.getHinemosPropertyStr("infra.export.dir", HinemosPropertyDefault.getString(HinemosPropertyDefault.StringKey.INFRA_EXPORT_DIR)); tempFile = new File(exportDirectory + fileId); fos = new FileOutputStream(tempFile); handler.writeTo(fos); long fileLength = tempFile.length(); int maxSize = HinemosPropertyUtil.getHinemosPropertyNum(MAX_FILE_KEY, Long.valueOf(1024 * 1024 * 64)) .intValue(); // 64MB if (fileLength > maxSize) { throw new InfraFileTooLarge(String.format("File size is larger than the limit size(%d)", maxSize)); } pgStream.write(HEADER_SIGN_PART); pgStream.write(HEADER_FLG_FIELD_PART); pgStream.write(HEADER_EX_PART); pgStream.write(TUPLE_FIELD_COUNT_PART); pgStream.write(ByteBuffer.allocate(4).putInt(fileId.getBytes().length).array()); pgStream.write(fileId.getBytes()); pgStream.write(ByteBuffer.allocate(4).putInt((int) fileLength).array()); bis = new BufferedInputStream(new FileInputStream(tempFile)); byte[] buf = new byte[1024 * 1024]; int read; while ((read = bis.read(buf)) != -1) { pgStream.write(buf, 0, read); } pgStream.write(FILETRAILER); pgStream.flush(); if (!tm.isNestedEm()) { conn.commit(); } } catch (InfraFileTooLarge e) { log.warn(e.getMessage()); try { pgStream.close(); } catch (IOException e1) { log.warn(e1); } try { conn.rollback(); } catch (SQLException e1) { log.warn(e1); } throw e; } catch (Exception e) { log.warn(e.getMessage(), e); try { if (pgStream != null) pgStream.close(); } catch (IOException e1) { log.warn(e1); } try { if (conn != null) 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 (bis != null) { try { bis.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(); } if (tempFile == null) { log.debug("Fail to delete. tempFile is null"); } else if (!tempFile.delete()) { log.debug("Fail to delete " + tempFile.getAbsolutePath()); } } }
From source file:com.che.software.testato.domain.dao.jdbc.impl.VariantDAO.java
/** * Creates variants for a given test case. Is called after the variants * generation./*from w w w. j a v a 2s. c o m*/ * * @author Clement HELIOU (clement.heliou@che-software.com). * @param testCaseId the test case id. * @param variants the list of generated variants. * @since July, 2011. * @throws VariantCreationDAOException if an error occurs during the * creation. */ @Override public void createVariantsFromTestCaseId(int testCaseId, List<VariantCreation> variants) throws VariantCreationDAOException { LOGGER.debug("createVariantsFromTestCaseId(" + testCaseId + "," + variants.size() + " variants)"); Connection connection = null; try { connection = getDataSource().getConnection(); connection.setAutoCommit(false); for (VariantCreation variant : variants) { getQueryRunner().update(connection, "INSERT INTO variant(variant_id, variant_type, test_case_id, label, quantitative_criterion) VALUES(nextval('variant_id_seq'),?,?,NULL,NULL) ", new Object[] { variant.getVariantType().name(), testCaseId }); Integer createdVariantId = (Integer) getQueryRunner().query(connection, "SELECT MAX(variant_id)::int AS result FROM variant ", new ScalarHandler("result")); for (Element element : variant.getElements()) { getQueryRunner().update(connection, "INSERT INTO variant_element(element_id, variant_id) VALUES(?,?) ", new Object[] { element.getElementId(), createdVariantId }); } for (ProceduralArrow transition : variant.getTransitions()) { getQueryRunner().update(connection, "INSERT INTO variant_transition(transition_id, variant_id) VALUES(?,?) ", new Object[] { transition.getTransitionId(), createdVariantId }); } } connection.commit(); } catch (SQLException e) { try { connection.rollback(); } catch (SQLException e1) { throw new VariantCreationDAOException(e1); } throw new VariantCreationDAOException(e); } finally { if (null != connection) { DbUtils.closeQuietly(connection); } } }
From source file:com.thinkmore.framework.orm.hibernate.SimpleHibernateDao.java
/** * ?//from www . j ava2s . co m * @param list sql? */ public void executeBatchByPrepare(String sql, final List<String> list) { Connection conn = null; PreparedStatement st = null; try { conn = SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection(); conn.setAutoCommit(false); // ?? st = conn.prepareStatement(sql); for (int i = 1, j = list.size(); i < j; i++) { Object objs = list.get(i - 1); if (objs instanceof List) { List<Object> values = (List<Object>) objs; for (int h = 1, k = values.size(); h <= k; k++) { Object value = values.get(k - 1); setParameters(st, k, value); } } else { setParameters(st, i, objs); } st.addBatch(sql); if (i % 240 == 0) {//?240?sql??? st.executeBatch(); conn.commit(); st.clearBatch(); } else if (i % j == 0) {//?? st.executeBatch(); conn.commit(); st.clearBatch(); } } } catch (Exception e) { try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } finally { closeAll(st, conn); } }
From source file:org.ulyssis.ipp.processor.Processor.java
/** * Restore the state from the database/* ww w. jav a 2s .c o m*/ * * @return Whether we could restore from db, if false, we're starting from a clean slate */ private boolean restoreFromDb() { Connection connection = null; Snapshot oldSnapshot = this.snapshot; try { connection = Database.createConnection(EnumSet.of(READ_WRITE)); Optional<Snapshot> snapshot = Snapshot.loadLatest(connection); if (snapshot.isPresent()) { this.snapshot = snapshot.get(); connection.commit(); return true; } else { List<Event> events = Event.loadAll(connection); Snapshot snapshotBefore = this.snapshot; // Instant now = Instant.now(); // TODO: Handle future events later! for (Event event : events) { if (!event.isRemoved()/* && event.getTime().isBefore(now)*/) { // TODO: Future events later! this.snapshot = event.apply(this.snapshot); this.snapshot.save(connection); } } connection.commit(); return !Objects.equals(this.snapshot, snapshotBefore); } } catch (SQLException | IOException e) { LOG.error("An error occurred when restoring from database!", e); this.snapshot = oldSnapshot; try { if (connection != null) { connection.rollback(); } } catch (SQLException e2) { LOG.error("Error in rollback after previous error", e2); } return false; } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { LOG.error("Error while closing connection", e); } } } }
From source file:edu.uga.cs.fluxbuster.db.PostgresDBInterface.java
/** * Executes a PostgresSQL copy command.//from w ww. j a va 2 s.c om * * @param query the copy command to execute * @param reader the containing the data to be copied */ private void executeCopyIn(String query, Reader reader) { Connection con = null; CopyManager manager = null; try { con = this.getConnection(); con.setAutoCommit(false); if (con instanceof com.jolbox.bonecp.ConnectionHandle) { ConnectionHandle handle = (ConnectionHandle) con; manager = new CopyManager((BaseConnection) handle.getInternalConnection()); } else { manager = new CopyManager((BaseConnection) con); } manager.copyIn(query, reader); con.commit(); } catch (Exception e) { if (log.isErrorEnabled()) { log.error(query, e); } if (con != null) { try { con.rollback(); } catch (SQLException e1) { if (log.isErrorEnabled()) { log.error("Error during rollback.", e1); } } } } finally { try { if (con != null && !con.isClosed()) { con.setAutoCommit(true); con.close(); } } catch (SQLException e) { if (log.isErrorEnabled()) { log.error("Error during close.", e); } } } }
From source file:es.juntadeandalucia.panelGestion.negocio.utiles.JDBCConnector.java
/** * TODO/*w ww. ja v a 2s . c om*/ * * @param sql * @return */ public String getGeometryType(String sql) throws Exception { Exception error = null; String geometryType = null; Connection connection = null; PreparedStatement preparedStmnt = null; try { DataSource dataSource = poolDataSources.get(schemaId); connection = dataSource.getConnection(); connection.setAutoCommit(false); preparedStmnt = connection.prepareStatement(sql); ResultSet result = preparedStmnt.executeQuery(); while (result.next()) { geometryType = result.getString("type"); } } catch (SQLException e) { error = e; } finally { if (connection != null) { try { if (error != null) { connection.rollback(); } } catch (SQLException se) { log.warn("Se produjo un error al manejar la conexin: ".concat(se.getLocalizedMessage())); } try { connection.close(); } catch (SQLException se) { log.warn("Se produjo un error al intentar cerrar la conexin: " .concat(se.getLocalizedMessage())); } } } if (error != null) { throw error; } return geometryType; }