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:org.niord.core.message.MessageService.java

/**
 * Updates the given message./*from   ww w . j a  v a2 s.  c o m*/
 * <p>
 * Important: this function can not be used to change the status of the message.
 * For that, call {@code MessageService.updateStatus()}
 *
 * @param message the template for the message to update
 * @return the updated message
 */
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public Message updateMessage(Message message) throws Exception {

    Message original = findByUid(message.getUid());

    // Validate the message
    if (original == null) {
        throw new Exception("Message not an existing message");
    }

    // Register who last updated he message
    original.setLastUpdatedBy(userService.currentUser());

    original.setRevision(message.getRevision());

    // Validate various required fields
    if (message.getMessageSeries() == null) {
        throw new Exception("Message series not specified");
    }

    // Check that there is no attempt to update the status
    if (message.getStatus() != original.getStatus()) {
        throw new Exception("updateMessage() cannot change status");
    }

    if (message.getType() != null) {
        message.setMainType(message.getType().getMainType());
    }

    original.setMessageSeries(messageSeriesService.findBySeriesId(message.getMessageSeries().getSeriesId()));
    original.setNumber(message.getNumber());
    original.setShortId(message.getShortId());
    original.setType(message.getType());
    original.setMainType(message.getMainType());
    original.setThumbnailPath(message.getThumbnailPath());

    if (original.getMainType() != null && original.getMainType() != original.getMessageSeries().getMainType()) {
        throw new Exception("Invalid main-type for message " + original.getMainType());
    }

    // If a verified message is updated, it will become draft again
    if (original.getStatus() == Status.VERIFIED) {
        original.setStatus(Status.DRAFT);
    }

    original.setHorizontalDatum(message.getHorizontalDatum());

    // Substitute the Area with a persisted one
    original.setAreas(persistedList(Area.class, message.getAreas()));

    // Substitute the Categories with the persisted ones
    original.setCategories(persistedList(Category.class, message.getCategories()));

    // Substitute the Charts with the persisted ones
    original.setCharts(chartService.persistedCharts(message.getCharts()));

    original.setPublishDateFrom(message.getPublishDateFrom());
    original.setPublishDateTo(message.getPublishDateTo());
    original.setFollowUpDate(message.getFollowUpDate());

    original.getReferences().clear();
    message.getReferences().stream().map(this::updateReference).filter(Objects::nonNull)
            .forEach(original::addReference);

    original.setOriginalInformation(message.getOriginalInformation());

    original.getParts().clear();
    message.getParts().stream().map(this::updateMessagePart).filter(Objects::nonNull)
            .forEach(original::addPart);
    original.getParts().removeIf(part -> !part.partDefined());

    // Copy the localized description data
    original.copyDescsAndRemoveBlanks(message.getDescs());
    original.setAutoTitle(message.isAutoTitle());

    original.getAttachments().clear();
    message.getAttachments().stream().map(this::updateAttachment).filter(Objects::nonNull)
            .forEach(original::addAttachment);

    original.setSeparatePage(message.getSeparatePage());

    // For non-published messages, compute the area sort order based on associated area and message part geometry
    if (original.getStatus().isDraft()) {
        original.setAreaSortOrder(areaService.computeMessageAreaSortingOrder(original));
    }

    // Persist the message
    saveMessage(original);
    log.info("Updated message " + original);

    em.flush();
    return original;
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public int getConditionCount(int alertDefinitionId) {
    Query query = entityManager.createQuery("" //
            + "SELECT COUNT(ac) " //
            + "  FROM AlertDefinition ad " //
            + "  JOIN ad.conditions ac " //
            + " WHERE ad.id = :alertDefinitionId");
    query.setParameter("alertDefinitionId", alertDefinitionId);
    long conditionCount = (Long) query.getSingleResult();
    return (int) conditionCount;
}

From source file:org.rhq.enterprise.server.configuration.ConfigurationManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public ConfigurationUpdateResponse executePluginConfigurationUpdate(PluginConfigurationUpdate update) {
    Resource resource = update.getResource();
    Configuration configuration = update.getConfiguration();
    configuration = configuration.deepCopy(false);

    ConfigurationUpdateResponse response = null;

    try {/*ww  w .  jav  a  2 s. c  o  m*/
        // now let's tell the agent to actually update the resource component's plugin configuration
        AgentClient agentClient = this.agentManager.getAgentClient(resource.getAgent());

        agentClient.getDiscoveryAgentService().updatePluginConfiguration(resource.getId(), configuration);
        try {
            agentClient.getDiscoveryAgentService().executeServiceScanDeferred();
        } catch (Exception e) {
            log.warn("Failed to execute service scan - cannot detect children of the newly connected resource ["
                    + resource + "]", e);
        }

        response = new ConfigurationUpdateResponse(update.getId(), null, ConfigurationUpdateStatus.SUCCESS,
                null);
    } catch (Exception e) {
        response = new ConfigurationUpdateResponse(update.getId(), null, e);
    }

    return response;
}

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

@SuppressWarnings("unused")
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
//@TransactionTimeout( 60 * 60 )
private int _calculateAutoBaselinesDELETE_HQL(long startTime, long endTime) throws Exception {
    Query query = entityManager.createNamedQuery(MeasurementBaseline.QUERY_DELETE_EXISTING_AUTOBASELINES);

    query.setParameter("startTime", startTime);
    query.setParameter("endTime", endTime);

    int rowsModified = query.executeUpdate();

    return rowsModified;
}

From source file:org.rhq.enterprise.server.resource.ResourceManagerBean.java

@SuppressWarnings("unchecked")
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public List<Integer> uninventoryResource(Subject user, int resourceId) {
    //        Resource resource = resourceManager.getResourceTree(resourceId, true);
    Resource resource = entityManager.find(Resource.class, resourceId);
    if (resource == null) {
        log.info("Delete resource not possible, as resource with id [" + resourceId + "] was not found");
        return Collections.emptyList(); // Resource not found. TODO give a nice message to the user
    }//from w  ww.jav a  2 s  .  co m

    // make sure the user is authorized to delete this resource (which implies you can delete all its children)
    // TODO: There is a pretty good argument for this being replaced with MANAGE_INVENTORY.  It takes an
    // inventory manager to import resources, so why not to remove them?  But, since no one has complained
    // we're timid about making a change that may hamstring existing setups. 
    if (!authorizationManager.hasResourcePermission(user, Permission.DELETE_RESOURCE, resourceId)) {
        throw new PermissionException(
                "You do not have permission to uninventory resource [" + resourceId + "]");
    }

    // if the resource has no parent, its a top root resource and its agent should be purged too
    // test code does not always follow this rule, so catch and continue.
    Agent doomedAgent = null;
    if (resource.getParentResource() == null) {
        try {
            // note, this needs to be done before the marking because the agent reference is going to be set to null
            doomedAgent = agentManager.getAgentByResourceId(subjectManager.getOverlord(), resourceId);
        } catch (Exception e) {
            doomedAgent = null;
            log.warn("This warning should occur in TEST code only! " + e);
        }
    }

    AgentClient agentClient = null;
    try {
        // The test code does not always generate agents for the resources. Catch and log any problem but continue
        agentClient = agentManager.getAgentClient(subjectManager.getOverlord(), resourceId);
    } catch (Throwable t) {
        log.warn("No AgentClient found for resource [" + resource
                + "]. Unable to inform agent of inventory removal (this may be ok): " + t);
    }

    // since we delete the resource asynchronously now, we need to make sure we remove things that would cause
    // system side effects after markForDeletion completed but before the resource was actually removed from the DB
    Subject overlord = subjectManager.getOverlord();

    // delete the resource and all its children
    log.info("User [" + user + "] is marking resource [" + resource + "] for asynchronous uninventory");

    // set agent references null
    // foobar the resourceKeys
    // update the inventory status to UNINVENTORY
    Query toBeDeletedQuery = entityManager.createNamedQuery(Resource.QUERY_FIND_DESCENDANTS);
    toBeDeletedQuery.setParameter("resourceId", resourceId);
    List<Integer> toBeDeletedResourceIds = toBeDeletedQuery.getResultList();

    int i = 0;
    log.debug("== total size : " + toBeDeletedResourceIds.size());

    while (i < toBeDeletedResourceIds.size()) {
        int j = i + 1000;
        if (j > toBeDeletedResourceIds.size())
            j = toBeDeletedResourceIds.size();
        List<Integer> idsToDelete = toBeDeletedResourceIds.subList(i, j);
        log.debug("== Bounds " + i + ", " + j);

        boolean hasErrors = uninventoryResourcesBulkDelete(overlord, idsToDelete);
        if (hasErrors) {
            throw new IllegalArgumentException("Could not remove resources from their containing groups");
        }
        i = j;
    }

    // QUERY_MARK_RESOURCES_FOR_ASYNC_DELETION is an expensive recursive query
    // But luckily we have already (through such a recursive query above) determined the doomed resources
    //        Query markDeletedQuery = entityManager.createNamedQuery(Resource.QUERY_MARK_RESOURCES_FOR_ASYNC_DELETION);
    //        markDeletedQuery.setParameter("resourceId", resourceId);
    //        markDeletedQuery.setParameter("status", InventoryStatus.UNINVENTORIED);
    //        int resourcesDeleted = markDeletedQuery.executeUpdate();

    i = 0;
    int resourcesDeleted = 0;
    while (i < toBeDeletedResourceIds.size()) {
        int j = i + 1000;
        if (j > toBeDeletedResourceIds.size())
            j = toBeDeletedResourceIds.size();
        List<Integer> idsToDelete = toBeDeletedResourceIds.subList(i, j);

        Query markDeletedQuery = entityManager
                .createNamedQuery(Resource.QUERY_MARK_RESOURCES_FOR_ASYNC_DELETION_QUICK);
        markDeletedQuery.setParameter("resourceIds", idsToDelete);
        markDeletedQuery.setParameter("status", InventoryStatus.UNINVENTORIED);
        resourcesDeleted += markDeletedQuery.executeUpdate();
        i = j;
    }

    if (resourcesDeleted != toBeDeletedResourceIds.size()) {
        log.error("Tried to uninventory " + toBeDeletedResourceIds.size()
                + " resources, but actually uninventoried " + resourcesDeleted);
    }

    // still need to tell the agent about the removed resources so it stops avail reports
    if (agentClient != null) {
        try {
            agentClient.getDiscoveryAgentService().uninventoryResource(resourceId);
        } catch (Exception e) {
            log.warn(" Unable to inform agent of inventory removal for resource [" + resourceId + "]", e);
        }
    }

    if (doomedAgent != null) {
        agentManager.deleteAgent(doomedAgent);
    }

    return toBeDeletedResourceIds;
}

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

/**
 * Purge data older than a given time.//from  w  w w.  jav  a 2 s .c  o m
 */
// 60 minute timeout
@TransactionTimeout(60 * 60)
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public int purgeMeasurementInterval(String tableName, long purgeAfter, long purgeBefore) throws SQLException {
    Connection conn = null;
    PreparedStatement stmt = null;

    log.info("Begin purging data from table [" + tableName + "] between [" + TimeUtil.toString(purgeAfter)
            + "] and [" + TimeUtil.toString(purgeBefore) + "]");

    StopWatch watch = new StopWatch();
    int rows;
    try {
        conn = ((DataSource) ctx.lookup(DATASOURCE_NAME)).getConnection();

        String sql = "DELETE FROM " + tableName + " WHERE time_stamp >= ? AND time_stamp < ?";

        stmt = conn.prepareStatement(sql);
        stmt.setLong(1, purgeAfter);
        stmt.setLong(2, purgeBefore);

        rows = stmt.executeUpdate();
    } finally {
        JDBCUtil.safeClose(conn, stmt, null);
    }

    MeasurementMonitor.getMBean().incrementPurgeTime(watch.getElapsed());

    log.info("Finished purging data from table [" + tableName + "] between [" + TimeUtil.toString(purgeAfter)
            + "] and [" + TimeUtil.toString(purgeBefore) + "], [" + rows + "] rows removed in ["
            + ((watch.getElapsed()) / SECOND) + "] seconds");

    return rows;
}

From source file:org.rhq.enterprise.server.system.SystemManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void loadSystemConfigurationCacheInNewTx() {
    // this is used by our timer, so any exceptions coming out here doesn't throw away our timer
    loadSystemConfigurationCache();//from  w ww  .  ja v  a  2 s  .  c  om
}

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

@SuppressWarnings("unused")
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
//@TransactionTimeout( 60 * 60 )
private int _calculateAutoBaselinesINSERT_HQL(long startTime, long endTime, long computeTime) throws Exception {
    Query query = entityManager.createNamedQuery(MeasurementBaseline.QUERY_CALC_FIRST_AUTOBASELINE);

    //query.setParameter("computeTime", computeTime);
    query.setParameter("startTime", startTime);
    query.setParameter("endTime", endTime);

    int rowsModified = query.executeUpdate();

    return rowsModified;
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void purgeAllGroupAlertDefinitions(Subject subject, int resourceGroupId) {
    Integer[] groupAlertDefinitionIdsForResourceGroup = findGroupAlertDefinitionIds(resourceGroupId);
    removeGroupAlertDefinitions(subject, groupAlertDefinitionIdsForResourceGroup);
}

From source file:org.oscm.identityservice.bean.IdentityServiceBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void importUser(VOUserDetails user, String marketplaceId) throws NonUniqueBusinessKeyException,
        MailOperationException, ValidationException, UserRoleAssignmentException, ObjectNotFoundException {
    try {/*from  w w w .j  a  v  a  2  s.co m*/
        Marketplace marketplace = getMarketplace(marketplaceId);
        Organization organization = getOrganization(user.getOrganizationId());
        String password = new PasswordGenerator().generatePassword();
        addPlatformUser(user, organization, password, UserAccountStatus.PASSWORD_MUST_BE_CHANGED, true, true,
                marketplace, true);
    } catch (NonUniqueBusinessKeyException | MailOperationException | ValidationException
            | UserRoleAssignmentException e) {
        sessionCtx.setRollbackOnly();
        throw e;
    }
}