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.configuration.DivisionConfigurationEngineBean.java

/**
 * {@inheritDoc}/* ww  w .  j a v  a  2s  . c o  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public List<FxFlatStorageInfo> getFlatStorageInfos() throws FxApplicationException {
    try {
        return FxFlatStorageManager.getInstance().getFlatStorageInfos();
    } catch (SQLException e) {
        throw new FxDbException(e, "ex.db.sqlError", e.getMessage());
    }
}

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

/**
 * {@inheritDoc}/*from   w ww  . j a va 2 s  .  c o  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public FxScriptInfo createScriptFromLibrary(String libraryname, FxScriptInfo scriptInfo)
        throws FxApplicationException {
    FxPermissionUtils.checkRole(FxContext.getUserTicket(), Role.ScriptManagement);
    String code = FxSharedUtils.loadFromInputStream(
            FxSharedUtils.getResourceStream("fxresources/scripts/library/" + libraryname), -1);
    if (code == null || code.length() == 0)
        throw new FxNotFoundException("ex.scripting.load.library.failed", libraryname);
    return createScript(new FxScriptInfoEdit(-1, scriptInfo.getEvent(), scriptInfo.getName(),
            scriptInfo.getDescription(), code, scriptInfo.isActive(), scriptInfo.isCached()));
}

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

/**
 * {@inheritDoc}/*w  ww.j a  v  a2s.c o m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public String getRootPassword() throws FxApplicationException {
    return get(SystemParameters.GLOBAL_ROOT_PASSWORD);
}

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

/**
 * {@inheritDoc}//w  w  w.j a  v  a2 s . c o m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void mergeMetaData(long id, Collection<FxReferenceMetaData<FxPK>> metaData)
        throws FxApplicationException {
    checkEditBriefcase(load(id));
    Connection con = null;
    boolean success = false;
    try {
        con = Database.getDbConnection();

        // merge changes into existing metadata
        final List<FxReferenceMetaData<FxPK>> currentMeta = loadMetaData(con, id, -1, true);
        final List<FxReferenceMetaData<FxPK>> newMeta = Lists.newArrayListWithCapacity(currentMeta.size());
        for (FxReferenceMetaData<FxPK> update : metaData) {
            if (update.getReference() == null) {
                throw new FxUpdateException(LOG, "ex.briefcase.metadata.update.reference");
            }
            // find existing metadata to apply changes to
            final FxReferenceMetaData<FxPK> oldMeta = FxReferenceMetaData.findByContent(currentMeta,
                    update.getReference());
            if (oldMeta == null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("No matching row found for briefcase item " + update.getReference()
                            + ", ignoring.");
                }
            } else {
                // merge changes
                oldMeta.merge(update);
                newMeta.add(oldMeta);
            }
        }

        // write back changes
        replaceMetaData(con, id, newMeta);

        success = true;
    } catch (SQLException e) {
        throw new FxUpdateException(LOG, e);
    } finally {
        if (!success) {
            EJBUtils.rollback(ctx);
        }
        closeObjects(BriefcaseEngineBean.class, con, null);
    }

}

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

/**
 * {@inheritDoc}/*  w  w  w .  j a v a2s  .com*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Factor copyFactor(Project project, long factorId)
        throws ProposalWorkflowException, InconsistentProjectStateException {
    checkIfProjectSaveAllowed(project);
    final Factor factor = this.searchDao.retrieve(Factor.class, factorId);
    final Factor copy = new Factor();
    final String copyName = getGenericDataService().getIncrementingCopyName(Factor.class, "name",
            factor.getName());
    copy.setName(copyName);
    copy.setType(factor.getType());
    project.getExperiment().getFactors().add(copy);
    this.projectDao.save(project);
    return copy;
}

From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void updateCAIds(AuthenticationToken authenticationToken, int fromId, int toId, String toDN)
        throws AuthorizationDeniedException {
    log.info("Updating CAIds in relations from " + fromId + " to " + toId + "\n");

    // Update Certificate Profiles
    final Map<Integer, String> certProfiles = certificateProfileSession.getCertificateProfileIdToNameMap();
    for (Integer certProfId : certProfiles.keySet()) {
        boolean changed = false;
        final CertificateProfile certProfile = certificateProfileSession.getCertificateProfile(certProfId);
        final List<Integer> availableCAs = new ArrayList<Integer>(certProfile.getAvailableCAs());
        // The list is modified so we can't use an iterator
        for (int i = 0; i < availableCAs.size(); i++) {
            int value = availableCAs.get(i);
            if (value == fromId) {
                availableCAs.set(i, toId);
                changed = true;/*from  w  w w . j  a v  a  2s. co  m*/
            }
        }

        if (changed) {
            certProfile.setAvailableCAs(availableCAs);
            String name = certProfiles.get(certProfId);
            certificateProfileSession.changeCertificateProfile(authenticationToken, name, certProfile);
        }
    }

    // Update End-Entity Profiles
    final Map<Integer, String> endEntityProfiles = endEntityProfileSession.getEndEntityProfileIdToNameMap();
    for (Integer endEntityProfId : endEntityProfiles.keySet()) {
        boolean changed = false;
        final EndEntityProfile endEntityProfile = endEntityProfileSession.getEndEntityProfile(endEntityProfId);

        if (endEntityProfile.getDefaultCA() == fromId) {
            endEntityProfile.setValue(EndEntityProfile.DEFAULTCA, 0, String.valueOf(toId));
            changed = true;
        }

        final Collection<String> original = endEntityProfile.getAvailableCAs();
        final List<Integer> updated = new ArrayList<Integer>();
        for (String oldvalueStr : original) {
            int oldvalue = Integer.valueOf(oldvalueStr);
            int newvalue;
            if (oldvalue == fromId) {
                newvalue = toId;
                changed = true;
            } else {
                newvalue = oldvalue;
            }
            updated.add(newvalue);
        }

        if (changed) {
            endEntityProfile.setAvailableCAs(updated);
            String name = endEntityProfiles.get(endEntityProfId);
            try {
                endEntityProfileSession.changeEndEntityProfile(authenticationToken, name, endEntityProfile);
            } catch (EndEntityProfileNotFoundException e) {
                log.error("End-entity profile " + name + " could no longer be found", e);
            }
        }
    }

    // Update End-Entities (only if it's possible to get the session bean)
    EndEntityManagementSessionLocal endEntityManagementSession = getEndEntityManagementSession();
    if (endEntityManagementSession != null) {
        final Collection<EndEntityInformation> endEntities = endEntityManagementSession
                .findAllUsersByCaId(authenticationToken, fromId);
        for (EndEntityInformation endEntityInfo : endEntities) {
            endEntityInfo.setCAId(toId);
            try {
                endEntityManagementSession.updateCAId(authenticationToken, endEntityInfo.getUsername(), toId);
            } catch (NoSuchEndEntityException e) {
                log.error("End entity " + endEntityInfo.getUsername() + " could no longer be found", e);
            }
        }
    } else {
        log.info("Can not update CAIds of end-entities (this requires EJB 3.1 support in the appserver)");
    }

    // Update Data Sources
    final Map<Integer, String> dataSources = userDataSourceSession
            .getUserDataSourceIdToNameMap(authenticationToken);
    for (Integer dataSourceId : dataSources.keySet()) {
        boolean changed = false;
        final BaseUserDataSource dataSource = userDataSourceSession.getUserDataSource(authenticationToken,
                dataSourceId);

        dataSource.getApplicableCAs();

        final List<Integer> applicableCAs = new ArrayList<Integer>(dataSource.getApplicableCAs());
        // The list is modified so we can't use an iterator
        for (int i = 0; i < applicableCAs.size(); i++) {
            int value = applicableCAs.get(i);
            if (value == fromId) {
                applicableCAs.set(i, toId);
                changed = true;
            }
        }

        if (changed) {
            dataSource.setApplicableCAs(applicableCAs);
            String name = dataSources.get(dataSourceId);
            userDataSourceSession.changeUserDataSource(authenticationToken, name, dataSource);
        }
    }

    // Update Services
    ServiceSessionLocal serviceSession = getServiceSession();
    if (serviceSession != null) {
        final Map<Integer, String> services = serviceSession.getServiceIdToNameMap();
        for (String serviceName : services.values()) {
            final ServiceConfiguration serviceConf = serviceSession.getService(serviceName);
            final Properties workerProps = serviceConf.getWorkerProperties();
            final String idsToCheckStr = workerProps.getProperty(BaseWorker.PROP_CAIDSTOCHECK);
            if (!StringUtils.isEmpty(idsToCheckStr)) {
                boolean changed = false;
                final String[] caIds = idsToCheckStr.split(";");
                for (int i = 0; i < caIds.length; i++) {
                    if (Integer.parseInt(caIds[i]) == fromId) {
                        caIds[i] = String.valueOf(toId);
                        changed = true;
                    }
                }

                if (changed) {
                    workerProps.setProperty(BaseWorker.PROP_CAIDSTOCHECK, StringUtils.join(caIds, ';'));
                    serviceConf.setWorkerProperties(workerProps);
                    serviceSession.changeService(authenticationToken, serviceName, serviceConf, false);
                }
            }
        }
    }

    // Update Internal Key Bindings
    Map<String, Map<String, InternalKeyBindingProperty<?>>> keyBindTypes = keyBindMgmtSession
            .getAvailableTypesAndProperties();
    Map<String, List<Integer>> typesKeybindings = new HashMap<String, List<Integer>>();
    for (String type : keyBindTypes.keySet()) {
        typesKeybindings.put(type, keyBindMgmtSession.getInternalKeyBindingIds(authenticationToken, type));
    }
    for (Map.Entry<String, List<Integer>> entry : typesKeybindings.entrySet()) {
        final List<Integer> keybindIds = entry.getValue();
        for (int keybindId : keybindIds) {
            final InternalKeyBinding keybind = keyBindMgmtSession.getInternalKeyBinding(authenticationToken,
                    keybindId);
            boolean changed = false;
            List<InternalKeyBindingTrustEntry> trustentries = new ArrayList<InternalKeyBindingTrustEntry>();
            for (InternalKeyBindingTrustEntry trustentry : keybind.getTrustedCertificateReferences()) {
                int trustCaId = trustentry.getCaId();
                if (trustCaId == fromId) {
                    trustCaId = toId;
                    changed = true;
                }
                trustentries.add(
                        new InternalKeyBindingTrustEntry(trustCaId, trustentry.fetchCertificateSerialNumber()));
            }

            if (changed) {
                keybind.setTrustedCertificateReferences(trustentries);
                try {
                    keyBindMgmtSession.persistInternalKeyBinding(authenticationToken, keybind);
                } catch (InternalKeyBindingNameInUseException e) {
                    // Should never happen
                    log.error("Name existed when trying to update keybinding", e);
                }
            }
        }
    }

    // Update System Configuration
    GlobalConfiguration globalConfig = (GlobalConfiguration) globalConfigurationSession
            .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID);
    if (globalConfig != null) {
        boolean changed = false;
        if (globalConfig.getAutoEnrollCA() == fromId) {
            globalConfig.setAutoEnrollCA(toId);
            changed = true;
        }
        if (changed) {
            globalConfigurationSession.saveConfiguration(authenticationToken, globalConfig);
        }
    }

    // Update CMP Configuration
    // Only "Default CA" contains a reference to the Subject DN. All other fields reference the CAs by CA name.
    CmpConfiguration cmpConfig = (CmpConfiguration) globalConfigurationSession
            .getCachedConfiguration(CmpConfiguration.CMP_CONFIGURATION_ID);
    if (cmpConfig != null) {
        boolean changed = false;
        for (String alias : cmpConfig.getAliasList()) {
            final String defaultCaDN = cmpConfig.getCMPDefaultCA(alias);
            if (defaultCaDN != null && defaultCaDN.hashCode() == fromId) {
                cmpConfig.setCMPDefaultCA(alias, toDN);
                changed = true;
            }
        }
        if (changed) {
            globalConfigurationSession.saveConfiguration(authenticationToken, cmpConfig);
        }
    }

    // Update Roles
    final Random random = new Random(System.nanoTime());
    for (RoleData role : roleManagementSession.getAllRolesAuthorizedToEdit(authenticationToken)) {
        final String roleName = role.getRoleName();
        final Map<Integer, AccessUserAspectData> users = new HashMap<Integer, AccessUserAspectData>(
                role.getAccessUsers());
        boolean changed = false;
        for (int id : new ArrayList<Integer>(users.keySet())) {
            AccessUserAspectData user = users.get(id);
            if (user.getCaId() == fromId) {
                user = new AccessUserAspectData(roleName, toId, user.getMatchWith(), user.getTokenType(),
                        user.getMatchTypeAsType(), user.getMatchValue());
                users.put(id, user);
                changed = true;
            }
        }
        if (changed) {
            final Map<Integer, AccessRuleData> rules = role.getAccessRules(); // Contains no CAIds. Used as-is

            try {
                // Rename old role so we can replace it without getting locked out
                final String oldTempName = roleName + "_CAIdUpdateOld" + random.nextLong();
                roleManagementSession.renameRole(authenticationToken, roleName, oldTempName);

                RoleData newRole = roleManagementSession.create(authenticationToken, roleName);
                // Rights are unchanged because they don't reference CAs
                newRole = roleManagementSession.addAccessRulesToRole(authenticationToken, newRole,
                        rules.values());
                newRole = roleManagementSession.addSubjectsToRole(authenticationToken, newRole, users.values());

                roleManagementSession.remove(authenticationToken, oldTempName);
            } catch (RoleNotFoundException e) {
                throw new IllegalStateException("Newly created temporary role was not found", e);
            } catch (RoleExistsException e) {
                throw new IllegalStateException("Temporary role name already exists", e);
            }
        }
    }

    final String detailsMsg = intres.getLocalizedMessage("caadmin.updatedcaid", fromId, toId, toDN);
    auditSession.log(EventTypes.CA_EDITING, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE,
            authenticationToken.toString(), String.valueOf(toId), null, null, detailsMsg);
}

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

/**
 * {@inheritDoc}//from  w  w w  . ja va 2s .  co m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public boolean isMatchingRootPassword(String userPassword) throws FxApplicationException {
    String hashedPassword = getRootPassword();
    return getHashedPassword(userPassword).matches(hashedPassword);
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRED)
@Override/*from w  w w.  j a v  a 2 s .  co  m*/
public void setRevokeStatus(Admin admin, String issuerdn, BigInteger serno, Collection<Integer> publishers,
        int reason, String userDataDN) {
    setRevokeStatus(admin, issuerdn, serno, new Date(), publishers, reason, userDataDN);
}

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

/**
 * {@inheritDoc}/*from w  ww .j a va2 s  .  c  om*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public boolean removePhrase(String phraseKey, long mandator) throws FxNoAccessException, FxEntryInUseException {
    return removePhrase(FxPhraseCategorySelection.CATEGORY_DEFAULT, phraseKey, mandator);
}

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

/**
 * {@inheritDoc}//w  w  w  . j a  va  2s .com
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void setRootLogin(String value) throws FxApplicationException {
    put(SystemParameters.GLOBAL_ROOT_LOGIN, value);
}