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

/**
 *  Check that a studyId entered by the user is unique (not currently used for any other study in this Dataverse Network)
 *///from   w  w w  .jav a 2  s  .c  o m
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public boolean isUniqueStudyId(String userStudyId, String protocol, String authority) {

    String queryStr = "SELECT s from Study s where s.studyId = :studyId  and s.protocol= :protocol and s.authority= :authority";

    Study study = null;

    Query query = em.createQuery(queryStr);
    query.setParameter("studyId", userStudyId);
    query.setParameter("protocol", protocol);
    query.setParameter("authority", authority);
    return query.getResultList().size() == 0;

}

From source file:org.rhq.enterprise.server.measurement.MeasurementScheduleManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public int returnSchedulesFor(int[] batchIds, Set<ResourceMeasurementScheduleRequest> allSchedules)
        throws Exception {
    Connection conn = null;//  w  w  w.j  a  va2 s.  co  m
    PreparedStatement resultsStatement = null;

    int created = -1;
    try {
        conn = dataSource.getConnection();

        String resultsQueryString = MeasurementSchedule.NATIVE_QUERY_REPORTING_RESOURCE_MEASUREMENT_SCHEDULE_REQUEST;
        resultsQueryString = JDBCUtil.transformQueryForMultipleInParameters(resultsQueryString, "@@RESOURCES@@",
                batchIds.length);
        resultsStatement = conn.prepareStatement(resultsQueryString);

        JDBCUtil.bindNTimes(resultsStatement, batchIds, 1);

        Map<Integer, ResourceMeasurementScheduleRequest> scheduleRequestMap = new HashMap<Integer, ResourceMeasurementScheduleRequest>();
        ResultSet results = resultsStatement.executeQuery();
        try {
            while (results.next()) {
                Integer resourceId = (Integer) results.getInt(1);
                Integer scheduleId = (Integer) results.getInt(2);
                String definitionName = (String) results.getString(3);
                Long interval = (Long) results.getLong(4);
                Boolean enabled = (Boolean) results.getBoolean(5);
                DataType dataType = DataType.values()[results.getInt(6)];
                NumericType rawNumericType = NumericType.values()[results.getInt(7)];
                if (results.wasNull()) {
                    rawNumericType = null;
                }

                ResourceMeasurementScheduleRequest scheduleRequest = scheduleRequestMap.get(resourceId);
                if (scheduleRequest == null) {
                    scheduleRequest = new ResourceMeasurementScheduleRequest(resourceId);
                    scheduleRequestMap.put(resourceId, scheduleRequest);
                    allSchedules.add(scheduleRequest);
                }

                MeasurementScheduleRequest requestData = new MeasurementScheduleRequest(scheduleId,
                        definitionName, interval, enabled, dataType, rawNumericType);
                scheduleRequest.addMeasurementScheduleRequest(requestData);
            }
        } finally {
            results.close();
        }
    } finally {
        if (resultsStatement != null) {
            try {
                resultsStatement.close();
            } catch (Exception e) {
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
            }
        }
    }
    return created;
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void failRequest(int requestId, Throwable error) {
    Query query = entityManager.createNamedQuery(ContentServiceRequest.QUERY_FIND_BY_ID);
    query.setParameter("id", requestId);

    ContentServiceRequest persistedRequest = (ContentServiceRequest) query.getSingleResult();
    Resource resource = persistedRequest.getResource();

    persistedRequest.setErrorMessage(ThrowableUtil.getStackAsString(error));
    persistedRequest.setStatus(ContentRequestStatus.FAILURE);

    // This should only be called as the result of an exception during the user initiated action. As such,
    // every package history entity represents an in progress state. Add a new entry for each in the failed state.
    long timestamp = System.currentTimeMillis();

    for (InstalledPackageHistory history : persistedRequest.getInstalledPackageHistory()) {
        InstalledPackageHistory failedEntry = new InstalledPackageHistory();
        failedEntry.setContentServiceRequest(persistedRequest);
        failedEntry.setDeploymentConfigurationValues(history.getDeploymentConfigurationValues());
        failedEntry.setErrorMessage(ThrowableUtil.getStackAsString(error));
        failedEntry.setPackageVersion(history.getPackageVersion());
        failedEntry.setResource(resource);
        failedEntry.setStatus(InstalledPackageHistoryStatus.FAILED);
        failedEntry.setTimestamp(timestamp);

        persistedRequest.addInstalledPackageHistory(failedEntry);
    }/*from   w w w  . j a  va  2  s .c  o m*/
}

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

@SuppressWarnings("unchecked")
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public RepoSyncResults persistRepoSyncResults(RepoSyncResults results) {

    ContentManagerHelper helper = new ContentManagerHelper(entityManager);
    Query q = entityManager.createNamedQuery(RepoSyncResults.QUERY_GET_INPROGRESS_BY_REPO_ID);
    q.setParameter("repoId", results.getRepo().getId());

    RepoSyncResults persistedSyncResults = (RepoSyncResults) helper.persistSyncResults(q, results);
    return (null != persistedSyncResults) ? persistedSyncResults : results;
}

From source file:org.rhq.enterprise.server.cloud.StorageNodeManagerBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@RequiredPermission(Permission.MANAGE_SETTINGS)
public void scheduleOperationInNewTransaction(Subject subject, ResourceOperationSchedule schedule) {
    operationManager.scheduleResourceOperation(subject, schedule);
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public RepoSyncResults mergeRepoSyncResults(RepoSyncResults results) {
    RepoSyncResults retval = entityManager.merge(results);
    return retval;
}

From source file:net.o3s.beans.registering.RegisteringBean.java

@SuppressWarnings("unchecked")
 @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
 public IEntityRegistered importRegistered(final IEntityEvent event, final IEntityCompetition competition,
         final IEntityCategory category, final String name, final Date registeringDate, final String labelValue,
         final String rfid, final boolean isTeamed, final boolean isPaid, final boolean providedHealthForm,
         final List<IEntityPerson> persons, final String club, final String source, final Date arrivalDate,
         final long elapsedTime) throws AlreadyExistException, RegisteringException {

     // Check if the registered already exists
     IEntityRegistered registered = null;
     try {//from ww  w.j a v a 2s.  c o  m
         registered = findRegisteredFromLabel(labelValue);
     } catch (InvalidException e1) {
         // TODO Auto-generated catch block
         e1.printStackTrace();
     }

     if (registered != null) {
         throw new AlreadyExistException(
                 "L'inscrit <" + name + "> avec le dossard <" + labelValue + "> existe deja !" + registered);
     }

     if (competition == null) {
         throw new RegisteringException("Competition inconnue pour le dossard : " + labelValue);
     }

     // At first check if the persons are not registered yet
     List<IEntityPerson> persistedPersonsList = new ArrayList<IEntityPerson>();
     for (IEntityPerson person : persons) {
         // Attempt to create the person
         IEntityPerson pClone = null;
         try {
             pClone = createPerson(person);
             logger.log(Level.FINE, "creation <" + person + ">");

         } catch (AlreadyExistException e) {

             // if exists, update it
             pClone = findPersonFromLastnameFirstNameBirthDay(person.getLastname(), person.getFirstname(),
                     person.getBirthday());
             IEntityRegistered rClone = findRegisteredFromPersonForDefaultEvent(pClone.getId());
             if (rClone != null) {
                 throw new AlreadyExistException("L'inscrit <" + name + "> existe deja !" + rClone);
             }

             logger.log(Level.WARNING, "La personne <" + person + "> existe deja -> update");

             pClone.setLastname(person.getLastname());
             pClone.setFirstname(person.getFirstname());
             pClone.setBirthday(person.getBirthday());
             pClone.setSex(person.getSex());
             pClone.setEmail(person.getEmail());
             pClone.setClub(person.getClub());
             pClone.setLicense(person.getLicense());
             updatePerson(pClone);
         }
         persistedPersonsList.add(pClone);

     }

     // reach this point means that none person is already registered !
     registered = new Registered();
     registered.setEvent(event);
     registered.setCompetition(competition);
     registered.setCategory(category);
     registered.setName(name);
     registered.setRegisteringDate(registeringDate);
     registered.setPersons(new HashSet(persistedPersonsList));
     registered.setLabel(createLabel(competition, labelValue, rfid));
     registered.setIsPaid(isPaid);
     registered.setIsTeamed(isTeamed);
     registered.setProvidedHealthForm(providedHealthForm);
     if (club != null) {
         registered.setClub(club);
     }

     registered.setSource(source);

     if (arrivalDate != null) {
         registered.setArrivalDate(arrivalDate);
     }

     if (elapsedTime != 0) {
         registered.setElapsedTime(elapsedTime);
     }

     this.entityManager.merge(registered);
     logger.log(Level.FINE, "creation <" + registered + ">");

     return registered;

 }

From source file:org.rhq.enterprise.server.measurement.MeasurementScheduleManagerBean.java

@SuppressWarnings("unchecked")
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void errorCorrectSchedules() {
    /* /*from  w  w  w  . ja v  a2 s  .com*/
     * update mtime of resources whose schedules are < 30s, this will indicate to the 
     * agent that it needs to sync / merge schedules for the resources updated here
     */
    try {
        long now = System.currentTimeMillis();
        String updateResourcesQueryString = "" //
                + " UPDATE Resource " //
                + "    SET mtime = :currentTime " //
                + "  WHERE id IN ( SELECT ms.resource.id " //
                + "                  FROM MeasurementSchedule ms " // 
                + "                 WHERE ms.interval < 30000 ) ";
        Query updateResourcesQuery = entityManager.createQuery(updateResourcesQueryString);
        updateResourcesQuery.setParameter("currentTime", now);
        int resourcesUpdatedCount = updateResourcesQuery.executeUpdate();

        // update schedules to 30s whose schedules are < 30s
        String updateSchedulesQueryString = "" //
                + " UPDATE MeasurementSchedule " //
                + "    SET interval = 30000 " //
                + "  WHERE interval < 30000 ";
        Query updateSchedulesQuery = entityManager.createQuery(updateSchedulesQueryString);
        int schedulesUpdatedCount = updateSchedulesQuery.executeUpdate();

        if (resourcesUpdatedCount > 0) {
            // now try to tell the agents that certain resources have changed
            String findResourcesQueryString = "" //
                    + " SELECT res.id " //
                    + "   FROM Resource res " //
                    + "  WHERE res.mtime = :currentTime ";
            Query findResourcesQuery = entityManager.createQuery(findResourcesQueryString);
            findResourcesQuery.setParameter("currentTime", now);
            List<Integer> updatedResourceIds = findResourcesQuery.getResultList();
            updateMeasurementSchedulesForResources(ArrayUtils.unwrapCollection(updatedResourceIds));

            log.error("MeasurementSchedule data was corrupt: automatically updated " + resourcesUpdatedCount
                    + " resources and " + schedulesUpdatedCount
                    + " to correct the issue; agents were notified");
        } else {
            if (log.isDebugEnabled()) {
                log.debug("MeasurementSchedule data was checked for corruption, but all data was consistent");
            }
        }
    } catch (Throwable t) {
        log.error("There was a problem correcting errors for MeasurementSchedules", t);
    }
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public ContentSourceSyncResults mergeContentSourceSyncResults(ContentSourceSyncResults results) {
    return entityManager.merge(results);
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@RolesAllowed("_Guest_")
@Override//w w  w  . j  a v a 2 s .  com
public DeliveryResult _deliverBegin(DeliveryData deliveryData) {
    if (logger.isDebugEnabled()) {
        logger.debug("_deliverBegin: *** begin ******************************************* ");
        logger.debug("_deliverBegin: IDGenerator.getOrganisationID()=" + IDGenerator.getOrganisationID());
        logger.debug("_deliverBegin: this.getOrganisationID()=" + this.getOrganisationID());
    }

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

    if (deliveryData.getDelivery() == null)
        throw new NullPointerException("deliveryData.getDelivery() is null!");

    //      if (deliveryData.getDelivery().getPartnerID() == null) {
    //         // if no partner is defined, at least one deliveryNote must be known!
    //         if (deliveryData.getDelivery().getDeliveryNoteIDs() == null)
    //            throw new NullPointerException("deliveryData.getDelivery().getPartnerID() and deliveryData.getDelivery().getDeliveryNoteIDs() are both null! One of them must be specified, because I need to know who's delivering!");
    //
    //         if (deliveryData.getDelivery().getDeliveryNoteIDs().isEmpty())
    //            throw new NullPointerException("deliveryData.getDelivery().getPartnerID() is null and deliveryData.getDelivery().getDeliveryNoteIDs() is empty! If no partner is specified explicitely, I need at least one invoice to find out who's delivering!");
    //      }
    if (deliveryData.getDelivery().getArticleIDs() == null)
        throw new IllegalArgumentException("deliveryData.getDelivery().getArticleIDs() is null!");

    if (deliveryData.getDelivery().getArticleIDs().isEmpty())
        throw new IllegalArgumentException("deliveryData.getDelivery().getArticleIDs() is empty!");

    //      if (deliveryData.getDelivery().getCurrencyID() == null)
    //         throw new NullPointerException("deliveryData.getDelivery().getCurrencyID() is null!");
    //
    //      if (deliveryData.getDelivery().getAmount() < 0)
    //         throw new IllegalArgumentException("deliveryData.getDelivery().getAmount() < 0!");

    if (deliveryData.getDelivery().getModeOfDeliveryFlavourID() == null)
        throw new IllegalArgumentException("deliveryData.getDelivery().getModeOfDeliveryFlavourID() is null!");

    if (deliveryData.getDelivery().getClientDeliveryProcessorFactoryID() == null)
        throw new IllegalArgumentException(
                "deliveryData.getDelivery().getClientDeliveryProcessorFactoryID() is null!");

    if (deliveryData.getDelivery().getDeliverBeginClientResult() == null)
        throw new IllegalArgumentException("deliveryData.getDelivery().getDeliverBeginClientResult() is null!");

    // Store deliveryData into the database within a NEW TRANSACTION to prevent it
    // from being deleted (if this method fails later and causes a rollback).
    DeliveryDataID deliveryDataID = deliveryHelperLocal.deliverBegin_storeDeliveryData(deliveryData);

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

    try {

        return deliveryHelperLocal.deliverBegin_internal(deliveryDataID, fetchGroups,
                NLJDOHelper.MAX_FETCH_DEPTH_NO_LIMIT);

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

        try {
            return deliveryHelperLocal.deliverBegin_storeDeliverBeginServerResult(
                    DeliveryID.create(deliveryDataID), deliverBeginServerResult, true, fetchGroups,
                    NLJDOHelper.MAX_FETCH_DEPTH_NO_LIMIT);
        } catch (RuntimeException x) {
            throw x;
        } catch (Exception x) {
            throw new RuntimeException(x);
        }
    }
}