Example usage for javax.ejb TransactionAttributeType REQUIRES_NEW

List of usage examples for javax.ejb TransactionAttributeType REQUIRES_NEW

Introduction

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

Prototype

TransactionAttributeType REQUIRES_NEW

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

Click Source Link

Document

The container must invoke an enterprise bean method whose transaction attribute is set to REQUIRES_NEW with a new transaction context.

Usage

From source file:edu.harvard.iq.dvn.core.study.StudyServiceBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void addStudyLock(Long studyId, Long userId, String detail) {
    Study study = em.find(Study.class, studyId);
    VDCUser user = em.find(VDCUser.class, userId);

    StudyLock lock = new StudyLock();
    lock.setStudy(study);//  w  w w .j  a v  a2  s . c o  m
    lock.setUser(user);
    lock.setDetail(detail);
    lock.setStartTime(new Date());

    study.setStudyLock(lock);
    if (user.getStudyLocks() == null) {
        user.setStudyLocks(new ArrayList());
    }
    user.getStudyLocks().add(lock);

    em.persist(lock);
}

From source file:org.rhq.enterprise.server.bundle.BundleManagerBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@RequiredPermission(Permission.MANAGE_BUNDLE)
public BundleResourceDeployment createBundleResourceDeployment(Subject subject, int bundleDeploymentId,
        int resourceId) throws Exception {

    BundleDeployment deployment = entityManager.find(BundleDeployment.class, bundleDeploymentId);
    if (null == deployment) {
        throw new IllegalArgumentException("Invalid bundleDeploymentId: " + bundleDeploymentId);
    }// www .  j  a  v  a2  s  . c  o m
    Resource resource = (Resource) entityManager.find(Resource.class, resourceId);
    if (null == resource) {
        throw new IllegalArgumentException("Invalid resourceId (Resource does not exist): " + resourceId);
    }

    BundleResourceDeployment resourceDeployment = new BundleResourceDeployment(deployment, resource);

    entityManager.persist(resourceDeployment);
    return resourceDeployment;
}

From source file:edu.harvard.iq.dvn.core.study.StudyServiceBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void removeStudyLock(Long studyId) {
    Study study = em.find(Study.class, studyId);
    em.refresh(study);/*from   w w  w.  j  av a  2  s .  c  o m*/
    StudyLock lock = study.getStudyLock();
    if (lock != null) {
        VDCUser user = lock.getUser();
        study.setStudyLock(null);
        user.getStudyLocks().remove(lock);
        em.remove(lock);
    }
}

From source file:org.rhq.enterprise.server.content.ContentManagerBean.java

@TransactionAttribute(value = TransactionAttributeType.REQUIRES_NEW)
public PackageVersion createPackageVersionWithDisplayVersion(Subject subject, String packageName,
        int packageTypeId, String version, String displayVersion, int architectureId,
        InputStream packageBitStream) {
    // See if the package version already exists and return that if it does
    Query packageVersionQuery = entityManager.createNamedQuery(PackageVersion.QUERY_FIND_BY_PACKAGE_VER_ARCH);
    packageVersionQuery.setParameter("name", packageName);
    packageVersionQuery.setParameter("packageTypeId", packageTypeId);
    packageVersionQuery.setParameter("architectureId", architectureId);
    packageVersionQuery.setParameter("version", version);

    // Result of the query should be either 0 or 1
    List existingVersionList = packageVersionQuery.getResultList();
    if (existingVersionList.size() > 0) {
        PackageVersion existingPackageVersion = (PackageVersion) existingVersionList.get(0);
        if (displayVersion != null && !displayVersion.trim().isEmpty()) {
            existingPackageVersion.setDisplayVersion(displayVersion);
            existingPackageVersion = persistOrMergePackageVersionSafely(existingPackageVersion);
        }//from  ww  w .java2 s.com

        return existingPackageVersion;
    }

    Architecture architecture = entityManager.find(Architecture.class, architectureId);
    PackageType packageType = entityManager.find(PackageType.class, packageTypeId);

    //check the validity of the provided data
    try {
        PackageTypeBehavior behavior = ContentManagerHelper.getPackageTypeBehavior(packageTypeId);
        ValidatablePackageDetailsKey key = new ValidatablePackageDetailsKey(packageName, version,
                packageType.getName(), architecture.getName());
        behavior.validateDetails(key, subject);

        packageName = key.getName();
        version = key.getVersion();
        if (!architecture.getName().equals(key.getArchitectureName())) {
            Query q = entityManager.createNamedQuery(Architecture.QUERY_FIND_BY_NAME);
            q.setParameter("name", key.getArchitectureName());
            architecture = (Architecture) q.getSingleResult();
        }
    } catch (PackageDetailsValidationException e) {
        throw e;
    } catch (Exception e) {
        log.error("Failed to get the package type plugin container. This is a bug.", e);
        throw new IllegalStateException("Failed to get the package type plugin container.", e);
    }

    // If the package doesn't exist, create that here
    Query packageQuery = entityManager.createNamedQuery(Package.QUERY_FIND_BY_NAME_PKG_TYPE_ID);
    packageQuery.setParameter("name", packageName);
    packageQuery.setParameter("packageTypeId", packageTypeId);

    Package existingPackage;

    List existingPackageList = packageQuery.getResultList();

    if (existingPackageList.size() == 0) {
        existingPackage = new Package(packageName, packageType);
        existingPackage = persistOrMergePackageSafely(existingPackage);
    } else {
        existingPackage = (Package) existingPackageList.get(0);
    }

    // Create a package version and add it to the package
    PackageVersion newPackageVersion = new PackageVersion(existingPackage, version, architecture);
    newPackageVersion.setDisplayName(existingPackage.getName());

    newPackageVersion = persistOrMergePackageVersionSafely(newPackageVersion);

    Map<String, String> contentDetails = new HashMap<String, String>();
    PackageBits bits = loadPackageBits(packageBitStream, newPackageVersion.getId(), packageName, version, null,
            contentDetails);

    newPackageVersion.setPackageBits(bits);
    newPackageVersion.setFileSize(Long.valueOf(contentDetails.get(UPLOAD_FILE_SIZE)).longValue());
    newPackageVersion.setSHA256(contentDetails.get(UPLOAD_SHA256));
    newPackageVersion.setDisplayVersion(displayVersion);

    existingPackage.addVersion(newPackageVersion);

    return newPackageVersion;
}

From source file:org.rhq.enterprise.server.content.ContentSourceManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public RepoSyncResults _mergeAdvisorySyncReportADD(ContentSource contentSource, AdvisorySyncReport report,
        RepoSyncResults syncResults, StringBuilder progress) {

    AdvisoryManagerLocal advManager = LookupUtil.getAdvisoryManagerLocal();
    RepoManagerLocal repoManager = LookupUtil.getRepoManagerLocal();
    Subject overlord = LookupUtil.getSubjectManager().getOverlord();
    List<AdvisoryDetails> newDetails = report.getAdvisory();
    for (AdvisoryDetails detail : newDetails) {
        try {/*from  w  w w  . j a  v a  2 s . c  o m*/
            Advisory newAdv = advManager.getAdvisoryByName(detail.getAdvisory());
            if (newAdv == null) {
                // Advisory does not exist, create a new one
                log.debug("Attempting to create new advisory based off of: " + detail);
                newAdv = advManager.createAdvisory(overlord, detail.getAdvisory(), detail.getAdvisory_type(),
                        detail.getSynopsis());
                newAdv.setAdvisory_name(detail.getAdvisory_name());
                newAdv.setAdvisory_rel(detail.getAdvisory_rel());
                newAdv.setDescription(detail.getDescription());
                newAdv.setSolution(detail.getSolution());
                newAdv.setIssue_date(detail.getIssue_date());
                newAdv.setUpdate_date(detail.getUpdate_date());
                newAdv.setTopic(detail.getTopic());
                entityManager.flush();
                entityManager.persist(newAdv);
            }

            Repo repo = repoManager.getRepo(overlord, report.getRepoId());
            RepoAdvisory repoAdv = new RepoAdvisory(repo, newAdv);
            log.debug("Created new mapping of RepoAdvisory repoId = " + repo.getId() + ", distId = "
                    + newAdv.getId());
            entityManager.flush();
            entityManager.persist(repoAdv);
            // persist pkgs associated with an errata
            List<AdvisoryPackageDetails> pkgs = detail.getPkgs();

            Query q = entityManager.createNamedQuery(PackageVersion.QUERY_FIND_PACKAGEVERSION_BY_FILENAME);
            for (AdvisoryPackageDetails pkg : pkgs) {
                try {
                    q.setParameter("rpmName", pkg.getRpmFilename());
                    PackageVersion pExisting = (PackageVersion) q.getSingleResult();
                    AdvisoryPackage apkg = advManager.findAdvisoryPackage(overlord, newAdv.getId(),
                            pExisting.getId());
                    if (apkg == null) {
                        apkg = new AdvisoryPackage(newAdv, pExisting);
                        entityManager.persist(apkg);
                        entityManager.flush();
                    }
                } catch (NoResultException nre) {
                    log.info("Advisory has package thats not yet in the db [" + pkg.getRpmFilename()
                            + "] - Processing rest");
                }
            }
            //persist cves associated with an errata
            List<AdvisoryCVEDetails> cves = detail.getCVEs();
            log.debug("list of CVEs " + cves);
            if (cves != null && cves.size() > 0) {
                for (AdvisoryCVEDetails cve : cves) {
                    AdvisoryCVE acve = new AdvisoryCVE(newAdv, advManager.createCVE(overlord, cve.getName()));
                    entityManager.persist(acve);
                    entityManager.flush();
                }
            }

            List<AdvisoryBugDetails> abugs = detail.getBugs();
            log.debug("list of Bugs " + abugs);
            if (abugs != null && abugs.size() > 0) {
                for (AdvisoryBugDetails abug : abugs) {
                    AdvisoryBuglist abuglist = advManager.getAdvisoryBuglist(overlord, newAdv.getId(),
                            abug.getBugInfo());
                    if (abuglist == null) {
                        abuglist = new AdvisoryBuglist(newAdv, abug.getBugInfo());
                        entityManager.persist(abuglist);
                        entityManager.flush();
                    }
                }
            }

        } catch (AdvisoryException e) {
            progress.append("Caught exception when trying to add: " + detail.getAdvisory() + "\n");
            progress.append("Error is: " + e.getMessage());
            syncResults.setResults(progress.toString());
            syncResults = repoManager.mergeRepoSyncResults(syncResults);
            log.error(e);
        }
    }
    return syncResults;
}

From source file:org.rhq.enterprise.server.content.ContentManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public PackageVersion persistPackageVersion(PackageVersion pv) {
    // EM.persist requires related entities to be attached, let's attach them now

    // package has persist cascade enabled, so skip loading it if we'll allow it to be created here
    if (pv.getGeneralPackage().getId() > 0) {
        pv.setGeneralPackage(entityManager.find(Package.class, pv.getGeneralPackage().getId()));
    }/*from  w w  w  . j  av  a2s  .  c o  m*/

    // arch has persist cascade enabled, so skip loading it if we'll allow it to be created here
    if (pv.getArchitecture().getId() > 0) {
        pv.setArchitecture(entityManager.find(Architecture.class, pv.getArchitecture().getId()));
    }

    // config is optional but has persist cascade enabled, so skip loading it if we'll allow it to be created here
    if (pv.getExtraProperties() != null && pv.getExtraProperties().getId() > 0) {
        pv.setExtraProperties(entityManager.find(Configuration.class, pv.getExtraProperties().getId()));
    }

    // our object's relations are now full attached, we can persist it
    entityManager.persist(pv);
    return pv;
}

From source file:org.nightlabs.jfire.accounting.AccountingManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@RolesAllowed("_Guest_")
@Override//from w w  w .  j av  a 2 s.  c om
public PaymentResult _payBegin(final PaymentData paymentData) {
    if (paymentData == null)
        throw new NullPointerException("paymentData");

    if (paymentData.getPayment() == null)
        throw new NullPointerException("paymentData.getPayment() is null!");

    if (paymentData.getPayment().getPartnerID() == null) {
        // if no partner is defined, at least one invoice must be known!
        if (paymentData.getPayment().getPayableObjectIDs() == null)
            throw new NullPointerException(
                    "paymentData.getPayment().getPartnerID() and paymentData.getPayment().getInvoiceIDs() are both null! One of them must be specified, because I need to know who's paying!");

        if (paymentData.getPayment().getPayableObjectIDs().isEmpty())
            throw new NullPointerException(
                    "paymentData.getPayment().getPartnerID() is null and paymentData.getPayment().getInvoiceIDs() is empty! If no partner is specified explicitely, I need at least one invoice to find out who's paying!");
    }

    if (paymentData.getPayment().getCurrencyID() == null)
        throw new NullPointerException("paymentData.getPayment().getCurrencyID() is null!");

    if (paymentData.getPayment().getAmount() < 0)
        throw new IllegalArgumentException("paymentData.getPayment().getAmount() < 0!");

    if (paymentData.getPayment().getModeOfPaymentFlavourID() == null)
        throw new NullPointerException("paymentData.getPayment().getModeOfPaymentFlavourID() is null!");

    if (paymentData.getPayment().getPayBeginClientResult() == null)
        throw new NullPointerException("paymentData.getPayment().getPayBeginClientResult() is null!");

    // Store paymentData into the database within a NEW TRANSACTION to prevent it
    // from being deleted (if this method fails later and causes a rollback).
    final PaymentDataID paymentDataID = paymentHelperLocal.payBegin_storePaymentData(paymentData);

    final String[] fetchGroups = new String[] { FetchPlan.DEFAULT };

    try {

        return paymentHelperLocal.payBegin_internal(paymentDataID, fetchGroups,
                NLJDOHelper.MAX_FETCH_DEPTH_NO_LIMIT);

    } catch (final Throwable t) {
        logger.error("payBegin_internal(...) failed: " + paymentDataID, t);
        final PaymentResult payBeginServerResult = new PaymentResult(getOrganisationID(), t);

        try {
            return paymentHelperLocal.payBegin_storePayBeginServerResult(PaymentID.create(paymentDataID),
                    payBeginServerResult, true, fetchGroups, NLJDOHelper.MAX_FETCH_DEPTH_NO_LIMIT);
        } catch (final RuntimeException x) {
            throw x;
        } catch (final Exception x) {
            throw new RuntimeException(x);
        }
    }
}

From source file:org.cesecore.certificates.certificate.CertificateStoreSessionBean.java

License:asdf

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void checkForUniqueCertificateSerialNumberIndexInTransaction(AuthenticationToken admin,
        Certificate incert, String username, String cafp, int status, int type, int certificateProfileId,
        String tag, long updateTime) throws CreateException, AuthorizationDeniedException {
    storeCertificate(admin, incert, username, cafp, status, type, certificateProfileId, tag, updateTime);
}

From source file:org.nightlabs.jfire.store.StoreManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@RolesAllowed("_Guest_")
@Override/*ww  w  .j a  v  a  2s . com*/
public DeliveryResult _deliverDoWork(DeliveryID deliveryID, DeliveryResult deliverDoWorkClientResult,
        boolean forceRollback) {
    if (deliveryID == null)
        throw new NullPointerException("deliveryID");

    if (deliverDoWorkClientResult == null)
        throw new NullPointerException("deliverDoWorkClientResult");

    // Store deliverDoWorkClientResult into the database within a NEW TRANSACTION to
    // prevent it from being lost (if this method fails later and causes a rollback).
    try {
        deliveryHelperLocal.deliverDoWork_storeDeliverDoWorkClientResult(deliveryID, deliverDoWorkClientResult,
                forceRollback);
    } catch (RuntimeException x) {
        throw x;
    } catch (Exception x) {
        throw new RuntimeException(x);
    }

    String[] fetchGroups = new String[] { FetchPlan.DEFAULT };

    try {

        return deliveryHelperLocal.deliverDoWork_internal(deliveryID, fetchGroups,
                NLJDOHelper.MAX_FETCH_DEPTH_NO_LIMIT);

    } catch (Throwable t) {
        DeliveryResult deliverDoWorkServerResult = new DeliveryResult(t);

        try {
            DeliveryResult deliverDoWorkServerResult_detached = deliveryHelperLocal
                    .deliverDoWork_storeDeliverDoWorkServerResult(deliveryID, deliverDoWorkServerResult, true,
                            fetchGroups, NLJDOHelper.MAX_FETCH_DEPTH_NO_LIMIT);

            return deliverDoWorkServerResult_detached;
        } catch (RuntimeException x) {
            throw x;
        } catch (Exception x) {
            throw new RuntimeException(x);
        }
    }
}

From source file:org.cesecore.certificates.certificate.CertificateStoreSessionBean.java

License:asdf

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void removeUniqueCertificateSerialNumberTestCertificates() {
    final X509Certificate x509Certificate1 = UniqueSernoHelper.getTestCertificate1();
    final X509Certificate x509Certificate2 = UniqueSernoHelper.getTestCertificate2();
    final String fingerprint1 = CertTools.getFingerprintAsString(x509Certificate1);
    final String fingerprint2 = CertTools.getFingerprintAsString(x509Certificate2);
    entityManager.createNativeQuery(/*www.j a v  a  2s .c o m*/
            "DELETE FROM Base64CertData WHERE fingerprint IN ('" + fingerprint1 + "', '" + fingerprint2 + "')")
            .executeUpdate();
    entityManager.createNativeQuery(
            "DELETE FROM CertificateData WHERE fingerprint IN ('" + fingerprint1 + "', '" + fingerprint2 + "')")
            .executeUpdate();
}