Example usage for javax.ejb TransactionAttributeType REQUIRED

List of usage examples for javax.ejb TransactionAttributeType REQUIRED

Introduction

In this page you can find the example usage for javax.ejb TransactionAttributeType REQUIRED.

Prototype

TransactionAttributeType REQUIRED

To view the source code for javax.ejb TransactionAttributeType REQUIRED.

Click Source Link

Document

If a client invokes the enterprise bean's method while the client is associated with a transaction context, the container invokes the enterprise bean's method in the client's transaction context.

Usage

From source file:com.flexive.ejb.beans.search.ResultPreferencesEngineBean.java

/** {@inheritDoc} */
@Override/*from w  w  w. j a va 2s .  c  o m*/
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public boolean isCustomized(long typeId, ResultViewType viewType, ResultLocation location)
        throws FxApplicationException {
    try {
        configuration.get(SystemParameters.USER_RESULT_PREFERENCES, getKey(typeId, viewType, location));
        return true;
    } catch (FxNotFoundException e) {
        return false;
    }
}

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

/**
 * {@inheritDoc}//w ww .j av a2s . c  o  m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void logout() throws FxLogoutFailedException {
    LoginLogoutHandler.doLogout();
}

From source file:com.flexive.ejb.beans.workflow.WorkflowEngineBean.java

/**
 * {@inheritDoc}//from   w w  w.j  a v  a 2  s.com
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void update(Workflow workflow) throws FxApplicationException {

    UserTicket ticket = FxContext.getUserTicket();

    // Permission checks
    FxPermissionUtils.checkRole(ticket, Role.WorkflowManagement);

    Workflow org = CacheAdmin.getEnvironment().getWorkflow(workflow.getId()).asEditable();

    List<Step> dups = new ArrayList<Step>(2); //duplicates (removed and re-added)
    for (Step check : workflow.getSteps()) {
        for (Step stp : org.getSteps())
            if (check.getId() < 0 && stp.getStepDefinitionId() == check.getStepDefinitionId())
                dups.add(check);
    }
    if (dups.size() > 0) {
        //sync steps
        workflow.getSteps().removeAll(dups);
        for (Step stp : org.getSteps())
            for (Step dp : dups)
                if (dp.getStepDefinitionId() == stp.getStepDefinitionId()) {
                    workflow.getSteps().add(stp);
                    break;
                }
        //sync routes
        boolean changes = true;
        while (changes) {
            changes = false;
            for (Route r : workflow.getRoutes()) {
                for (Step s : dups) {
                    if (r.getFromStepId() == s.getId()) {
                        long _from = r.getFromStepId();
                        for (Step stp : org.getSteps())
                            if (stp.getStepDefinitionId() == s.getStepDefinitionId()) {
                                _from = stp.getId();
                                break;
                            }
                        Route nr = new Route(r.getId(), r.getGroupId(), _from, r.getToStepId());
                        if (!workflow.getRoutes().contains(nr)) {
                            workflow.getRoutes().remove(r);
                            workflow.getRoutes().add(nr);
                            changes = true;
                        }
                        break;
                    } else if (r.getToStepId() == s.getId()) {
                        long _to = r.getToStepId();
                        for (Step stp : org.getSteps())
                            if (stp.getStepDefinitionId() == s.getStepDefinitionId()) {
                                _to = stp.getId();
                                break;
                            }
                        Route nr = new Route(r.getId(), r.getGroupId(), r.getFromStepId(), _to);
                        if (!workflow.getRoutes().contains(nr)) {
                            workflow.getRoutes().remove(r);
                            workflow.getRoutes().add(nr);
                            changes = true;
                        }
                        break;
                    }
                    if (changes)
                        break;
                }
                if (changes)
                    break;
            }
        }
    }
    Connection con = null;
    PreparedStatement stmt = null;
    String sql = "UPDATE " + TBL_WORKFLOW + " SET NAME=?, DESCRIPTION=? WHERE ID=?";

    boolean success = false;
    try {
        // Sanity checks
        checkIfValid(workflow);

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

        // Update the workflow instance
        stmt = con.prepareStatement(sql);
        stmt.setString(1, workflow.getName());
        stmt.setString(2, StringUtils.defaultString(workflow.getDescription()));
        stmt.setLong(3, workflow.getId());

        stmt.executeUpdate();

        FxEnvironment fxEnvironment = CacheAdmin.getEnvironment();
        // Remove steps?
        List<Step> remove = new ArrayList<Step>(2);
        for (Step step : fxEnvironment.getStepsByWorkflow(workflow.getId())) {
            if (!workflow.getSteps().contains(step)) {
                // remove step
                remove.add(step);
            }
        }

        if (remove.size() > 0) {
            int tries = remove.size() * 2;
            List<Step> tmpRemove = new ArrayList<Step>(remove.size());
            while (remove.size() > 0 && --tries > 0) {
                for (Step step : remove) {
                    try {
                        //remove affected routes as well
                        for (Route route : org.getRoutes())
                            if (route.getFromStepId() == step.getId() || route.getToStepId() == step.getId())
                                routeEngine.remove(route.getId());

                        stepEngine.removeStep(step.getId());
                        tmpRemove.add(step);
                    } catch (FxApplicationException e) {
                        //ignore since rmeove order matters
                    }
                }
                remove.removeAll(tmpRemove);
            }
        }

        // Add/update steps, if necessary
        Map<Long, Step> createdSteps = new HashMap<Long, Step>();
        int index = 1;
        for (Step step : workflow.getSteps()) {
            if (step.getId() < 0) {
                long newStepId = stepEngine.createStep(step);
                // set position
                stepEngine.updateStep(newStepId, step.getAclId(), index);
                // map created steps using the old ID - if routes reference them
                createdSteps.put(step.getId(), new Step(newStepId, step));
            } else {
                // update ACL and position
                stepEngine.updateStep(step.getId(), step.getAclId(), index);
            }
            index++;
        }

        // Remove routes?
        boolean found;
        for (Route route : org.getRoutes()) {
            found = false;
            for (Route check : workflow.getRoutes()) {
                if (check.getGroupId() == route.getGroupId() && check.getFromStepId() == route.getFromStepId()
                        && check.getToStepId() == route.getToStepId()) {
                    workflow.getRoutes().remove(check); //dont add this one again
                    found = true;
                    break;
                }
            }
            // remove route if not found
            if (!found)
                routeEngine.remove(route.getId());
        }

        // add routes
        for (Route route : workflow.getRoutes()) {
            if (route.getId() < 0) {
                long fromStepId = resolveTemporaryStep(createdSteps, route.getFromStepId());
                long toStepId = resolveTemporaryStep(createdSteps, route.getToStepId());
                routeEngine.create(fromStepId, toStepId, route.getGroupId());
            }
        }

        success = true;
    } catch (SQLException exc) {
        if (StorageManager.isUniqueConstraintViolation(exc)) {
            throw new FxEntryExistsException("ex.workflow.exists");
        } else {
            throw new FxUpdateException(LOG, exc, "ex.workflow.update", workflow.getName(), exc.getMessage());
        }
    } catch (Exception exc) {
        throw new FxUpdateException(LOG, exc, "ex.workflow.update", workflow.getName(), exc.getMessage());
    } finally {
        Database.closeObjects(WorkflowEngineBean.class, con, stmt);
        if (!success) {
            EJBUtils.rollback(ctx);
        } else {
            StructureLoader.reloadWorkflows(FxContext.get().getDivisionId());
        }
    }
}

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

/**
 * {@inheritDoc}//  w w  w. jav a  2  s.  c om
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void assignMetaData(int mandatorId, long contentId) throws FxApplicationException {
    final UserTicket ticket = FxContext.getUserTicket();
    final FxEnvironment environment;
    // Security
    FxPermissionUtils.checkRole(ticket, Role.GlobalSupervisor);
    environment = CacheAdmin.getEnvironment();
    // check existance
    Mandator mand = environment.getMandator(mandatorId);
    EJBLookup.getContentEngine().load(new FxPK(contentId)); // throws exception if content doesn't exist
    Connection con = null;
    PreparedStatement ps = null;
    String sql;

    try {
        // get Database connection
        con = Database.getDbConnection(); //1             //2            //3        //4
        sql = "UPDATE " + TBL_MANDATORS + " SET METADATA=?, MODIFIED_BY=?, MODIFIED_AT=? WHERE ID=?";
        final long NOW = System.currentTimeMillis();
        ps = con.prepareStatement(sql);
        ps.setLong(1, contentId);
        ps.setLong(2, ticket.getUserId());
        ps.setLong(3, NOW);
        ps.setLong(4, mandatorId);
        ps.executeUpdate();
        StructureLoader.updateMandator(FxContext.get().getDivisionId(),
                new Mandator(mand.getId(), mand.getName(), contentId, true,
                        new LifeCycleInfoImpl(mand.getLifeCycleInfo().getCreatorId(),
                                mand.getLifeCycleInfo().getCreationTime(), ticket.getUserId(), NOW)));
    } catch (SQLException e) {
        EJBUtils.rollback(ctx);
        throw new FxUpdateException(LOG, e, "ex.mandator.assignMetaDataFailed", contentId, mand.getName(),
                mand.getId(), e.getMessage());
    } finally {
        Database.closeObjects(MandatorEngineBean.class, con, ps);
    }
}

From source file:be.fedict.eid.pkira.blm.model.usermgmt.RegistrationManagerBean.java

/**
 * {@inheritDoc}//  w w  w .j av  a  2 s  .  c o  m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public List<Registration> findRegistrationForUserDNAndCertificateType(String userIdentification, String dn,
        List<String> alternativeNames, CertificateType certificateType) throws BlacklistedException {
    // Parse the DNs
    List<DistinguishedName> theDNs = parseDNs(dn, alternativeNames);
    if (theDNs.size() == 0) {
        return Collections.emptyList();
    }

    // Get all registrations for the user
    List<Registration> allRegistrations = findApprovedRegistrationsByUser(userIdentification);

    // Filter the registrations
    List<Registration> validRegistrations = new ArrayList<Registration>();
    boolean blacklisted = false;
    nextRegistration: for (Registration registration : allRegistrations) {
        CertificateDomain certificateDomain = registration.getCertificateDomain();

        // Check certificate types
        if (certificateType != null && !certificateDomain.getCertificateTypes().contains(certificateType)) {
            continue;
        }

        // Check DNs
        DistinguishedNameExpression dnExpression = parseDNExpression(certificateDomain.getDnExpression());
        if (dnExpression == null) {
            continue;
        }
        for (DistinguishedName theDN : theDNs) {
            if (!dnExpression.matches(theDN)) {
                continue nextRegistration;
            }
        }

        // Check blacklist
        if (!checkBlacklist(theDNs, registration)) {
            blacklisted = true;
            continue;
        }

        // All ok
        validRegistrations.add(registration);
    }

    if (blacklisted)
        throw new BlacklistedException();

    // Return the result
    return validRegistrations;
}

From source file:com.flexive.ejb.beans.structure.AssignmentEngineBean.java

/**
 * {@inheritDoc}/* w  w w.ja  v a 2  s  .  co  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public long createProperty(long typeId, FxPropertyEdit property, String parentXPath)
        throws FxApplicationException {
    return createProperty(typeId, property, parentXPath, property.getName());
}

From source file:com.flexive.ejb.beans.workflow.StepDefinitionEngineBean.java

/**
 * {@inheritDoc}// w w w. j  a va2  s .co m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public long create(StepDefinition stepDefinition) throws FxApplicationException {

    final UserTicket ticket = FxContext.getUserTicket();
    // Security checks
    FxPermissionUtils.checkRole(ticket, Role.WorkflowManagement);
    // Create the new step
    Connection con = null;
    PreparedStatement ps = null;
    String sql;
    FxString label = stepDefinition.getLabel();
    if (StringUtils.isEmpty(stepDefinition.getName()))
        throw new FxInvalidParameterException("NAME", "ex.stepdefinition.name.empty");
    if (label.isEmpty())
        throw new FxInvalidParameterException("LABEL", "ex.stepdefinition.label.empty");
    String name = stepDefinition.getName();
    long uniqueTargetId = stepDefinition.getUniqueTargetId();
    boolean success = false;
    long newId = -1;
    try {
        // Check the unique target
        checkValidUniqueTarget(-1, uniqueTargetId);

        if (StringUtils.isBlank(label.getDefaultTranslation())) {
            FxInvalidParameterException ip = new FxInvalidParameterException("NAME",
                    "ex.stepdefinition.name.empty");
            if (LOG.isDebugEnabled())
                LOG.debug(ip);
            throw ip;
        }

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

        // Create the new workflow instance
        sql = "INSERT INTO " + TBL_WORKFLOW_STEPDEFINITION + " (ID,NAME,UNIQUE_TARGET) VALUES (?,?,?)";
        ps = con.prepareStatement(sql);
        newId = seq.getId(FxSystemSequencer.STEPDEFINITION);
        ps.setLong(1, newId);
        ps.setString(2, name);
        if (uniqueTargetId != -1) {
            ps.setLong(3, uniqueTargetId);
        } else {
            ps.setNull(3, Types.NUMERIC);
        }
        if (ps.executeUpdate() != 1)
            throw new FxCreateException(LOG, "ex.stepdefinition.create");
        Database.storeFxString(label, con, TBL_WORKFLOW_STEPDEFINITION, "name", "id", newId);
        success = true;
    } catch (FxInvalidParameterException exc) {
        throw exc;
    } catch (Exception exc) {
        if (StorageManager.isUniqueConstraintViolation(exc)) {
            FxEntryExistsException ee = new FxEntryExistsException("ex.stepdefinition.name.exists", name);
            if (LOG.isDebugEnabled())
                LOG.debug(ee);
            throw ee;
        } else {
            FxCreateException ce = new FxCreateException(LOG, "ex.stepdefinition.create", exc);
            LOG.error("Internal error: " + exc.getMessage(), ce);
            throw ce;
        }
    } finally {
        Database.closeObjects(StepDefinitionEngineBean.class, con, ps);
        if (!success) {
            EJBUtils.rollback(ctx);
        } else {
            StructureLoader.reloadWorkflows(FxContext.get().getDivisionId());
        }
    }
    return newId;
}

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

/**
 * {@inheritDoc}//  ww  w  .  j a v  a  2 s  . co m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public boolean loginCheck(String username, String password, UserTicket currentTicket)
        throws FxLoginFailedException, FxDbException {
    DataSource ds;
    boolean checkOK;
    try {
        ds = Database.getDataSource();
        checkOK = FxDBAuthentication.checkLogin(username, password, currentTicket, ds);
    } catch (Exception exc) {
        throw new FxLoginFailedException(exc.getMessage(), FxLoginFailedException.TYPE_SQL_ERROR);
    }
    return checkOK;
}

From source file:org.cesecore.audit.impl.integrityprotected.IntegrityProtectedAuditorSessionBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public int deleteRows(final AuthenticationToken token, final Date timestamp, final Properties properties) {
    final Map<String, Object> detailsDelete = new LinkedHashMap<String, Object>();
    detailsDelete.put("timestamp", FastDateFormat
            .getInstance(ValidityDate.ISO8601_DATE_FORMAT, TimeZone.getTimeZone("GMT")).format(timestamp));
    securityEventsLogger.log(EventTypes.LOG_DELETE, EventStatus.VOID, ModuleTypes.SECURITY_AUDIT,
            ServiceTypes.CORE, token.toString(), null, null, null, detailsDelete);
    // Delete all the exported logs (from all nodes)
    final QueryCriteria queryCriteria = QueryCriteria.create()
            .add(Criteria.leq(AuditLogEntry.FIELD_TIMESTAMP, timestamp.getTime()))
            .add(Criteria.orderAsc(AuditLogEntry.FIELD_SEQUENCENUMBER));
    return buildConditionalQuery(entityManager, "DELETE FROM AuditRecordData a", queryCriteria, 0, 0)
            .executeUpdate();/*from   w  w w.  j  a va  2s  .co  m*/
}

From source file:com.flexive.ejb.beans.search.SearchEngineBean.java

/**
 * {@inheritDoc}/*from  w  w w. j a  v a2s . c o  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Collection<String> loadNames(ResultLocation location) throws FxApplicationException {
    final List<String> names = Lists.newArrayList(configuration.getKeys(getConfigurationParameter(location)));
    // remove default query from list
    final Iterator<String> iter = names.iterator();
    while (iter.hasNext()) {
        if (iter.next().equals(DEFAULT_QUERY_NAME)) {
            iter.remove();
        }
    }

    return names;
}