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.PhraseEngineBean.java

/**
 * {@inheritDoc}// ww  w  .  jav  a  2 s. c  o m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public int removeMandatorPhrases(FxPhraseCategorySelection categories, long mandator)
        throws FxNoAccessException, FxEntryInUseException {
    Connection con = null;
    PreparedStatement ps = null;
    final UserTicket userTicket = FxContext.getUserTicket();
    checkMandatorAccess(mandator, userTicket);
    int count = 0;
    try {
        // Obtain a database connection
        con = Database.getDbConnection();
        if (categories.isAny()) {
            ps = con.prepareStatement("SELECT COUNT(ID) FROM " + TBL_PHRASE_TREE + " WHERE PMANDATOR=?");
            ps.setLong(1, mandator);
        } else {
            ps = con.prepareStatement("SELECT COUNT(ID) FROM " + TBL_PHRASE_TREE
                    + " WHERE PMANDATOR=? AND CAT IN(" + categoriesList(categories) + ")");
            ps.setLong(1, mandator);
        }
        ResultSet rsCheck = ps.executeQuery();
        if (rsCheck != null && rsCheck.next()) {
            long used = rsCheck.getLong(1);
            if (used > 0)
                throw new FxEntryInUseException("ex.phrase.inUse.tree.count", used);
        }
        if (rsCheck != null)
            rsCheck.close();
        ps.close();
        if (categories.isAny()) {
            ps = con.prepareStatement("DELETE FROM " + TBL_PHRASE_VALUES + " WHERE MANDATOR=?");
            ps.setLong(1, mandator);
            ps.execute();
            ps.close();
            ps = con.prepareStatement("DELETE FROM " + TBL_PHRASE_MAP + " WHERE PMANDATOR=?");
            ps.setLong(1, mandator);
            ps.execute();
            ps.close();
            ps = con.prepareStatement("DELETE FROM " + TBL_PHRASE + " WHERE MANDATOR=?");
            ps.setLong(1, mandator);
            count = ps.executeUpdate();
        } else {
            ps = con.prepareStatement(
                    "DELETE FROM " + TBL_PHRASE_VALUES + " WHERE MANDATOR=? AND ID IN(SELECT DISTINCT ID FROM "
                            + TBL_PHRASE + " WHERE MANDATOR=? AND CAT IN(" + categoriesList(categories) + "))");
            ps.setLong(1, mandator);
            ps.setLong(2, mandator);
            ps.execute();
            ps.close();
            ps = con.prepareStatement("DELETE FROM " + TBL_PHRASE_MAP
                    + " WHERE PMANDATOR=? AND PHRASEID IN(SELECT DISTINCT ID FROM " + TBL_PHRASE
                    + " WHERE MANDATOR=? AND CAT IN(" + categoriesList(categories) + "))");
            ps.setLong(1, mandator);
            ps.execute();
            ps.close();
            ps = con.prepareStatement("DELETE FROM " + TBL_PHRASE + " WHERE MANDATOR=? AND CAT IN("
                    + categoriesList(categories) + ")");
            ps.setLong(1, mandator);
            count = ps.executeUpdate();
        }
        removePhraseSequencer(mandator); //force a re-initialization on next use/call
    } catch (SQLException exc) {
        EJBUtils.rollback(ctx);
        throw new FxDbException(LOG, exc, "ex.db.sqlError", exc.getMessage()).asRuntimeException();
    } finally {
        Database.closeObjects(PhraseEngineBean.class, con, ps);
    }
    return count;
}

From source file:gov.nih.nci.caarray.application.project.ProjectManagementServiceBean.java

/**
 * {@inheritDoc}//w  w w . j  av a 2s. co m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void changeOwner(Long projectId, String newOwner) throws CSException {
    final Project project = this.searchDao.retrieve(Project.class, projectId);
    final AuthorizationManager am = SecurityUtils.getAuthorizationManager();
    final User newOwnerUser = am.getUser(newOwner);
    SecurityUtils.changeOwner(project, newOwnerUser);
}

From source file:org.ejbca.core.ejb.ca.store.CertificateStoreSessionBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRED)
@Override/*w w w .  j a va2s. c  o m*/
public void revokeCertificate(Admin admin, Certificate cert, Collection<Integer> publishers, int reason,
        String userDataDN) {
    if (cert instanceof X509Certificate) {
        setRevokeStatus(admin, CertTools.getIssuerDN(cert), CertTools.getSerialNumber(cert), publishers, reason,
                userDataDN);
    }
}

From source file:com.flexive.ejb.beans.configuration.DivisionConfigurationEngineBean.java

/**
 * {@inheritDoc}/*from   ww w.j  a  v  a 2  s  .c  o m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void removeResourceValues(String keyPrefix) throws FxApplicationException {
    if (StringUtils.isBlank(keyPrefix))
        return;
    keyPrefix = keyPrefix.trim();
    if (keyPrefix.length() > 250)
        throw new FxApplicationException("ex.configuration.resource.key.tooLong", keyPrefix);
    if (!StringUtils.isAsciiPrintable(keyPrefix))
        throw new FxApplicationException("ex.configuration.resource.key.nonAscii", keyPrefix);
    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = Database.getDbConnection();
        ps = con.prepareStatement("DELETE FROM " + TBL_RESOURCES + " WHERE RKEY LIKE ?");
        ps.setString(1, keyPrefix + "%");
        ps.executeUpdate();
    } catch (SQLException e) {
        throw new FxApplicationException(e, "ex.db.sqlError", e.getMessage());
    } finally {
        Database.closeObjects(DivisionConfigurationEngine.class, con, ps);
    }
}

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

/**
 * {@inheritDoc}//from  w  w  w  .  j  av a 2s  . com
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void remove(FxPK pk) throws FxApplicationException {
    Connection con = null;
    PreparedStatement ps = null;
    try {
        ContentStorage storage = StorageManager.getContentStorage(pk.getStorageMode());
        con = Database.getDbConnection();
        final FxEnvironment env = CacheAdmin.getEnvironment();
        //security check start
        if (!(FxContext.get().getRunAsSystem() || FxContext.getUserTicket().isGlobalSupervisor())) {
            FxContentVersionInfo cvi = storage.getContentVersionInfo(con, pk.getId());
            FxPK currPK;
            for (int currVer : cvi.getVersions()) {
                currPK = new FxPK(pk.getId(), currVer);
                FxContentSecurityInfo si = storage.getContentSecurityInfo(con, currPK, null);
                FxPermissionUtils.checkPermission(FxContext.getUserTicket(), ACLPermission.DELETE, si, true);
            }
        }
        //security check end
        FxScriptBinding binding = null;
        long[] scripts;
        FxContentSecurityInfo securityInfo = storage.getContentSecurityInfo(con, pk, null);
        try {
            FxPermissionUtils.checkMandatorExistance(securityInfo.getMandatorId());
            FxPermissionUtils.checkTypeAvailable(securityInfo.getTypeId(), false);
        } catch (FxNotFoundException e) {
            throw new FxRemoveException(e);
        }
        long typeId = securityInfo.getTypeId();
        FxType type = env.getType(typeId);

        //scripting before start
        //type scripting
        scripts = type.getScriptMapping(FxScriptEvent.BeforeContentRemove);
        if (scripts != null)
            for (long script : scripts) {
                if (binding == null)
                    binding = new FxScriptBinding();
                binding.setVariable("pk", pk);
                if (!binding.getProperties().containsKey("securityInfo"))
                    binding.setVariable("securityInfo", securityInfo);
                scripting.runScript(script, binding);
            }
        //assignment scripting
        if (type.hasScriptedAssignments()) {
            binding = new FxScriptBinding();
            binding.setVariable("pk", pk);
            for (FxAssignment as : type.getScriptedAssignments(FxScriptEvent.BeforeAssignmentDataDelete)) {
                binding.setVariable("assignment", as);
                for (long script : as.getScriptMapping(FxScriptEvent.BeforeAssignmentDataDelete)) {
                    scripting.runScript(script, binding);
                }
            }
        }
        //scripting before end
        storage.contentRemove(con, type, pk);
        //scripting after start
        //assignment scripting
        if (type.hasScriptedAssignments()) {
            binding = new FxScriptBinding();
            binding.setVariable("pk", pk);
            for (FxAssignment as : type.getScriptedAssignments(FxScriptEvent.AfterAssignmentDataDelete)) {
                binding.setVariable("assignment", as);
                for (long script : as.getScriptMapping(FxScriptEvent.AfterAssignmentDataDelete)) {
                    scripting.runScript(script, binding);
                }
            }
        }
        //type scripting
        scripts = type.getScriptMapping(FxScriptEvent.AfterContentRemove);
        if (scripts != null)
            for (long script : scripts) {
                if (binding == null)
                    binding = new FxScriptBinding();
                binding.setVariable("pk", pk);
                if (!binding.getProperties().containsKey("securityInfo"))
                    binding.setVariable("securityInfo", securityInfo);
                scripting.runScript(script, binding);
            }
        //scripting after end
    } catch (FxRemoveException e) {
        EJBUtils.rollback(ctx);
        throw e;
    } catch (FxNotFoundException e) {
        //not found is ok for removed instances
    } catch (SQLException e) {
        EJBUtils.rollback(ctx);
        throw new FxRemoveException(LOG, e, "ex.db.sqlError", e.getMessage());
    } finally {
        Database.closeObjects(ContentEngineBean.class, con, ps);
        if (!ctx.getRollbackOnly())
            CacheAdmin.expireCachedContent(pk.getId());
    }
}

From source file:org.ejbca.core.ejb.ca.store.CertificateStoreSessionBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRED)
@Override//w w w.  j  ava 2  s  . c  o m
// TODO: Does not publish revocations to publishers!!!
// TODO: Enforce or drop Admin parameter
public void revokeAllCertByCA(Admin admin, String issuerdn, int reason) {
    int temprevoked = 0;
    int revoked = 0;
    String bcdn = CertTools.stringToBCDNString(issuerdn);
    try {
        // Change all temporaty revoked certificates to permanently revoked certificates
        temprevoked = CertificateData.revokeOnHoldPermanently(entityManager, bcdn);
        // Revoking all non revoked certificates.
        revoked = CertificateData.revokeAllNonRevokedCertificates(entityManager, bcdn, reason);
        String msg = intres.getLocalizedMessage("store.revokedallbyca", issuerdn,
                Integer.valueOf(revoked + temprevoked), Integer.valueOf(reason));
        logSession.log(admin, bcdn.hashCode(), LogConstants.MODULE_CA, new java.util.Date(), null, null,
                LogConstants.EVENT_INFO_REVOKEDCERT, msg);
    } catch (Exception e) {
        String msg = intres.getLocalizedMessage("store.errorrevokeallbyca", issuerdn);
        logSession.log(admin, bcdn.hashCode(), LogConstants.MODULE_CA, new java.util.Date(), null, null,
                LogConstants.EVENT_ERROR_REVOKEDCERT, msg, e);
        throw new EJBException(e);
    }
}

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

/**
 * {@inheritDoc}/*w w w.  j a  va2 s  . c om*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void remove(long accountId) throws FxApplicationException {
    // Handle protected users
    if (accountId == Account.USER_GUEST)
        throw new FxNoAccessException("ex.account.delete.guest");
    if (accountId == Account.USER_GLOBAL_SUPERVISOR)
        throw new FxNoAccessException("ex.account.delete.supervisor");
    if (accountId == Account.NULL_ACCOUNT)
        throw new FxNoAccessException("ex.account.delete.nullAccount");

    Account account = load(accountId);

    // Permission checks
    final UserTicket ticket = FxContext.getUserTicket();
    if (!ticket.isGlobalSupervisor()) {
        if (!ticket.isInRole(Role.MandatorSupervisor))
            FxPermissionUtils.checkRole(ticket, Role.AccountManagement);
        if (account.getMandatorId() != ticket.getMandatorId())
            throw new FxNoAccessException(LOG, "ex.account.delete.wrongMandator");
    }

    Connection con = null;
    Statement stmt = null;
    String curSql = null;
    try {
        con = Database.getDbConnection();
        //Check if contents exist that the account created/modified
        stmt = con.createStatement();
        curSql = "SELECT COUNT(DISTINCT ID) FROM " + TBL_CONTENT + " WHERE CREATED_BY=" + accountId
                + " OR MODIFIED_BY=" + accountId;
        ResultSet rs = stmt.executeQuery(curSql);
        if (rs != null && rs.next()) {
            if (rs.getLong(1) > 1) // 1 contact data record always exists
                throw new FxNoAccessException("ex.account.delete.contentExists");
        }
        stmt.close();

        // also check all other tables with lifecycle information
        for (String tableName : TABLES_WITH_LCI) {
            if (!TBL_CONTENT.equals(tableName)) {
                stmt = con.createStatement();
                rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName + " WHERE CREATED_BY=" + accountId
                        + " OR MODIFIED_BY=" + accountId);
                if (rs.next() && rs.getLong(1) > 0) {
                    // TODO: set to special user account ("deleted user")?
                    LOG.warn("User " + accountId + " references table " + tableName + " (ignored)");
                }
            }
        }

        // Delete all group assignments ..
        stmt = con.createStatement();
        curSql = "DELETE FROM " + TBL_ASSIGN_GROUPS + " WHERE ACCOUNT=" + accountId;
        stmt.executeUpdate(curSql);
        stmt.close();

        // Delete all role assigments ..
        stmt = con.createStatement();
        curSql = "DELETE FROM " + TBL_ROLE_MAPPING + " WHERE ACCOUNT=" + accountId;
        stmt.executeUpdate(curSql);
        stmt.close();

        // TODO: delete user specific configurations
        // TODO: delete user specific locks

        // Finally remove the user itself
        stmt = con.createStatement();
        curSql = "DELETE FROM " + TBL_ACCOUNTS + " WHERE ID=" + accountId;
        stmt.executeUpdate(curSql);

        // Log the user out of the system (if he is active)
        // This is done after the commit, since a failure should not block the user delete action
        UserTicketStore.removeUserId(accountId, null);

        // delete contact data
        try {
            // disable security since the contact data ACL prevents foreign users from deleting
            // CD instances. However, in this case the user has the role AccountManagement
            // which overrules the ACL permissions.
            FxContext.get().runAsSystem();
            co.remove(account.getContactData());
        } finally {
            FxContext.get().stopRunAsSystem();
        }
        EJBLookup.getHistoryTrackerEngine().track("history.account.remove", account.getLoginName());
    } catch (SQLException exc) {
        EJBUtils.rollback(ctx);
        throw new FxRemoveException(LOG, exc, "ex.account.delete.failed.sql", accountId, exc.getMessage(),
                curSql);
    } finally {
        Database.closeObjects(AccountEngineBean.class, con, stmt);
    }
}

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

/**
 * {@inheritDoc}// w ww.  j  ava 2s  . c  o m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public FxScriptMappingEntry createAssignmentScriptMapping(FxScriptEvent scriptEvent, long scriptId,
        long assignmentId, boolean active, boolean derivedUsage) throws FxApplicationException {
    FxPermissionUtils.checkRole(FxContext.getUserTicket(), Role.ScriptManagement);
    FxScriptMappingEntry sm;
    Connection con = null;
    PreparedStatement ps = null;
    String sql;
    boolean success = false;
    //check existance
    CacheAdmin.getEnvironment().getScript(scriptId);
    checkAssignmentScriptConsistency(scriptId, assignmentId, scriptEvent, active, derivedUsage);
    try {
        long[] derived;
        if (!derivedUsage)
            derived = new long[0];
        else {
            List<FxAssignment> ass = CacheAdmin.getEnvironment().getDerivedAssignments(assignmentId);
            derived = new long[ass.size()];
            for (int i = 0; i < ass.size(); i++)
                derived[i] = ass.get(i).getId();
        }
        sm = new FxScriptMappingEntry(scriptEvent, scriptId, active, derivedUsage, assignmentId, derived);
        // Obtain a database connection
        con = Database.getDbConnection();
        sql = "INSERT INTO " + TBL_SCRIPT_MAPPING_ASSIGN
                + " (ASSIGNMENT,SCRIPT,DERIVED_USAGE,ACTIVE,STYPE) VALUES " +
                //1,2,3,4,5
                "(?,?,?,?,?)";
        ps = con.prepareStatement(sql);
        ps.setLong(1, sm.getId());
        ps.setLong(2, sm.getScriptId());
        ps.setBoolean(3, sm.isDerivedUsage());
        ps.setBoolean(4, sm.isActive());
        ps.setLong(5, sm.getScriptEvent().getId());
        ps.executeUpdate();
        success = true;
    } catch (SQLException exc) {
        if (StorageManager.isUniqueConstraintViolation(exc))
            throw new FxEntryExistsException("ex.scripting.mapping.assign.notUnique", scriptId, assignmentId);
        throw new FxCreateException(LOG, exc, "ex.scripting.mapping.assign.create.failed", scriptId,
                assignmentId, exc.getMessage());
    } finally {
        Database.closeObjects(ScriptingEngineBean.class, con, ps);
        if (!success)
            EJBUtils.rollback(ctx);
        else
            StructureLoader.reloadScripting(FxContext.get().getDivisionId());
    }
    return sm;
}

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

/**
 * {@inheritDoc}//from w  w  w .j  a v  a 2 s  .c  om
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void removeItemData(long briefcaseId, Long itemId) throws FxApplicationException {
    Briefcase br = load(briefcaseId); // check read permissions
    Connection con = null;
    PreparedStatement stmt = null;
    try {
        con = Database.getDbConnection();
        // check if the item actually exists
        stmt = con.prepareStatement("DELETE FROM " + TBL_BRIEFCASE_DATA_ITEM + " WHERE briefcase_id=? "
                + (itemId != null ? " AND id=?" : ""));
        stmt.setLong(1, briefcaseId);
        if (itemId != null)
            stmt.setLong(2, itemId);
        stmt.executeUpdate();
    } catch (Exception e) {
        EJBUtils.rollback(ctx);
        if (itemId != null)
            throw new FxRemoveException(LOG, e, "ex.briefcase.removeItemData.id", br.getName(), itemId,
                    e.getMessage());
        else
            throw new FxRemoveException(LOG, e, "ex.briefcase.removeItemData.all", br.getName(),
                    e.getMessage());
    } finally {
        Database.closeObjects(BriefcaseEngineBean.class, con, stmt);
    }
}

From source file:org.cesecore.keys.token.CryptoTokenManagementSessionBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRED)
@Override//from   ww w  . j  a va2  s .  c  o  m
public void createKeyPair(final AuthenticationToken authenticationToken, final int cryptoTokenId,
        final String alias, final String keySpecificationParam) throws AuthorizationDeniedException,
        CryptoTokenOfflineException, InvalidKeyException, InvalidAlgorithmParameterException {
    assertAuthorization(authenticationToken, cryptoTokenId,
            CryptoTokenRules.GENERATE_KEYS.resource() + "/" + cryptoTokenId);
    final CryptoToken cryptoToken = getCryptoTokenAndAssertExistence(cryptoTokenId);
    // Check if alias is already in use
    assertAliasNotInUse(cryptoToken, alias);

    // Support "RSAnnnn" and convert it to the legacy format "nnnn"
    final String keySpecification;
    if (keySpecificationParam.startsWith(AlgorithmConstants.KEYALGORITHM_RSA)) {
        keySpecification = keySpecificationParam.substring(AlgorithmConstants.KEYALGORITHM_RSA.length());
    } else {
        keySpecification = keySpecificationParam;
    }
    // Check if keySpec is valid
    KeyTools.checkValidKeyLength(keySpecification);
    // Audit log before generation. If the token is an HSM the merge will not make a difference.
    final Map<String, Object> details = new LinkedHashMap<String, Object>();
    details.put("msg", "Generated new keypair in CryptoToken " + cryptoTokenId);
    details.put("keyAlias", alias);
    details.put("keySpecification", keySpecification);
    cryptoToken.generateKeyPair(keySpecification, alias);
    cryptoToken.testKeyPair(alias);
    // Merge is important for soft tokens where the data is persisted in the database, but will also update lastUpdate
    try {
        cryptoTokenSession.mergeCryptoToken(cryptoToken);
    } catch (CryptoTokenNameInUseException e) {
        throw new RuntimeException(e); // We have not changed the name of the CrytpoToken here, so this should never happen
    }
    securityEventsLoggerSession.log(EventTypes.CRYPTOTOKEN_GEN_KEYPAIR, EventStatus.SUCCESS,
            ModuleTypes.CRYPTOTOKEN, ServiceTypes.CORE, authenticationToken.toString(),
            String.valueOf(cryptoTokenId), null, null, details);
}