Example usage for java.sql Connection rollback

List of usage examples for java.sql Connection rollback

Introduction

In this page you can find the example usage for java.sql Connection rollback.

Prototype

void rollback() throws SQLException;

Source Link

Document

Undoes all changes made in the current transaction and releases any database locks currently held by this Connection object.

Usage

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.JDBCConnector.java

public List<ColumnVO> getColumnsMetaDataExceptGeom(String sql, String geometryName) throws Exception {
    Exception error = null;//from  w  w w  .  j  a  v  a  2  s.  co m

    List<ColumnVO> tableColumns = new LinkedList<ColumnVO>();

    Connection connection = null;
    PreparedStatement preparedStmnt = null;

    try {
        DataSource dataSource = poolDataSources.get(schemaId);
        connection = dataSource.getConnection();
        connection.setAutoCommit(false);

        preparedStmnt = connection.prepareStatement(sql);
        ResultSet rs = preparedStmnt.executeQuery();
        ResultSetMetaData rsmd = rs.getMetaData();
        String geometryFieldName = geometryName;
        if (StringUtils.isEmpty(geometryFieldName)) {
            geometryFieldName = "the_geom";
        }
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            String columnName = rsmd.getColumnName(i);
            if (!columnName.equals(geometryFieldName)) {
                String columnType = rsmd.getColumnTypeName(i);
                int columnSqlType = rsmd.getColumnType(i);
                int columnLength = rsmd.getColumnDisplaySize(i);
                int columnPrecision = rsmd.getPrecision(i);

                ColumnVO column = new ColumnVO();
                column.setNameOnTable(columnName);
                column.setType(columnType);
                column.setSqlType(columnSqlType);
                column.setLength(columnLength);
                column.setPrecision(columnPrecision);
                column.setInTable(true);

                tableColumns.add(column);
            }

        }
    } catch (SQLException e) {
        error = e;
    } finally {
        if (preparedStmnt != null) {
            try {
                preparedStmnt.close();
            } catch (SQLException se2) {
                log.warn("No se pudo cerrar el statment: ".concat(se2.getLocalizedMessage()));
            }
        }
        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 tableColumns;
}

From source file:org.opennms.ng.services.capsd.BroadcastEventProcessor.java

/**
 * Process the event, add the specified interface into database. If the
 * associated node does not exist in the database yet, add a node into the
 * database./*from   w w  w.j  a  v  a  2 s  .c o  m*/
 *
 * @param event The event to process.
 * @throws org.opennms.netmgt.capsd.InsufficientInformationException if the event is missing essential information
 * @throws org.opennms.netmgt.capsd.FailedOperationException         if the operation fails (because of database error for
 *                                                                   example)
 */
@EventHandler(uei = EventConstants.ADD_INTERFACE_EVENT_UEI)
public void handleAddInterface(Event event) throws InsufficientInformationException, FailedOperationException {
    EventUtils.checkInterface(event);
    EventUtils.requireParm(event, EventConstants.PARM_NODE_LABEL);
    if (isXmlRpcEnabled()) {
        EventUtils.requireParm(event, EventConstants.PARM_TRANSACTION_NO);
    }
    LOG.debug("addInterfaceHandler:  processing addInterface event for {}", event.getInterface());

    String nodeLabel = EventUtils.getParm(event, EventConstants.PARM_NODE_LABEL);
    long txNo = EventUtils.getLongParm(event, EventConstants.PARM_TRANSACTION_NO, -1L);

    // First make sure the specified node label and ipaddress do not exist
    // in the database
    // before trying to add them in.
    Connection dbConn = null;
    List<Event> eventsToSend = null;
    try {
        dbConn = getConnection();
        dbConn.setAutoCommit(false);

        eventsToSend = doAddInterface(dbConn, nodeLabel, event.getInterface());
    } catch (SQLException sqlE) {
        LOG.error("addInterfaceHandler: SQLException during add node and ipaddress to the database.", 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("handleAddInterface: Threw Exception during commit: ", ex);
                throw new FailedOperationException("Database error: " + ex.getMessage(), ex);
            } finally {
                if (dbConn != null) {
                    try {
                        dbConn.setAutoCommit(true); //TODO:verify this
                        dbConn.close();
                    } catch (SQLException ex) {
                        LOG.error("handleAddInterface: Threw Exception during close: ", ex);
                    }
                }
            }
        }
    }
}

From source file:org.opennms.ng.services.capsd.BroadcastEventProcessor.java

/**
 * Handles the process of adding/updating a node.
 * TODO: Change the name of this to something that makes more sense.  This impacts the UEI of the named event
 * for consistency and clearity, however, being called "Server" is unclear to itself.  Change the event from
 * "Server" to "Node" and all related methods.
 *
 * @param event a {@link org.opennms.netmgt.xml.event.Event} object.
 * @throws org.opennms.netmgt.capsd.InsufficientInformationException if any.
 * @throws org.opennms.netmgt.capsd.FailedOperationException         if any.
 *///from ww  w.java 2  s .co  m
@EventHandler(uei = EventConstants.UPDATE_SERVER_EVENT_UEI)
public void handleUpdateServer(Event event) throws InsufficientInformationException, FailedOperationException {
    // If there is no interface or NMS server found then it cannot be
    // processed
    EventUtils.checkInterface(event);
    EventUtils.checkHost(event);
    EventUtils.requireParm(event, EventConstants.PARM_ACTION);
    EventUtils.requireParm(event, EventConstants.PARM_NODE_LABEL);
    if (isXmlRpcEnabled()) {
        EventUtils.requireParm(event, EventConstants.PARM_TRANSACTION_NO);
    }

    String action = EventUtils.getParm(event, EventConstants.PARM_ACTION);
    String nodeLabel = EventUtils.getParm(event, EventConstants.PARM_NODE_LABEL);
    long txNo = EventUtils.getLongParm(event, EventConstants.PARM_TRANSACTION_NO, -1L);

    LOG.debug("updateServerHandler:  processing updateServer event for: {} on OpenNMS server: {}",
            event.getInterface(), m_localServer);

    Connection dbConn = null;
    List<Event> eventsToSend = null;
    try {
        dbConn = getConnection();
        dbConn.setAutoCommit(false);

        eventsToSend = doUpdateServer(dbConn, nodeLabel, event.getInterface(), action, m_localServer, txNo);
    } catch (SQLException sqlE) {
        LOG.error("SQLException during updateServer on database.", sqlE);
        throw new FailedOperationException("SQLException during updateServer on database.", 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("handleUpdateServer: Exception thrown during commit/rollback: ", ex);
                throw new FailedOperationException("SQLException during updateServer on database.", ex);
            } finally {
                if (dbConn != null) {
                    try {
                        dbConn.close();
                    } catch (SQLException ex) {
                        LOG.error("handleUpdateServer: Exception thrown closing connection: ", ex);
                    }
                }
            }
        }
    }
}

From source file:org.opennms.ng.services.capsd.BroadcastEventProcessor.java

/**
 * Process the event, add or remove a specified service from an interface.
 * An 'action' parameter wraped in the event will tell which action to take
 * to the service./*from   www .j  a v  a 2 s .  c o  m*/
 *
 * @param event The event to process.
 * @throws org.opennms.netmgt.capsd.FailedOperationException         if any.
 * @throws org.opennms.netmgt.capsd.InsufficientInformationException if any.
 */
@EventHandler(uei = EventConstants.CHANGE_SERVICE_EVENT_UEI)
public void handleChangeService(Event event) throws InsufficientInformationException, FailedOperationException {
    EventUtils.checkInterface(event);
    EventUtils.checkService(event);
    EventUtils.requireParm(event, EventConstants.PARM_ACTION);
    if (isXmlRpcEnabled()) {
        EventUtils.requireParm(event, EventConstants.PARM_TRANSACTION_NO);
    }

    String action = EventUtils.getParm(event, EventConstants.PARM_ACTION);
    long txNo = EventUtils.getLongParm(event, EventConstants.PARM_TRANSACTION_NO, -1L);

    LOG.debug("changeServiceHandler:  processing changeService event on: {}", event.getInterface());

    Connection dbConn = null;
    List<Event> eventsToSend = null;
    try {
        dbConn = getConnection();
        dbConn.setAutoCommit(false);

        eventsToSend = doChangeService(dbConn, event.getInterface(), event.getService(), action, txNo);
    } catch (SQLException sqlE) {
        LOG.error("SQLException during changeService on database.", sqlE);
        throw new FailedOperationException("exeption processing changeService: " + 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("handleChangeService: Exception thrown during commit/rollback: ", ex);
                throw new FailedOperationException("exeption processing changeService: " + ex.getMessage(), ex);
            } finally {
                if (dbConn != null) {
                    try {
                        dbConn.close();
                    } catch (SQLException ex) {
                        LOG.error("handleChangeService: Exception thrown closing connection: {}", ex);
                    }
                }
            }
        }
    }
}

From source file:dao.ContactDaoDb.java

/**
 * Given a login return the updated personal info page.
 * @param loginId/*from  w ww. ja va 2 s  .co m*/
 * @param dob
 * @param title
 * @param industry
 * @param company
 * @param pwebsite
 * @param cwebsite
 * @param blogsite
 * @param city
 * @param state
 * @param country
 * @param description
 * @param zipcode
 * @param fname
 * @param lname
 * @param mname
 * @param email
 * @param gender
 * @param nickname
 * @param designation
 * @param bcity
 * @param bstate
 * @param bcountry
 * @param bzipcode
 * @param hphone
 * @param cphone
 * @param bphone
 * @param yim
 * @param aim
 * @param msn
 * @param icq
 * @param fax
 * @param netphone
 * @param relation
 * @param publish
 * @param tags
 * @param alphabet - the first letter of firstname or lastname
 * @throws BaseDaoException If we have a problem interpreting the data or the data is missing or incorrect
 */
public void addContact(String loginId, String dob, String title, String industry, String company,
        String pwebsite, String cwebsite, String blogsite, String city, String state, String country,
        String description, String zipcode, String fname, String lname, String mname, String email,
        String gender, String nickname, String designation, String bcity, String bstate, String bcountry,
        String bzipcode, String hphone, String cphone, String bphone, String yim, String aim, String msn,
        String icq, String fax, String netphone, String relation, String publish, String tags, String alphabet,
        String street, String bstreet) throws BaseDaoException {

    /**
     *  Get scalability datasource for hdcontacts
     */
    String sourceName = scalabilityManager.getWriteZeroScalability();
    ds = scalabilityManager.getSource(sourceName);
    if (ds == null) {
        throw new BaseDaoException("ds null, addContact() " + sourceName);
    }

    boolean canPublish = false;
    if (!RegexStrUtil.isNull(publish)) {
        if (publish.equals("1")) {
            canPublish = true;
        }
    }

    Connection conn = null;
    try {
        conn = ds.getConnection();
        conn.setAutoCommit(false);
        if (canPublish) {
            addQuery.run(conn, fname, lname, mname, dob, title, industry, company, pwebsite, cwebsite, blogsite,
                    city, state, country, description, zipcode, gender, nickname, designation, bcity, bstate,
                    bcountry, bzipcode, hphone, cphone, bphone, yim, aim, msn, icq, loginId, fax, netphone,
                    relation, email, publish, "", street, bstreet);
            addTagQuery.run(conn, "LAST_INSERT_ID()", tags);
        } else {
            addQuery.run(conn, fname, lname, mname, dob, title, industry, company, pwebsite, cwebsite, blogsite,
                    city, state, country, description, zipcode, gender, nickname, designation, bcity, bstate,
                    bcountry, bzipcode, hphone, cphone, bphone, yim, aim, msn, icq, loginId, fax, netphone,
                    relation, email, publish, tags, street, bstreet);
        }
    } catch (Exception e) {
        try {
            conn.rollback();
        } catch (Exception e1) {
            try {
                if (conn != null) {
                    conn.setAutoCommit(true);
                    conn.close();
                }
            } catch (Exception e2) {
                throw new BaseDaoException("connection close exception", e2);
            }
            throw new BaseDaoException("conn.rollback() exception", e1);
        }
        throw new BaseDaoException("exception", e);
    }

    // connection commit
    try {
        conn.commit();
    } catch (Exception e3) {
        throw new BaseDaoException("commit() exception, for add contact loginid = " + loginId, e3);
    }

    try {
        if (conn != null) {
            conn.setAutoCommit(true);
            conn.close();
        }
    } catch (Exception e3) {
        throw new BaseDaoException(
                "setAutocommit()/conn.close() exception, for add contact loginid = " + loginId, e3);
    }

    Fqn fqn = cacheUtil.fqn(DbConstants.CONTACTS);
    if (treeCache.exists(fqn, loginId)) {
        treeCache.remove(fqn, loginId);
    }

    fqn = cacheUtil.fqn(DbConstants.CONTACTS_ALPHABET);
    if (!RegexStrUtil.isNull(alphabet)) {
        StringBuffer sb = new StringBuffer(alphabet);
        sb.append("-");
        sb.append(loginId);
        if (treeCache.exists(fqn, sb.toString())) {
            treeCache.remove(fqn, sb.toString());
        }
    }

    fqn = cacheUtil.fqn(DbConstants.SHARED_PUBLISHED_CONTACTS);
    if (treeCache.exists(fqn, loginId)) {
        treeCache.remove(fqn, loginId);
    }

    fqn = cacheUtil.fqn(DbConstants.PUBLISHED_CONTACTS);
    if (treeCache.exists(fqn, loginId)) {
        treeCache.remove(fqn, loginId);
    }
}

From source file:com.app.das.business.dao.SearchDAO.java

/**
 * ?  ? .//ww w . j  a va 2  s  . c o m
 * @param lendAplnNo   
 * @param commonDO 
 * @throws Exception 
 */
public void deleteTapeLendingAll(String lendAplnNo, DASCommonDO commonDO) throws Exception {
    StringBuffer buf = new StringBuffer();
    buf.append("\n delete from DAS.TAPELENDMST_TBL ");
    buf.append("\n where LEND_APLN_NO = ? ");

    Connection con = null;
    PreparedStatement stmt = null;
    try {
        con = DBService.getInstance().getConnection();
        con.setAutoCommit(false);

        stmt = con.prepareStatement(buf.toString());

        int index = 0;
        stmt.setString(++index, lendAplnNo);

        stmt.executeUpdate();

        //?  ??  .
        deleteTapeLendingItemAll(con, lendAplnNo);

        con.commit();

    }

    catch (Exception e) {
        logger.error(buf.toString());

        if (con != null) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                // TODO ?? ?? catch ?
                e1.printStackTrace();
            }
        }

        throw e;
    } finally {
        release(null, stmt, con);
    }

}

From source file:hoot.services.controllers.wps.MarkItemsReviewedProcesslet.java

@Override
public void process(ProcessletInputs inputParams, ProcessletOutputs outputParams,
        ProcessletExecutionInfo processletExecInfo) throws ProcessletException {
    final String errorMessageStart = "marking items as reviewed";
    Connection conn = DbUtils.createConnection();
    MarkItemsReviewedResponse markItemsReviewedResponse = null;
    try {/*from w w w.j  a v a 2s.com*/
        //Any changes to these default parameters must also be reflected in 
        //$HOOT_HOME/hoot-services/src/main/webapp/WEB-INF/workspace/MarkItemsReviewedProcesslet.xml
        //and vice versa.
        ReviewInputParamsValidator inputParamsValidator = new ReviewInputParamsValidator(inputParams);
        final String mapId = (String) inputParamsValidator.validateAndParseInputParam("mapId", "", null, null,
                false, null);
        final boolean markAll = (Boolean) inputParamsValidator.validateAndParseInputParam("markAll", false,
                null, null, true, false);
        final String reviewedItemsStr = (String) inputParamsValidator
                .validateAndParseInputParam("reviewedItems", "", null, null, true, null);
        ReviewedItems reviewedItems = null;
        if (reviewedItemsStr != null) {
            reviewedItems = (new ObjectMapper()).readValue(reviewedItemsStr, ReviewedItems.class);
        }
        if (!markAll && (reviewedItems == null || reviewedItems.getReviewedItems() == null
                || reviewedItems.getReviewedItems().length == 0)) {
            throw new Exception("Invalid input parameter: markAll set to false and "
                    + "markItemsReviewedRequest.reviewedItems empty.");
        }
        final String reviewedItemsChangesetStr = (String) inputParamsValidator
                .validateAndParseInputParam("reviewedItemsChangeset", "", null, null, true, "");
        MarkItemsReviewedRequest markItemsReviewedRequest = new MarkItemsReviewedRequest();
        markItemsReviewedRequest.setReviewedItems(reviewedItems);
        markItemsReviewedRequest.setReviewedItemsChangeset(reviewedItemsChangesetStr);

        log.debug("Initializing transaction manager...");
        PlatformTransactionManager transactionManager = appContext.getBean("transactionManager",
                PlatformTransactionManager.class);

        log.debug("Initializing database connection...");

        //TODO: verify that no other writes are seen during this transaction

        log.debug("Intializing transaction...");
        TransactionStatus transactionStatus = transactionManager
                .getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED));
        conn.setAutoCommit(false);

        try {
            markItemsReviewedResponse = (new ReviewItemsMarker(conn, mapId))
                    .markItemsReviewed(markItemsReviewedRequest, markAll);
        } catch (Exception e) {
            log.debug("Rolling back database transaction for MarkItemsReviewedProcesslet...");
            transactionManager.rollback(transactionStatus);
            conn.rollback();
            throw e;
        }

        log.debug("Committing MarkItemsReviewedProcesslet database transaction...");
        transactionManager.commit(transactionStatus);
        conn.commit();

        if (StringUtils.trimToNull(markItemsReviewedResponse.getChangesetUploadResponse()) != null) {
            log.debug("Returning changeset upload response: "
                    + StringUtils.abbreviate(markItemsReviewedResponse.getChangesetUploadResponse(), 100)
                    + " ...");
        } else {
            log.debug("Returning null changeset upload response...");
        }
        ((LiteralOutput) outputParams.getParameter("changesetUploadResponse"))
                .setValue(markItemsReviewedResponse.getChangesetUploadResponse());
        log.debug("Returning number of items marked as reviewed: "
                + markItemsReviewedResponse.getNumItemsMarkedReviewed() + " ...");
        ((LiteralOutput) outputParams.getParameter("numItemsMarkedReviewed"))
                .setValue(String.valueOf(markItemsReviewedResponse.getNumItemsMarkedReviewed()));
        log.debug("Returning changeset ID: " + markItemsReviewedResponse.getChangesetId() + " ...");
        ((LiteralOutput) outputParams.getParameter("changesetId"))
                .setValue(String.valueOf(markItemsReviewedResponse.getChangesetId()));
    } catch (Exception e) {
        try {
            ReviewUtils.handleError(e, errorMessageStart, true);
        } catch (Exception e2) {
            throw (ProcessletException) e2;
        }
    } finally {
        try {
            conn.setAutoCommit(true);
            DbUtils.closeConnection(conn);
        } catch (Exception e) {
            try {
                ReviewUtils.handleError(e, errorMessageStart, true);
            } catch (Exception e2) {
                throw (ProcessletException) e2;
            }
        }
    }
}

From source file:org.ulyssis.ipp.processor.Processor.java

private void processEvent(Event event) {
    logProcessEvent(event);//from  w w  w  .  j  a  v  a 2 s . c  om
    Connection connection = null;
    Snapshot oldSnapshot = this.snapshot;
    try {
        connection = Database.createConnection(EnumSet.of(READ_WRITE));
        Event firstEvent = event;
        if (event.isUnique()) {
            Optional<Event> other = Event.loadUnique(connection, event.getClass());
            if (other.isPresent()) {
                other.get().setRemoved(connection, true);
                if (!other.get().getTime().isAfter(event.getTime())) {
                    firstEvent = other.get();
                }
            }
        }
        event.save(connection);
        Snapshot snapshotToUpdateFrom = this.snapshot;
        if (!firstEvent.getTime().isAfter(this.snapshot.getSnapshotTime())) {
            LOG.debug("Event before current snapshot, loading snapshot before");
            Optional<Snapshot> s = Snapshot.loadBefore(connection, firstEvent.getTime());
            if (s.isPresent())
                snapshotToUpdateFrom = s.get();
            else
                snapshotToUpdateFrom = new Snapshot(Instant.EPOCH);
        }
        List<Event> events;
        Snapshot.deleteAfter(connection, snapshotToUpdateFrom);
        LOG.debug("Updating from snapshot: {}", snapshotToUpdateFrom.getId());
        if (snapshotToUpdateFrom.getId().isPresent()) {
            assert snapshotToUpdateFrom.getEventId().isPresent();
            events = Event.loadAfter(connection, snapshotToUpdateFrom.getSnapshotTime(),
                    snapshotToUpdateFrom.getEventId().get());
        } else {
            events = Event.loadAll(connection);
        }
        for (Event e : events) {
            if (!e.isRemoved()) {
                snapshotToUpdateFrom = e.apply(snapshotToUpdateFrom);
                snapshotToUpdateFrom.save(connection);
            }
        }
        LOG.debug("Updated up to snapshot: {}", snapshotToUpdateFrom.getId().get());
        this.snapshot = snapshotToUpdateFrom;
        connection.commit();
        // TODO: Provide a sensible message for NEW_SNAPSHOT?
        statusReporter.broadcast(new StatusMessage(StatusMessage.MessageType.NEW_SNAPSHOT, "New snapshot!"));
        if (eventCallbacks.containsKey(event)) {
            eventCallbacks.get(event).accept(true);
            eventCallbacks.remove(event);
        }
    } catch (SQLException | IOException e) {
        LOG.error("Error when handling event!", e);
        this.snapshot = oldSnapshot;
        try {
            if (connection != null)
                connection.rollback();
        } catch (SQLException e2) {
            LOG.error("Error in rollback after previous error!", e2);
        }
        // TODO(Roel): Reschedule event!
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                LOG.error("Error while closing connection", e);
            }
        }
    }
}

From source file:jade.domain.DFDBKB.java

/**
 *  Delete the DFD object corresponding to the indicated agent name.
 *//*w  w w  . j  a v  a  2 s. com*/
private void remove(String aid) throws SQLException {
    ResultSet rs = null;
    Connection conn = getConnectionWrapper().getConnection();

    try {
        PreparedStatements pss = getPreparedStatements();
        // get description ID
        pss.stm_selDescrId.setString(1, aid);
        rs = pss.stm_selDescrId.executeQuery();

        if (rs.next()) {
            String descrId = rs.getString("id");
            closeResultSet(rs);

            // ontologies
            pss.stm_delOntology.setString(1, descrId);
            pss.stm_delOntology.execute();

            // protocols
            pss.stm_delProtocol.setString(1, descrId);
            pss.stm_delProtocol.execute();

            // languages
            pss.stm_delLanguage.setString(1, descrId);
            pss.stm_delLanguage.execute();

            // services
            removeServices(descrId);

            // agent description
            pss.stm_delAgentDescr.setString(1, descrId);
            pss.stm_delAgentDescr.execute();

            // AID
            removeAID(aid);
            conn.commit();

        } else {
            if (logger.isLoggable(Logger.FINE))
                logger.log(Logger.FINE, "No DF description found to remove for agent '" + aid + "'");
        }
    } catch (SQLException sqle) {
        try {
            conn.rollback();
        } catch (SQLException se) {
            logger.log(Logger.SEVERE, "Rollback for incomplete remotion of DFD for agent " + aid + " failed.",
                    se);
        }
        throw sqle;
    } finally {
        closeResultSet(rs);
    }
}

From source file:com.flexive.ejb.beans.BriefcaseEngineBean.java

/**
 * {@inheritDoc}/*from ww  w .  j  a v  a  2s. c o m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public long create(String name, String description, Long aclId, LifeCycleInfo forcedLifeCycleInfo)
        throws FxApplicationException {
    final UserTicket ticket = FxContext.getUserTicket();

    if (description == null) {
        description = "";
    }
    if (name == null || name.trim().length() == 0) {
        throw new FxInvalidParameterException("ex.briefcase.nameMissing", "name");
    }
    if (aclId != null && aclId != -1) {
        ACL acl;
        try {
            acl = new ACLEngineBean().load(aclId);
        } catch (Throwable t) {
            throw new FxInvalidParameterException("ex.briefcase.invalidAcl", "acl");
        }
        if (!ticket.mayCreateACL(aclId, ticket.getUserId())) {
            throw new FxNoAccessException("ex.briefcase.noCreatePermission", acl.getLabel());
        }

    }
    if (forcedLifeCycleInfo != null && !ticket.isGlobalSupervisor()) {
        throw new FxNoAccessException("ex.briefcase.lciPermission");
    }
    Connection con = null;
    PreparedStatement ps = null;
    String sql;
    String sourceQuery = "";

    try {
        // Obtain a database connection
        con = Database.getDbConnection();

        // Obtain a new id
        long newId = seq.getId(FxSystemSequencer.BRIEFCASE);

        sql = "INSERT INTO " + DatabaseConst.TBL_BRIEFCASE + "(" + //1,   2,  3        ,  4         , 5 ,    6        7         8              9      , 10     , 11
                "ID,NAME,DESCRIPTION,SOURCE_QUERY,ACL,CREATED_BY,CREATED_AT,MODIFIED_BY,MODIFIED_AT,MANDATOR,ICON_ID)"
                + "VALUES (?,?,?,?,?,?,?,?,?,?,1)";
        final long NOW = System.currentTimeMillis();
        ps = con.prepareStatement(sql);
        ps.setLong(1, newId);
        ps.setString(2, name);
        ps.setString(3, description);
        ps.setString(4, sourceQuery);
        if (aclId != null && aclId != -1) {
            ps.setLong(5, aclId);
        } else {
            ps.setNull(5, java.sql.Types.NUMERIC);
        }
        if (forcedLifeCycleInfo != null) {
            ps.setLong(6, forcedLifeCycleInfo.getCreatorId());
            ps.setLong(7, forcedLifeCycleInfo.getCreationTime());
            ps.setLong(8, forcedLifeCycleInfo.getModificatorId());
            ps.setLong(9, forcedLifeCycleInfo.getModificationTime());
        } else {
            ps.setLong(6, ticket.getUserId());
            ps.setLong(7, NOW);
            ps.setLong(8, ticket.getUserId());
            ps.setLong(9, NOW);
        }
        ps.setLong(10, ticket.getMandatorId());
        ps.executeUpdate();
        return newId;
    } catch (SQLException exc) {
        final boolean uniqueConstraintViolation = StorageManager.isUniqueConstraintViolation(exc);
        if (ctx != null) {
            EJBUtils.rollback(ctx);
        } else {
            try {
                if (con != null)
                    con.rollback();
            } catch (SQLException e) {
                LOG.warn(e.getMessage(), e);
            }
        }
        if (uniqueConstraintViolation) {
            throw new FxEntryExistsException(LOG, "ex.briefcase.nameAlreadyExists", name);
        } else {
            throw new FxCreateException(LOG, exc, "ex.briefcase.createFailed");
        }
    } finally {
        closeObjects(BriefcaseEngineBean.class, con, ps);
    }
}