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:gwap.rest.UserPicture.java

@POST
@Path("/userpicture")
@Consumes(MediaType.APPLICATION_JSON)/*from  w  ww.j  a  v a2 s .c  o m*/
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@Transactional
public Response createUserPicture(String string) {
    JSONObject payload = parse(string);
    ArtResource artResource = createPicture(payload);

    artResource.setOrigin(ArtResource.ORIGIN_APP_CRIMESCENE);
    ArtResource isVersionOf = entityManager.find(ArtResource.class,
            Long.parseLong(payload.get("artigoid").toString()));
    artResource.setIsVersionOf(isVersionOf);

    //TODO Bild anlegen
    entityManager.flush();

    log.info("Created picture: #0", artResource.getId());
    return Response.status(Response.Status.CREATED).build();
}

From source file:org.meveo.service.job.JobExecutionService.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void persistResult(Job job, JobExecutionResult result, JobInstance jobInstance, User currentUser,
        JobCategoryEnum jobCategory) {//from   w  w w  .  j a v  a  2  s .c  o  m
    try {
        log.info("JobExecutionService persistResult...");
        JobExecutionResultImpl entity = JobExecutionResultImpl.createFromInterface(jobInstance, result);
        boolean persistResult = false;

        if ((entity.getNbItemsCorrectlyProcessed() + entity.getNbItemsProcessedWithError()
                + entity.getNbItemsProcessedWithWarning()) > 0) {
            log.info(job.getClass().getName() + entity.toString());
            persistResult = true;
        } else {
            log.info(job.getClass().getName() + ": nothing to do");
            persistResult = "true"
                    .equals(ParamBean.getInstance().getProperty("meveo.job.persistResult", "true"));
        }
        if (persistResult) {
            if (entity.isTransient()) {
                create(entity, currentUser);
            } else {
                // search for job execution result
                JobExecutionResultImpl updateEntity = findById(result.getId());
                if (updateEntity != null) {
                    JobExecutionResultImpl.updateFromInterface(result, updateEntity);
                }
            }
            result.setId(entity.getId());
        }
        log.info("PersistResult entity.isDone()=" + entity.isDone());
        if (!entity.isDone()) {
            executeJob(job.getClass().getSimpleName(), jobInstance, currentUser, jobCategory);
        } else if (jobInstance.getFollowingJob() != null) {
            try {
                JobInstance jobFlow = jobInstanceService.attach(jobInstance.getFollowingJob());
                executeJob(jobFlow.getJobTemplate(), jobFlow, currentUser, jobFlow.getJobCategoryEnum());
            } catch (Exception e) {
                log.warn("PersistResult cannot excute the following jobs.");
            }
        }
    } catch (Exception e) {// FIXME:BusinessException e) {
        log.error("error on persistResult", e);
    }
    log.info("JobExecutionService persistResult End");
}

From source file:gwap.rest.NewPicture.java

@PUT
@Consumes(MediaType.APPLICATION_JSON)//from w w  w .  ja  va  2 s  .c o  m
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@Transactional
@Path("/newpicture/{id:[0-9][0-9]*}")
public Response rateNewPicture(@PathParam("id") String idString, String payloadString) {
    persistPicturerating(idString, payloadString);
    return Response.ok().build();
}

From source file:org.cesecore.audit.impl.queued.QueuedLoggerSessionBean.java

/**
 * {@inheritDoc}//from   w  ww .  j a v  a2 s  .  c om
 * @see InternalSecurityEventsLoggerSession#log(TrustedTime,EventType,EventStatus,ModuleType,ServiceType,String,Map<String,Object>)
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) // Always persist audit log
public void log(final TrustedTime trustedTime, EventType eventType, EventStatus eventStatus, ModuleType module,
        ServiceType service, String authToken, final String customId, final String searchDetail1,
        final String searchDetail2, Map<String, Object> additionalDetails, Properties properties)
        throws AuditRecordStorageException {

    AuditLogData auditLogData = new AuditLogData();
    auditLogData.setEventType(eventType);
    auditLogData.setEventStatus(eventStatus);
    auditLogData.setModule(module);
    auditLogData.setService(service);
    auditLogData.setAuthToken(authToken);
    auditLogData.setMapAdditionalDetails(additionalDetails);

    LogManagementData config = null;
    try {
        config = LogManagementManager.getCurrentConfiguration(em);
    } catch (Exception e) {
        throw new AuditRecordStorageException(e.getMessage(), e);
    }
    if (config != null) {
        auditLogData.setConfig(config);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("configuration is not defined");
        }
    }

    AuditLogProcess process = null;
    AuditLogProcessQueue queue;
    try {
        queue = AuditLogProcessQueue.getInstance(em);
    } catch (AuditLogManagerProcessException e) {
        throw new AuditRecordStorageException(e.getMessage(), e);
    }
    try {
        process = queue.push(trustedTime, auditLogData);
        sign(queue, process);
        auditLogData = process.getAuditLogData();
        auditLogData.save(em);
        //removes process from queue
        queue.pull(process);
        if (log.isDebugEnabled()) {
            log.debug("Processed log:" + auditLogData.toString());
        }
    } catch (Exception e) {
        if (process != null) {
            if (log.isDebugEnabled()) {
                log.debug("Abort log: " + auditLogData.toString());
            }
            queue.abort(process, em);
        }
        throw new AuditRecordStorageException(e.getMessage(), e);
    }
}

From source file:org.rhq.enterprise.server.alert.AlertConditionManagerBean.java

@SuppressWarnings("unchecked")
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public PageList<? extends AbstractAlertConditionCategoryComposite> getAlertConditionComposites(Subject user,
        Integer agentId, AlertConditionCategory category, PageControl pageControl) {
    if (authorizationManager.isOverlord(user) == false) {
        throw new PermissionException("User [" + user.getName() + "] does not have permission to call "
                + "getAlertConditionComposites; only the overlord has that right");
    }//from   w  w w.j  ava2  s . co  m

    String queryName = null;
    String countQueryName = AlertCondition.QUERY_BY_CATEGORY_COUNT_PARAMETERIZED; // default

    if (category == AlertConditionCategory.BASELINE) {
        queryName = AlertCondition.QUERY_BY_CATEGORY_BASELINE;
        countQueryName = AlertCondition.QUERY_BY_CATEGORY_COUNT_BASELINE; // no countQuery parameters needed

    } else if (category == AlertConditionCategory.CHANGE) {
        queryName = AlertCondition.QUERY_BY_CATEGORY_CHANGE;

    } else if (category == AlertConditionCategory.TRAIT) {
        queryName = AlertCondition.QUERY_BY_CATEGORY_TRAIT;

    } else if (category == AlertConditionCategory.AVAILABILITY) {
        queryName = AlertCondition.QUERY_BY_CATEGORY_AVAILABILITY;

    } else if (category == AlertConditionCategory.AVAIL_DURATION) {
        // The duration category can use the same availability composite query, just needs a parameter set
        queryName = AlertCondition.QUERY_BY_CATEGORY_AVAILABILITY;

    } else if (category == AlertConditionCategory.CONTROL) {
        queryName = AlertCondition.QUERY_BY_CATEGORY_CONTROL;

    } else if (category == AlertConditionCategory.THRESHOLD) {
        queryName = AlertCondition.QUERY_BY_CATEGORY_THRESHOLD;

    } else if (category == AlertConditionCategory.EVENT) {
        queryName = AlertCondition.QUERY_BY_CATEGORY_EVENT;

    } else if (category == AlertConditionCategory.RESOURCE_CONFIG) {
        queryName = AlertCondition.QUERY_BY_CATEGORY_RESOURCE_CONFIG;

    } else if (category == AlertConditionCategory.DRIFT) {
        queryName = AlertCondition.QUERY_BY_CATEGORY_DRIFT;

    } else if (category == AlertConditionCategory.RANGE) {
        queryName = AlertCondition.QUERY_BY_CATEGORY_RANGE;

    } else {
        throw new IllegalArgumentException(
                "getAlertConditionComposites does not support category '" + category + "'");
    }

    Query query = entityManager.createNamedQuery(queryName);
    PersistenceUtility.setDataPage(query, pageControl);
    Query queryCount = entityManager.createNamedQuery(countQueryName);

    // The following query is used in two places, and needs the category set to get different results
    if (queryName == AlertCondition.QUERY_BY_CATEGORY_AVAILABILITY) {
        query.setParameter("category", category);
    }

    // the default parameterized count query needs a parameter
    if (countQueryName == AlertCondition.QUERY_BY_CATEGORY_COUNT_PARAMETERIZED) {
        queryCount.setParameter("category", category);
    }
    query.setParameter("agentId", agentId);
    queryCount.setParameter("agentId", agentId);

    long totalCount = (Long) queryCount.getSingleResult();
    List<? extends AbstractAlertConditionCategoryComposite> list = query.getResultList();
    LOG.debug("Found " + totalCount + " elements of type '" + category + "', list was size " + list.size());

    return new PageList<AbstractAlertConditionCategoryComposite>(list, (int) totalCount, pageControl);
}

From source file:com.encens.khipus.service.production.RawMaterialPayRollServiceBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void create(RawMaterialPayRoll rawMaterialPayRoll)
        throws EntryDuplicatedException, RawMaterialPayRollException {
    try {/*from w w w  .  j  ava  2s  . co m*/
        validate(rawMaterialPayRoll);
        Object args = preCreate(rawMaterialPayRoll);
        processCreate(rawMaterialPayRoll);
        postCreate(rawMaterialPayRoll, args);
        getEntityManager().flush();
    } catch (PersistenceException e) { //TODO when hibernate will fix this http://opensource.atlassian.com/projects/hibernate/browse/EJB-382, we have to restore EntityExistsException here.
        log.debug("Persistence error..", e);
        log.info("PersistenceException caught");
        //log.error(e);
        throw new EntryDuplicatedException(e);
    }
}

From source file:org.rhq.enterprise.server.alert.AlertConditionLogManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void updateUnmatchedLogByAlertConditionId(int alertConditionId, long ctime, String value) {
    /*//from  w  w w  .ja v a 2 s  . c om
     * this method is marked as REQUIRES_NEW because I want this log work to complete before I resume the
     * outer-scoping transaction, which will operate on the results.
     */
    try {
        try {
            AlertConditionLog alertConditionLog = this.getUnmatchedLogByAlertConditionId(alertConditionId);

            /*
             * No exceptions.
             *
             * This means that there was exactly one existing, unmatched, active alert condition.  This is another
             * positive event associated against the same alertCondition, so we're going to use its data to update the
             * "ctime" and "value" properties.
             */
            alertConditionLog.setCtime(ctime);
            alertConditionLog.setValue(value);
            log.debug("Updating unmatched alert condition log: " + alertConditionLog);

            entityManager.merge(alertConditionLog); // update values, for
            entityManager.flush();
        } catch (NoResultException nre) { // this is the expected case 90% of the time
            // lookup the condition entity
            AlertCondition condition = entityManager.find(AlertCondition.class, alertConditionId);
            if (condition == null) {
                // the associated AlertDefinition must have been updated, which removes all previous AlertConditions
            }

            // persist the log entry
            AlertConditionLog conditionLog = new AlertConditionLog(condition, ctime);
            conditionLog.setValue(value);

            log.debug("Inserting unmatched alert condition log: " + conditionLog);

            entityManager.persist(conditionLog);
            entityManager.flush();
        } catch (NonUniqueResultException nure) {
            // serious bug in the processing logic
            log.debug("Found multiple unmatched results for alertConditionId of " + alertConditionId
                    + " while performing activation.  There should only be one.");
        }
    } catch (Throwable t) {
        Throwable throwable = t;
        boolean found = false;
        while (throwable != null) {
            if (throwable instanceof ConstraintViolationException) {
                // we're trying to persist a log entry for an AlertCondition that was just deleted
                log.debug("ConstraintViolationException thrown during AlertConditionLog persistence");
                found = true;
                break;
            }
            throwable = throwable.getCause();
        }
        if (!found) {
            throw new RuntimeException(
                    "Could not insert log entry for AlertCondition[id=" + alertConditionId + "]", t);
        }
    }
}

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

@SuppressWarnings("unchecked")
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public List<Integer> getAndClearAgentsWithStatusForServer(String serverName) {
    Query selectQuery = entityManager.createNamedQuery(Agent.QUERY_FIND_ALL_WITH_STATUS_BY_SERVER);
    selectQuery.setParameter("serverName", serverName);
    List<Integer> agentIds = selectQuery.getResultList();

    if (agentIds.size() > 0) {
        /* // w w  w .jav  a2 s .c  o  m
         * note: not worried about size of the in clause, because the number of
         * agents per server will be reasonable, say, 50-150
         */
        Query updateQuery = entityManager.createNamedQuery(Agent.QUERY_UPDATE_CLEAR_STATUS_BY_IDS);
        updateQuery.setParameter("agentIds", agentIds);
        updateQuery.executeUpdate();
    }

    return agentIds;
}

From source file:pl.psnc.synat.wrdz.ru.owl.OntologyManager.java

/**
 * Removes the specified ontology.//from   w  ww.  j  a va 2 s  .  co m
 * 
 * @param ontology
 *            ontology to remove.
 */
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
// New transaction since this method should be called even in the case of rollback.  
public void removeLoadedOntologies(OWLOntology ontology) {
    Set<OWLOntology> imports = ontology.getImportsClosure();
    imports.removeAll(BASE_ONTOLOGIES);
    for (OWLOntology imported : imports) {
        MANAGER.removeOntology(imported);
    }
}

From source file:pl.psnc.synat.wrdz.zmkd.plan.DeliveryPlanProcessorBean.java

@Override
@Asynchronous/*from w  w w.  jav a2s .co m*/
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public Future<Void> process(String planId) {

    DeliveryPlan plan = planDao.findById(planId);
    if (plan == null) {
        logger.error("No such plan: " + planId);
        return new AsyncResult<Void>(null);
    }

    planManager.changeStatus(planId, DeliveryPlanStatus.RUNNING);

    String objectIdentifier = plan.getObjectIdentifier();

    HttpClient client = httpsClientHelper.getHttpsClient(WrdzModule.ZMKD);

    HttpGet get = new HttpGet(zmkdConfiguration.getZmdObjectUrl(objectIdentifier));
    HttpResponse response = null;

    File digitalObjectFile;
    File workDir;

    try {

        planExecutor.setWait(planId, objectIdentifier);

        response = client.execute(get);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) {
            planExecutor.confirmWait(planId);
            return new AsyncResult<Void>(null);
        }

        planExecutor.clearWait(planId);

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            planManager.changeStatus(planId, DeliveryPlanStatus.ERROR);
            logger.error("Unexpected response: " + response.getStatusLine());
            return new AsyncResult<Void>(null);
        }

        workDir = new File(zmkdConfiguration.getWorkingDirectory(uuidGenerator.generateCacheFolderName()));
        workDir.mkdir();

        digitalObjectFile = httpsClientHelper.storeResponseEntity(workDir, response.getEntity(),
                response.getFirstHeader("Content-Disposition"));

        ZipUtility.unzip(digitalObjectFile, workDir);

    } catch (IOException e) {
        planExecutor.clearWait(planId);
        planManager.changeStatus(planId, DeliveryPlanStatus.ERROR);
        logger.error(e.getMessage(), e);
        return new AsyncResult<Void>(null);
    } finally {
        if (response != null) {
            EntityUtils.consumeQuietly(response.getEntity());
        }
    }

    DigitalObjectInfo objectInfo = reader.parseMets(workDir, METS_PATH);
    String clientLocation = null;

    try {
        for (ConversionPath conversion : plan.getConversionPaths()) {
            List<TransformationInfo> path = planExecutionParser.parseTransformationPath(conversion);
            planExecutionManager.transform(objectInfo, path);
        }
    } catch (InconsistentServiceDescriptionException e) {
        planManager.changeStatus(planId, DeliveryPlanStatus.ERROR);
        logger.error(e.getMessage(), e);
        return new AsyncResult<Void>(null);
    } catch (TransformationException e) {
        planManager.changeStatus(planId, DeliveryPlanStatus.ERROR);
        logger.error(e.getMessage(), e);
        return new AsyncResult<Void>(null);
    }
    try {
        DeliveryInfo deliveryInfo = planExecutionParser.parseDelivery(plan.getDelivery());
        clientLocation = planExecutionManager.deliver(objectInfo, deliveryInfo);
    } catch (InconsistentServiceDescriptionException e) {
        planManager.changeStatus(planId, DeliveryPlanStatus.ERROR);
        logger.error(e.getMessage(), e);
        return new AsyncResult<Void>(null);
    } catch (DeliveryException e) {
        planManager.changeStatus(planId, DeliveryPlanStatus.ERROR);
        logger.error(e.getMessage(), e);
        return new AsyncResult<Void>(null);
    }

    planManager.completePlan(planId, clientLocation);

    return new AsyncResult<Void>(null);
}