List of usage examples for java.sql Connection rollback
void rollback() throws SQLException;
Connection
object. From source file:org.apache.hadoop.hive.metastore.txn.TxnHandler.java
static void rollbackDBConn(Connection dbConn) { try {/*from w w w . j a v a 2s . c o m*/ if (dbConn != null && !dbConn.isClosed()) dbConn.rollback(); } catch (SQLException e) { LOG.warn("Failed to rollback db connection " + getMessage(e)); } }
From source file:com.wso2telco.dep.mediator.dao.SMSMessagingDAO.java
/** * Outbound subscription delete.//from ww w. j a v a 2 s . co m * * @param dnSubscriptionId * the dnSubscriptionId * @return true, if successful * @throws Exception * the exception */ public void outboundSubscriptionDelete(Integer dnSubscriptionId) throws SQLException, Exception { Connection con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB); PreparedStatement deleteSubscriptionsStatement = null; PreparedStatement deleteOperatorSubscriptionsStatement = null; try { if (con == null) { throw new Exception("Connection not found"); } /** * Set autocommit off to handle the transaction */ con.setAutoCommit(false); StringBuilder deleteSubscriptionsQueryString = new StringBuilder("DELETE FROM "); deleteSubscriptionsQueryString.append(DatabaseTables.OUTBOUND_SUBSCRIPTIONS.getTableName()); deleteSubscriptionsQueryString.append(" WHERE dn_subscription_did = ?"); deleteSubscriptionsStatement = con.prepareStatement(deleteSubscriptionsQueryString.toString()); deleteSubscriptionsStatement.setInt(1, dnSubscriptionId); log.debug("sql query in outboundSubscriptionDelete : " + deleteSubscriptionsStatement); deleteSubscriptionsStatement.executeUpdate(); StringBuilder deleteOperatorSubscriptionsQueryString = new StringBuilder("DELETE FROM "); deleteOperatorSubscriptionsQueryString.append(DatabaseTables.OUTBOUND_OPERATORSUBS.getTableName()); deleteOperatorSubscriptionsQueryString.append(" WHERE dn_subscription_did = ?"); deleteOperatorSubscriptionsStatement = con .prepareStatement(deleteOperatorSubscriptionsQueryString.toString()); deleteOperatorSubscriptionsStatement.setInt(1, dnSubscriptionId); log.debug("sql query in outboundSubscriptionDelete : " + deleteOperatorSubscriptionsStatement); deleteOperatorSubscriptionsStatement.executeUpdate(); /** * commit the transaction if all success */ con.commit(); } catch (SQLException e) { /** * rollback if Exception occurs */ con.rollback(); log.error("database operation error in outboundSubscriptionDelete : ", e); throw e; } catch (Exception e) { /** * rollback if Exception occurs */ con.rollback(); log.error("error in outboundSubscriptionDelete : ", e); throw e; } finally { DbUtils.closeAllConnections(deleteSubscriptionsStatement, con, null); DbUtils.closeAllConnections(deleteOperatorSubscriptionsStatement, null, null); } }
From source file:com.skilrock.lms.coreEngine.scratchService.orderMgmt.common.AgentOrderProcessHelper.java
/** * This method is used for generating order for a retailer. Returns true if * the order is successfully generated//from ww w.jav a 2 s . c o m * * @param userId * @param cartList * @param retOrgList * @param retOrgName * @return boolean * @throws LMSException */ public int generateOrder(int userId, List<GameBean> cartList, List<OrgBean> retOrgList, String retOrgName, int userOrgId) throws LMSException { int retOrgId = -1; int retailerId = -1; if (retOrgList != null) { OrgBean bean = null; for (int i = 0; i < retOrgList.size(); i++) { bean = retOrgList.get(i); logger.debug("---OrG Name::" + bean.getOrgName()); if (retOrgName.equals(bean.getOrgName())) { retOrgId = bean.getOrgId(); retailerId = bean.getUserId(); logger.debug("RetOrgId::" + retOrgId); logger.debug("retailerId::" + retailerId); break; } } } logger.debug("RetOrgId::" + retOrgId); logger.debug("retailerId::" + retailerId); Connection connection = null; PreparedStatement orderPstmt = null; PreparedStatement gamePstmt = null; ResultSet resultSet = null; int orderId = -1; if (cartList != null) { int size = cartList.size(); // QueryManager queryManager = null; GameBean gameBean = null; String orderQuery = null; String gameQuery = null; if (size > 0) { try { // create database connection connection = DBConnect.getConnection(); connection.setAutoCommit(false); // get order query orderQuery = QueryManager.getST1InsertAgtOrderQuery(); orderPstmt = connection.prepareStatement(orderQuery); // get ordered game query gameQuery = QueryManager.getST1InsertAgtOrderedGamesQuery(); gamePstmt = connection.prepareStatement(gameQuery); // set parameters for insert into order table orderPstmt.setInt(1, userId); orderPstmt.setInt(2, retailerId); orderPstmt.setInt(3, retOrgId); orderPstmt.setDate(4, new java.sql.Date(new Date().getTime())); orderPstmt.setString(5, "APPROVED"); orderPstmt.setString(6, "Y"); orderPstmt.setInt(7, userOrgId); orderPstmt.execute(); resultSet = orderPstmt.getGeneratedKeys(); while (resultSet.next()) { orderId = resultSet.getInt(1); } logger.debug("OrderId::" + orderId); // set parameters for insert into ordered games table for (int i = 0; i < size; i++) { gameBean = cartList.get(i); logger.debug("1:" + gameBean.getGameId()); logger.debug("2:" + gameBean.getOrderedQty()); gamePstmt.setInt(1, orderId); gamePstmt.setInt(2, gameBean.getGameId()); gamePstmt.setInt(3, gameBean.getOrderedQty()); gamePstmt.setInt(4, gameBean.getOrderedQty()); gamePstmt.execute(); } // commit the connection connection.commit(); return orderId; } catch (SQLException e) { try { connection.rollback(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); throw new LMSException(e); } finally { try { if (orderPstmt != null) { orderPstmt.close(); } if (gamePstmt != null) { gamePstmt.close(); } if (connection != null) { connection.close(); } } catch (SQLException se) { se.printStackTrace(); } } } } return orderId; }
From source file:com.wso2telco.dep.mediator.dao.SMSMessagingDAO.java
/** * Operatorsubs entry./*from w w w. ja v a 2 s.c om*/ * * @param domainsubs * the domainsubs * @param moSubscriptionId * the moSubscriptionId * @return true, if successful * @throws Exception * the exception */ public void operatorSubsEntry(List<OperatorSubscriptionDTO> domainsubs, Integer moSubscriptionId) throws SQLException, Exception { Connection con = null; PreparedStatement insertStatement = null; PreparedStatement updateStatement = 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 queryString = new StringBuilder("INSERT INTO "); queryString.append(DatabaseTables.OPERATORSUBS.getTableName()); queryString.append(" (mo_subscription_did, domainurl, operator) "); queryString.append("VALUES (?, ?, ?)"); insertStatement = con.prepareStatement(queryString.toString()); for (OperatorSubscriptionDTO d : domainsubs) { insertStatement.setInt(1, moSubscriptionId); insertStatement.setString(2, d.getDomain()); insertStatement.setString(3, d.getOperator()); insertStatement.addBatch(); } log.debug("sql query in operatorSubsEntry : " + insertStatement); insertStatement.executeBatch(); StringBuilder updateQueryString = new StringBuilder("UPDATE "); updateQueryString.append(DatabaseTables.SUBSCRIPTIONS.getTableName()); updateQueryString.append(" SET is_active = ?"); updateQueryString.append(" WHERE mo_subscription_did = ?"); updateStatement = con.prepareStatement(updateQueryString.toString()); updateStatement.setInt(1, 1); updateStatement.setInt(2, moSubscriptionId); log.debug("sql query in operatorSubsEntry : " + 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 operatorSubsEntry : ", e); throw e; } catch (Exception e) { /** * rollback if Exception occurs */ con.rollback(); log.error("error in operatorSubsEntry : ", e); throw e; } finally { DbUtils.closeAllConnections(insertStatement, con, null); DbUtils.closeAllConnections(updateStatement, null, null); } }
From source file:com.concursive.connect.web.modules.login.dao.User.java
/** * There's quite a bit of work to delete a user, so active users will * not be able to be deleted; this will simply delete a user without any * related data and without a profile//from www . j ava 2 s . c om * * @param db Description of the Parameter * @return Description of the Return Value * @throws SQLException Description of the Exception */ public int delete(Connection db) throws SQLException { int count = 0; boolean commit = db.getAutoCommit(); try { if (commit) { db.setAutoCommit(false); } // Delete any login records PreparedStatement pst = db.prepareStatement("DELETE FROM user_log WHERE user_id = ?"); pst.setInt(1, id); pst.execute(); pst.close(); // Delete the user pst = db.prepareStatement("DELETE FROM users WHERE user_id = ?"); pst.setInt(1, id); count = pst.executeUpdate(); pst.close(); if (commit) { db.commit(); } CacheUtils.invalidateValue(Constants.SYSTEM_USER_CACHE, id); //@todo enable //CacheUtils.invalidateValue(Constants.SYSTEM_USER_PROJECT_ROLE_CACHE, id); } catch (SQLException e) { if (commit) { db.rollback(); } throw new SQLException(e.getMessage()); } finally { if (commit) { db.setAutoCommit(true); } } return count; }
From source file:com.wso2telco.dep.mediator.dao.SMSMessagingDAO.java
/** * Outbound operatorsubs entry./*from ww w . jav a 2 s .c o m*/ * * @param domainsubs * the domainsubs * @param dnSubscriptionId * the dnSubscriptionId * @return true, if successful * @throws Exception * the exception */ public void outboundOperatorsubsEntry(List<OperatorSubscriptionDTO> domainsubs, Integer dnSubscriptionId) throws SQLException, Exception { Connection con = null; PreparedStatement insertStatement = null; PreparedStatement updateStatement = 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 queryString = new StringBuilder("INSERT INTO "); queryString.append(DatabaseTables.OUTBOUND_OPERATORSUBS.getTableName()); queryString.append(" (dn_subscription_did, domainurl, operator) "); queryString.append("VALUES (?, ?, ?)"); insertStatement = con.prepareStatement(queryString.toString()); for (OperatorSubscriptionDTO d : domainsubs) { insertStatement.setInt(1, dnSubscriptionId); insertStatement.setString(2, d.getDomain()); insertStatement.setString(3, d.getOperator()); insertStatement.addBatch(); } log.debug("sql query in outboundOperatorsubsEntry : " + insertStatement); insertStatement.executeBatch(); StringBuilder updateQueryString = new StringBuilder("UPDATE "); updateQueryString.append(DatabaseTables.OUTBOUND_SUBSCRIPTIONS.getTableName()); updateQueryString.append(" SET is_active = ?"); updateQueryString.append(" WHERE dn_subscription_did = ?"); updateStatement = con.prepareStatement(updateQueryString.toString()); updateStatement.setInt(1, 1); updateStatement.setInt(2, dnSubscriptionId); log.debug("sql query in outboundOperatorsubsEntry : " + 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 outboundOperatorsubsEntry : ", e); throw e; } catch (Exception e) { /** * rollback if Exception occurs */ con.rollback(); log.error("error in outboundOperatorsubsEntry : ", e); throw e; } finally { DbUtils.closeAllConnections(insertStatement, con, null); DbUtils.closeAllConnections(updateStatement, null, null); } }
From source file:com.wso2telco.dep.mediator.dao.SMSMessagingDAO.java
public boolean operatorsubsEntry(List<OperatorSubscriptionDTO> domainsubs, Integer dnSubscriptionId) throws SQLException, Exception { Connection con = null; PreparedStatement insertStatement = null; PreparedStatement updateStatement = null; try {//from w w w. j a v a 2s .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.OUTBOUND_OPERATORSUBS.getTableName()); queryString.append(" (dn_subscription_did, domainurl, operator) "); queryString.append("VALUES (?, ?, ?)"); insertStatement = con.prepareStatement(queryString.toString()); for (OperatorSubscriptionDTO d : domainsubs) { insertStatement.setInt(1, dnSubscriptionId); insertStatement.setString(2, d.getDomain()); insertStatement.setString(3, d.getOperator()); insertStatement.addBatch(); } log.debug("sql query in outboundOperatorsubsEntry : " + insertStatement); insertStatement.executeBatch(); StringBuilder updateQueryString = new StringBuilder("UPDATE "); updateQueryString.append(DatabaseTables.OUTBOUND_SUBSCRIPTIONS.getTableName()); updateQueryString.append(" SET is_active = ?"); updateQueryString.append(" WHERE dn_subscription_did = ?"); updateStatement = con.prepareStatement(updateQueryString.toString()); updateStatement.setInt(1, 1); updateStatement.setInt(2, dnSubscriptionId); log.debug("sql query in outboundOperatorsubsEntry : " + 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 outboundOperatorsubsEntry : ", e); throw e; } catch (Exception e) { /** * rollback if Exception occurs */ con.rollback(); log.error("error in outboundOperatorsubsEntry : ", e); throw e; } finally { DbUtils.closeAllConnections(insertStatement, con, null); DbUtils.closeAllConnections(updateStatement, null, null); } return true; }
From source file:hoot.services.controllers.osm.ChangesetResource.java
/** * <NAME>Changeset Create</NAME> * <DESCRIPTION>/*from w w w.j a v a 2 s . c o m*/ * The Hootenanny Changeset Service implements a subset of the OSM * Changeset Service v0.6. It supports the OSM changeset upload process only. * It does not support the browsing of changeset contents. * </DESCRIPTION> * <PARAMETERS> * <mapId> * string; ID or name of the map to which the created changeset will belong * </mapId> * <changesetData> * XML; payload data; an empty OSM xml changeset * </changesetData> * </PARAMETERS> * <OUTPUT> * ID of the created changeset * </OUTPUT> * <EXAMPLE> * <URL>http://localhost:8080/hoot-services/osm/api/0.6/changeset/create?mapId=dc-admin</URL> * <REQUEST_TYPE>PUT</REQUEST_TYPE> * <INPUT> * Changeset OSM XML * See https://insightcloud.digitalglobe.com/redmine/projects/hootenany/wiki/User_-_OsmChangesetService#Changeset-Create * </INPUT> * <OUTPUT> * 1 * </OUTPUT> * </EXAMPLE> * * Service method endpoint for creating a new OSM changeset * * @param changeset changeset create data * @param mapId ID of the map the changeset belongs to * @return Response containing the ID assigned to the new changeset * @throws Exception * @todo why can't I get changesetData in as an XML doc? * @todo update for parsing multiple changesets in one request (#2894): duplicated changeset tag keys are allowed but later changeset tag keys overwrite earlier ones; isn't that contradictory with the rest of the logic in this method? * @see https://insightcloud.digitalglobe.com/redmine/projects/hootenany/wiki/User_-_OsmChangesetService#Changeset-Create */ @PUT @Path("/create") @Consumes(MediaType.TEXT_XML) @Produces(MediaType.TEXT_PLAIN) public Response create(final String changesetData, @QueryParam("mapId") final String mapId) throws Exception { log.debug("Creating changeset for map with ID: " + mapId + " ..."); Document changesetDoc = null; try { log.debug("Parsing changeset XML..."); changesetDoc = XmlDocumentBuilder.parse(changesetData); } catch (Exception e) { ResourceErrorHandler.handleError("Error parsing changeset XML: " + StringUtils.abbreviate(changesetData, 100) + " (" + e.getMessage() + ")", Status.BAD_REQUEST, log); } Connection conn = DbUtils.createConnection(); long changesetId = -1; try { log.debug("Initializing database connection..."); long mapIdNum = -1; try { QMaps maps = QMaps.maps; //input mapId may be a map ID or a map name mapIdNum = ModelDaoUtils.getRecordIdForInputString(mapId, conn, maps, maps.id, maps.displayName); } catch (Exception e) { if (e.getMessage().startsWith("Multiple records exist")) { ResourceErrorHandler.handleError( e.getMessage().replaceAll("records", "maps").replaceAll("record", "map"), Status.NOT_FOUND, log); } else if (e.getMessage().startsWith("No record exists")) { ResourceErrorHandler.handleError( e.getMessage().replaceAll("records", "maps").replaceAll("record", "map"), Status.NOT_FOUND, log); } ResourceErrorHandler.handleError( "Error requesting map with ID: " + mapId + " (" + e.getMessage() + ")", Status.BAD_REQUEST, log); } long userId = -1; try { assert (mapIdNum != -1); log.debug("Retrieving user ID associated with map having ID: " + String.valueOf(mapIdNum) + " ..."); QMaps maps = QMaps.maps; SQLQuery query = new SQLQuery(conn, DbUtils.getConfiguration()); userId = query.from(maps).where(maps.id.eq(mapIdNum)).singleResult(maps.userId); log.debug("Retrieved user ID: " + userId); } catch (Exception e) { ResourceErrorHandler.handleError( "Error locating user associated with map for changeset data: " + StringUtils.abbreviate(changesetData, 100) + " (" + e.getMessage() + ")", Status.BAD_REQUEST, log); } log.debug("Intializing transaction..."); TransactionStatus transactionStatus = transactionManager .getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED)); conn.setAutoCommit(false); try { changesetId = Changeset.createChangeset(changesetDoc, mapIdNum, userId, conn); } catch (Exception e) { log.error("Rolling back the database transaction..."); transactionManager.rollback(transactionStatus); conn.rollback(); ResourceErrorHandler.handleError("Error creating changeset: (" + e.getMessage() + ") " + StringUtils.abbreviate(changesetData, 100), Status.BAD_REQUEST, log); } log.debug("Committing the database transaction..."); transactionManager.commit(transactionStatus); conn.commit(); } finally { conn.setAutoCommit(true); DbUtils.closeConnection(conn); } log.debug("Returning ID: " + changesetId + " for new changeset..."); return Response.ok(String.valueOf(changesetId), MediaType.TEXT_PLAIN) .header("Content-type", MediaType.TEXT_PLAIN).build(); }
From source file:org.opennms.ng.services.capsd.BroadcastEventProcessor.java
/** * Process the event, add or remove a specified interface/service pair into * the database. this event will cause an changeService event with the * specified action. An 'action' parameter wraped in the event will tell * which action to take to the service on the specified interface. The * ipaddress of the interface, the service name must be included in the * event.//w ww . j av a 2 s. c om * * @param event The event to process. * @throws org.opennms.netmgt.capsd.InsufficientInformationException if there is missing information in the event * @throws org.opennms.netmgt.capsd.FailedOperationException if the operation fails for some reason */ @EventHandler(uei = EventConstants.UPDATE_SERVICE_EVENT_UEI) public void handleUpdateService(Event event) throws InsufficientInformationException, FailedOperationException { EventUtils.checkInterface(event); EventUtils.checkService(event); EventUtils.requireParm(event, EventConstants.PARM_NODE_LABEL); EventUtils.requireParm(event, EventConstants.PARM_ACTION); if (isXmlRpcEnabled()) { EventUtils.requireParm(event, EventConstants.PARM_TRANSACTION_NO); } long txNo = EventUtils.getLongParm(event, EventConstants.PARM_TRANSACTION_NO, -1L); String action = EventUtils.getParm(event, EventConstants.PARM_ACTION); String nodeLabel = EventUtils.getParm(event, EventConstants.PARM_NODE_LABEL); LOG.debug("handleUpdateService: processing updateService event for : {} on : {}", event.getService(), event.getInterface()); List<Event> eventsToSend = null; Connection dbConn = null; try { dbConn = getConnection(); dbConn.setAutoCommit(false); eventsToSend = doUpdateService(dbConn, nodeLabel, event.getInterface(), event.getService(), action, txNo); } catch (SQLException sqlE) { LOG.error("SQLException during handleUpdateService on database.", sqlE); throw new FailedOperationException(sqlE.getMessage()); } finally { if (dbConn != null) { try { if (eventsToSend != null) { dbConn.commit(); for (Event e : eventsToSend) { EventUtils.sendEvent(e, event.getUei(), txNo, isXmlRpcEnabled()); } } else { dbConn.rollback(); } } catch (SQLException ex) { LOG.error("handleUpdateService: Exception thrown during commit/rollback: ", ex); throw new FailedOperationException(ex.getMessage()); } finally { if (dbConn != null) { try { dbConn.close(); } catch (SQLException ex) { LOG.error("handleUpdateService: Exception thrown during close: ", ex); } } } } } }
From source file:org.opennms.ng.services.capsd.BroadcastEventProcessor.java
/** * Process an addNode event.//from w w w. ja v a2 s. c o m * * @param event The event to process. * @throws org.opennms.netmgt.capsd.InsufficientInformationException if the event is missing information * @throws org.opennms.netmgt.capsd.FailedOperationException if an error occurs during processing */ @EventHandler(uei = EventConstants.ADD_NODE_EVENT_UEI) public void handleAddNode(Event event) throws InsufficientInformationException, FailedOperationException { EventUtils.requireParm(event, EventConstants.PARM_NODE_LABEL); if (isXmlRpcEnabled()) { EventUtils.requireParm(event, EventConstants.PARM_TRANSACTION_NO); } String ipaddr = event.getInterface(); String nodeLabel = EventUtils.getParm(event, EventConstants.PARM_NODE_LABEL); long txNo = EventUtils.getLongParm(event, EventConstants.PARM_TRANSACTION_NO, -1L); LOG.debug("addNodeHandler: processing addNode event for {}", ipaddr); Connection dbConn = null; List<Event> eventsToSend = null; try { dbConn = getConnection(); dbConn.setAutoCommit(false); eventsToSend = doAddNode(dbConn, nodeLabel, ipaddr); } catch (SQLException sqlE) { LOG.error("addNodeHandler: SQLException during add node and ipaddress to tables", sqlE); throw new FailedOperationException("database error: " + sqlE.getMessage(), sqlE); } finally { if (dbConn != null) { try { if (eventsToSend != null) { dbConn.commit(); for (Event e : eventsToSend) { EventUtils.sendEvent(e, event.getUei(), txNo, isXmlRpcEnabled()); } } else { dbConn.rollback(); } } catch (SQLException ex) { LOG.error("handleAddNode: Threw Exception during commit: ", ex); throw new FailedOperationException("database error: " + ex.getMessage(), ex); } finally { if (dbConn != null) { try { dbConn.close(); } catch (SQLException ex) { LOG.error("handleAddNode: Threw Exception during close: ", ex); } } } } } }