List of usage examples for java.sql Connection setAutoCommit
void setAutoCommit(boolean autoCommit) throws SQLException;
From source file:eionet.cr.dao.virtuoso.VirtuosoEndpointHarvestQueryDAO.java
@Override public void move(String endpointUrl, Set<Integer> ids, int direction) throws DAOException { if (StringUtils.isBlank(endpointUrl) || ids == null || ids.isEmpty()) { return;/*from w w w . j a v a2 s. c o m*/ } if (direction == 0) { throw new IllegalArgumentException("Direction must not be 0!"); } // Prepare map where we can get queries by position, also find the max and min positions. LinkedHashMap<Integer, EndpointHarvestQueryDTO> queriesByPos = getQueriesByPosition(endpointUrl); if (queriesByPos.isEmpty()) { return; } Set<Integer> positions = queriesByPos.keySet(); int maxPos = Collections.max(positions); int minPos = Collections.min(positions); Connection conn = null; try { conn = getSQLConnection(); conn.setAutoCommit(false); // If even one query is already at position 1 then moving up is not considered possible. // And conversely, if even one query is already at the last position, then moving down // is not considered possible either. boolean isMovingPossible = true; List<Integer> selectedPositions = new ArrayList<Integer>(); List<EndpointHarvestQueryDTO> queries = new ArrayList<EndpointHarvestQueryDTO>(queriesByPos.values()); for (EndpointHarvestQueryDTO query : queries) { if (ids.contains(query.getId())) { int pos = query.getPosition(); if ((direction < 0 && pos == minPos) || (direction > 0 && pos == maxPos)) { isMovingPossible = false; } else { selectedPositions.add(pos); } } } if (isMovingPossible) { if (direction < 0) { for (Integer selectedPosition : selectedPositions) { EndpointHarvestQueryDTO queryToMove = queriesByPos.get(selectedPosition); int i = queries.indexOf(queryToMove); queries.set(i, queries.get(i - 1)); queries.set(i - 1, queryToMove); } } else { for (int j = selectedPositions.size() - 1; j >= 0; j--) { EndpointHarvestQueryDTO queryToMove = queriesByPos.get(selectedPositions.get(j)); int i = queries.indexOf(queryToMove); queries.set(i, queries.get(i + 1)); queries.set(i + 1, queryToMove); } } } SQLUtil.executeUpdate(INCREASE_POSITIONS_SQL, Arrays.asList(maxPos, endpointUrl), conn); for (int i = 0; i < queries.size(); i++) { SQLUtil.executeUpdate(UPDATE_POSITION_SQL, Arrays.asList(i + 1, queries.get(i).getId()), conn); } conn.commit(); } catch (Exception e) { SQLUtil.rollback(conn); throw new DAOException(e.getMessage(), e); } finally { SQLUtil.close(conn); } }
From source file:com.viettel.logistic.wms.service.SerialInventoryServiceImpl.java
@Override public ResultDTO insertListSerialInventoryBatch(List<SerialInventoryDTO> serialInventoryDTO) { ResultDTO resultDTO = new ResultDTO(); Transaction transaction;/*from w ww . j av a 2 s . c o m*/ Connection connection = null; Session session = sessionFactory.openSession(); transaction = session.getTransaction(); transaction.begin(); SessionFactory sessionFactoryBatch = session.getSessionFactory(); try { connection = sessionFactoryBatch.getSessionFactoryOptions().getServiceRegistry() .getService(ConnectionProvider.class).getConnection(); connection.setAutoCommit(false); } catch (SQLException ex) { Logger.getLogger(SerialInventoryServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } resultDTO = serialInventoryBusiness2.insertListSerialInventoryBatch(serialInventoryDTO, connection); if (!resultDTO.getMessage().equals(ParamUtils.SUCCESS)) { rollback(session, transaction, connection); } commit(session, transaction, connection); return resultDTO; }
From source file:com.wso2telco.aggregatorblacklist.dao.ProvisionDAO.java
public boolean insertMerchantProvision(Integer appID, String subscriber, String operator, String[] merchants) throws SQLException, Exception { Connection con = null; ResultSet rs = null;/*from www.j a v a2 s .co m*/ PreparedStatement insertStatement = null; PreparedStatement selectStatement = null; try { con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB); if (con == null) { throw new Exception("Connection not found"); } /** * Set autocommit off to handle the transaction */ con.setAutoCommit(false); StringBuilder selectQueryString = new StringBuilder(" SELECT id "); selectQueryString.append(" FROM "); selectQueryString.append(DatabaseTables.OPERATORS.getTableName()); selectQueryString.append(" WHERE operatorname = '" + operator + "'"); selectStatement = con.prepareStatement(selectQueryString.toString()); rs = selectStatement.executeQuery(); int operatorid = 0; if (rs.next()) { operatorid = rs.getInt("id"); } else { throw new Exception("Operator Not Found"); } for (int i = 0; i < merchants.length; i++) { StringBuilder insertQueryString = new StringBuilder("INSERT INTO "); insertQueryString.append(DatabaseTables.MERCHANTOPCO_BLACKLIST.getTableName()); insertQueryString.append(" (application_id, operator_id, subscriber, merchant) "); insertQueryString.append("VALUES (?, ?, ?, ?)"); insertStatement = con.prepareStatement(insertQueryString.toString()); if (appID == null) { insertStatement.setNull(1, Types.INTEGER); } else { insertStatement.setInt(1, appID); } insertStatement.setInt(2, operatorid); insertStatement.setString(3, subscriber); insertStatement.setString(4, merchants[i]); insertStatement.executeUpdate(); /** * commit the transaction if all success */ con.commit(); } } catch (SQLException e) { /** * rollback if Exception occurs */ con.rollback(); log.error("database operation error in Merachantopco Blacklist Entry : ", e); throw e; } catch (Exception e) { /** * rollback if Exception occurs */ con.rollback(); log.error("Error while Provisioning Merchant : ", e); throw e; } finally { DbUtils.closeAllConnections(selectStatement, con, rs); DbUtils.closeAllConnections(insertStatement, null, null); } return true; }
From source file:com.wabacus.system.dataset.update.action.rationaldb.AbsRationalDBUpdateAction.java
public void commitTransaction(ReportRequest rrequest) { Connection conn = rrequest.getConnection(this.datasource); try {// w w w. j av a2 s . co m if (conn.getAutoCommit()) return; conn.commit(); conn.setAutoCommit(true); } catch (SQLException e) { throw new WabacusRuntimeException( "??" + this.ownerUpdateBean.getOwner().getReportBean().getPath() + "??" + this.datasource + "", e); } }
From source file:com.wabacus.system.dataset.update.action.rationaldb.AbsRationalDBUpdateAction.java
public void rollbackTransaction(ReportRequest rrequest) { Connection conn = rrequest.getConnection(this.datasource); try {//www . j a v a 2 s .c o m if (conn.getAutoCommit()) return; conn.rollback(); conn.setAutoCommit(true); } catch (SQLException e) { throw new WabacusRuntimeException( "" + this.ownerUpdateBean.getOwner().getReportBean().getPath() + "??" + this.datasource + "", e); } }
From source file:com.uber.stream.kafka.chaperone.collector.reporter.DbAuditReporter.java
private void maybeCreateTable(String sql, String tblName) { Connection conn = null; PreparedStatement stmt = null; try {/*from w w w .j av a 2 s. c om*/ conn = getConnection(); conn.setAutoCommit(true); stmt = conn.prepareStatement(String.format(sql, tblName)); stmt.executeUpdate(); } catch (Exception e) { logger.warn("Got exception to create table={} with sql={}", tblName, sql, e); rollback(conn); } finally { closeDbResource(null, stmt, conn); } }
From source file:com.stgmastek.core.purge.PurgeBatchDetails.java
/** * The method to delete batch details/*from ww w. j a v a2 s.co m*/ * <p> * Deletes the batch details from tables in the following order * </p> * <li>SYSTEM_INFO</li><li>LOG</li><li>INSTRUCTION_PARAMETERS</li><li> * INSTRUCTION_LOG</li> <li>PROGRESS_LEVEL</li><li>BATCH</li> * * @param batchNoList * Batch numbers list */ private void deleteBatchDetails(Connection con, ArrayList<String> batchNoList) throws SQLException { PreparedStatement psUpdate = null; int count = 1; out.println("Deleting batch details started.."); try { con.setAutoCommit(false); for (String strBacthNo : batchNoList) { log("SYSTEM_INFO", count, batchNoList.size(), strBacthNo, 2); psUpdate = con.prepareStatement("delete from SYSTEM_INFO WHERE BATCH_NO = ?"); psUpdate.setString(1, strBacthNo); psUpdate.executeUpdate(); con.setAutoCommit(true); psUpdate.close(); log("LOG", count, batchNoList.size(), strBacthNo, 2); psUpdate = con.prepareStatement("delete from LOG WHERE BATCH_NO = ?"); psUpdate.setString(1, strBacthNo); psUpdate.executeUpdate(); psUpdate.close(); log("INSTRUCTION_PARAMETERS", count, batchNoList.size(), strBacthNo, 2); psUpdate = con.prepareStatement( "delete from INSTRUCTION_PARAMETERS b where exists (select a.seq_no from instruction_log a where a.seq_no = b.instruction_log_no and a.batch_no = ? )"); psUpdate.setString(1, strBacthNo); psUpdate.executeUpdate(); psUpdate.close(); log("INSTRUCTION_LOG", count, batchNoList.size(), strBacthNo, 2); psUpdate = con.prepareStatement("delete from INSTRUCTION_LOG WHERE BATCH_NO = ?"); psUpdate.setString(1, strBacthNo); psUpdate.executeUpdate(); psUpdate.close(); log("PROGRESS_LEVEL", count, batchNoList.size(), strBacthNo, 2); psUpdate = con.prepareStatement("delete from PROGRESS_LEVEL WHERE BATCH_NO = ?"); psUpdate.setString(1, strBacthNo); psUpdate.executeUpdate(); psUpdate.close(); log("BATCH", count, batchNoList.size(), strBacthNo, 2); psUpdate = con.prepareStatement("delete from BATCH WHERE BATCH_NO = ?"); psUpdate.setString(1, strBacthNo); psUpdate.executeUpdate(); psUpdate.close(); count++; } out.println("Deleting batch details completed."); con.commit(); } catch (SQLException e) { logger.error("SQLException in getting batch details based on installation codes ", e); try { con.rollback(); } catch (SQLException e2) { } throw e; } finally { try { if (psUpdate != null) { psUpdate.close(); } } catch (SQLException e) { } try { con.setAutoCommit(true); } catch (SQLException e2) { } } }
From source file:eionet.cr.dao.virtuoso.VirtuosoPostHarvestScriptDAO.java
/** * @see eionet.cr.dao.PostHarvestScriptDAO#insert(eionet.cr.dto.PostHarvestScriptDTO.TargetType, java.lang.String, * java.lang.String, java.lang.String, boolean, boolean) *//*from www .j a va 2 s .co m*/ @Override public int insert(TargetType targetType, String targetUrl, String title, String script, boolean active, boolean runOnce) throws DAOException { String sourceUrl = targetType != null && targetType.equals(TargetType.SOURCE) ? targetUrl : null; String typeUrl = targetType != null && targetType.equals(TargetType.TYPE) ? targetUrl : null; Connection conn = null; try { conn = getSQLConnection(); conn.setAutoCommit(false); ArrayList<Object> values = new ArrayList<Object>(); values.add(sourceUrl == null ? "" : sourceUrl); values.add(typeUrl == null ? "" : typeUrl); Object o = SQLUtil.executeSingleReturnValueQuery(GET_LAST_POSITION_SQL, values, conn); int position = o == null ? 1 : Integer.parseInt(o.toString()) + 1; values = new ArrayList<Object>(); values.add(sourceUrl); values.add(typeUrl); values.add(title); values.add(script); values.add(Integer.valueOf(position)); values.add(YesNoBoolean.format(active)); values.add(YesNoBoolean.format(runOnce)); int result = SQLUtil.executeUpdateReturnAutoID(INSERT_SQL, values, conn); conn.commit(); return result; } catch (Exception e) { SQLUtil.rollback(conn); throw new DAOException(e.getMessage(), e); } finally { SQLUtil.close(conn); } }
From source file:at.rocworks.oa4j.logger.dbs.NoSQLJDBC.java
public int storeData(DataList list) { try {//from w w w . j a v a2 s .c o m Connection conn = dataSourceWrite.getConnection(); if (conn != null) { int i; DataItem item; EventItem event; Object tag; conn.setAutoCommit(false); PreparedStatement stmt; Date t1 = new Date(); stmt = conn.prepareStatement(sqlInsertStmt); for (i = 0; i <= list.getHighWaterMark() && (item = list.getItem(i)) != null; i++) { if (!(item instanceof EventItem)) continue; event = (EventItem) item; ValueItem val = event.getValue(); tag = this.getTagOfDp(event.getDp()); if (tag == null) continue; if (tag instanceof Long) stmt.setLong(1, (Long) tag); else if (tag instanceof String) stmt.setString(1, (String) tag); java.sql.Timestamp ts = new java.sql.Timestamp(event.getTimeMS()); ts.setNanos(event.getNanos()); stmt.setTimestamp(2, ts, cal); Double dval = val.getDouble(); if (dval != null) { stmt.setDouble(3, dval); } else { stmt.setNull(3, Types.DOUBLE); } // value_string stmt.setString(4, val.getString()); // value_timestamp if (val.getTimeMS() != null) stmt.setTimestamp(5, new java.sql.Timestamp(val.getTimeMS()), cal); else stmt.setNull(5, Types.TIMESTAMP); // status, manager, user if (event.hasAttributes()) { stmt.setLong(6, event.getStatus()); stmt.setInt(7, event.getManager()); stmt.setInt(8, event.getUser()); } else { stmt.setNull(6, Types.INTEGER); stmt.setNull(7, Types.INTEGER); stmt.setNull(8, Types.INTEGER); } //JDebug.out.log(Level.FINE, "{0}:{1}/{2} [{3}]", new Object[] {i, element_id.toString(), ts.toString(), item.toString()}); stmt.addBatch(); } try { stmt.executeBatch(); // TODO check result? int[] res = } catch (BatchUpdateException ex) { JDebug.out.log(Level.SEVERE, "Batch exception {0} update count {1}.", new Object[] { ex.getErrorCode(), ex.getUpdateCounts().length }); JDebug.StackTrace(Level.SEVERE, ex); } catch (SQLException ex) { SQLException current = ex; do { JDebug.out.log(Level.SEVERE, "SQL exception {0}.", new Object[] { ex.getErrorCode() }); JDebug.StackTrace(Level.SEVERE, current); } while ((current = current.getNextException()) != null); // for (i = 0; i <= list.getHighWaterMark() && (item = list.getItem(i)) != null; i++) { // JDebug.out.log(Level.INFO, "{0}", item.toJSONObject()); // } } Date t2 = new Date(); stmt.close(); afterInsert(conn); conn.commit(); conn.close(); addServerStats(list.getHighWaterMark(), t2.getTime() - t1.getTime()); return INoSQLInterface.OK; } else { JDebug.StackTrace(Level.SEVERE, "no connection!"); return INoSQLInterface.ERR_REPEATABLE; } } catch (Exception ex) { JDebug.StackTrace(Level.SEVERE, ex); return INoSQLInterface.ERR_REPEATABLE; } }
From source file:com.wso2telco.dep.mediator.dao.ProvisionDAO.java
public void provisionServiceOperatorEntry(String operatorEndpoint, Integer provisionServiceId, String operatorName) throws SQLException, Exception { Connection con = null; PreparedStatement insertStatement = null; PreparedStatement updateStatement = null; try {/*from w w w . j av a2 s. c o m*/ con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB); if (con == null) { throw new Exception("Connection not found"); } /** * Set autocommit off to handle the transaction */ con.setAutoCommit(false); StringBuilder queryString = new StringBuilder("INSERT INTO "); queryString.append(DatabaseTables.PROVISION_SERVICE_OPERATOR_ENDPOINTS.getTableName()); queryString.append(" (provision_service_did, domainurl, operator) "); queryString.append("VALUES (?, ?, ?)"); insertStatement = con.prepareStatement(queryString.toString()); insertStatement.setInt(1, provisionServiceId); insertStatement.setString(2, operatorEndpoint); insertStatement.setString(3, operatorName); log.debug("sql query in provisionServiceOperatorEntry : " + insertStatement); insertStatement.executeUpdate(); StringBuilder updateQueryString = new StringBuilder("UPDATE "); updateQueryString.append(DatabaseTables.PROVISION_SERVICE_ENTRY.getTableName()); updateQueryString.append(" SET is_active = ?"); updateQueryString.append(" WHERE provision_service_did = ?"); updateStatement = con.prepareStatement(updateQueryString.toString()); updateStatement.setInt(1, 1); updateStatement.setInt(2, provisionServiceId); log.debug("sql query in provisionServiceOperatorEntry : " + updateStatement); updateStatement.executeUpdate(); /** * commit the transaction if all success */ con.commit(); } catch (SQLException e) { /** * rollback if Exception occurs */ con.rollback(); log.error("database operation error in provisionServiceOperatorEntry : ", e); throw e; } catch (Exception e) { /** * rollback if Exception occurs */ con.rollback(); log.error("error in provisionServiceOperatorEntry : ", e); throw e; } finally { DbUtils.closeAllConnections(insertStatement, con, null); DbUtils.closeAllConnections(updateStatement, null, null); } }