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.rhq.enterprise.server.resource.ResourceManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public boolean bulkNativeQueryDeleteInNewTransaction(Subject subject, String nativeQueryString,
        List<Integer> resourceIds) {
    if (!authorizationManager.isOverlord(subject)) {
        throw new IllegalArgumentException("Only the overlord can execute arbitrary native query strings");
    }/*from  ww  w.j  av  a  2s  . co  m*/

    try {
        Query nativeQuery = entityManager.createNativeQuery(nativeQueryString);
        nativeQuery.setParameter("resourceIds", resourceIds);
        nativeQuery.executeUpdate();
    } catch (Throwable t) {
        if (log.isDebugEnabled()) {
            log.error("Bulk native query delete error for '" + nativeQueryString + "' for " + resourceIds, t);
        } else {
            log.error("Bulk native query delete error for '" + nativeQueryString + "' for " + resourceIds + ": "
                    + t.getMessage());
        }
        return true; // had errors
    }
    return false;
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public boolean bulkNamedQueryDeleteInNewTransaction(Subject subject, String namedQuery,
        List<Integer> resourceIds) {
    if (!authorizationManager.isOverlord(subject)) {
        throw new IllegalArgumentException("Only the overlord can execute arbitrary named query strings");
    }/*from w w w .  j a v  a  2 s .co m*/

    try {
        Query nativeQuery = entityManager.createNamedQuery(namedQuery);
        nativeQuery.setParameter("resourceIds", resourceIds);
        nativeQuery.executeUpdate();
    } catch (Throwable t) {
        if (log.isDebugEnabled()) {
            log.error("Bulk named query delete error for '" + namedQuery + "' for " + resourceIds, t);
        } else {
            log.error("Bulk named query delete error for '" + namedQuery + "' for " + resourceIds + ": "
                    + t.getMessage());
        }
        return true; // had errors
    }
    return false;
}

From source file:org.rhq.enterprise.server.resource.group.ResourceGroupManagerBean.java

@RequiredPermission(Permission.MANAGE_INVENTORY)
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void removeAllResourcesFromGroup(Subject subject, int groupId) throws ResourceGroupDeleteException {
    Connection conn = null;/* w  ww .  j a v  a2 s .c o  m*/
    PreparedStatement explicitStatement = null;
    PreparedStatement implicitStatement = null;
    try {
        conn = rhqDs.getConnection();

        explicitStatement = conn
                .prepareStatement("delete from rhq_resource_group_res_exp_map where resource_group_id = ?");
        implicitStatement = conn
                .prepareStatement("delete from rhq_resource_group_res_imp_map where resource_group_id = ?");

        explicitStatement.setInt(1, groupId);
        implicitStatement.setInt(1, groupId);

        explicitStatement.executeUpdate();
        implicitStatement.executeUpdate();
    } catch (SQLException sqle) {
        log.error("Error removing group resources", sqle);
        throw new ResourceGroupDeleteException("Error removing group resources: " + sqle.getMessage());
    } finally {
        JDBCUtil.safeClose(explicitStatement);
        JDBCUtil.safeClose(implicitStatement);
        JDBCUtil.safeClose(conn);
    }
}

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

/**
 * This is the core of the alert sending process. For each AlertNotification that is hanging
 * on the alerts definition, the sender is instantiated and its send() method called. If a sender
 * returns a list of email addresses, those will be collected and sent at the end.
 * @param alert the fired alert/*from  w ww.  j  a  v a2 s  . c  o  m*/
 */
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void sendAlertNotifications(Alert alert) {
    /*
     * make this method public in case we show the notification failure to the user in the UI in the future and want
     * to give them some way to explicitly try to re-send the notification for some client-side auditing purposes
     */
    try {
        if (log.isDebugEnabled()) {
            log.debug("Sending alert notifications for " + alert.toSimpleString() + "...");
        }
        List<AlertNotification> alertNotifications = alert.getAlertDefinition().getAlertNotifications();

        if (alertNotifications != null && alertNotifications.size() > 0) {
            AlertSenderPluginManager alertSenderPluginManager = getAlertPluginManager();

            for (AlertNotification alertNotification : alertNotifications) {
                AlertNotificationLog notificationLog = null;

                String senderName = alertNotification.getSenderName();
                if (senderName == null) {
                    notificationLog = new AlertNotificationLog(alert, senderName, ResultState.FAILURE,
                            "Sender '" + senderName + "' is not defined");
                } else {

                    AlertSender<?> notificationSender = alertSenderPluginManager
                            .getAlertSenderForNotification(alertNotification);
                    if (notificationSender == null) {
                        notificationLog = new AlertNotificationLog(alert, senderName, ResultState.FAILURE,
                                "Failed to obtain a sender with given name");
                    } else {
                        try {
                            SenderResult result = notificationSender.send(alert);
                            if (log.isDebugEnabled()) {
                                log.debug(result);
                            }

                            if (result == null) {
                                notificationLog = new AlertNotificationLog(alert, senderName,
                                        ResultState.UNKNOWN, "Sender did not return any result");
                            } else {
                                notificationLog = new AlertNotificationLog(alert, senderName, result);
                            }
                        } catch (Throwable t) {
                            log.error("Notification processing terminated abruptly" + t.getMessage());
                            notificationLog = new AlertNotificationLog(alert, senderName, ResultState.FAILURE,
                                    "Notification processing terminated abruptly, cause: " + t.getMessage());
                        }
                    }
                }

                entityManager.persist(notificationLog);
                alert.addAlertNotificatinLog(notificationLog);
            }
        }
    } catch (Throwable t) {
        log.error("Failed to send all notifications for " + alert.toSimpleString(), t);
    }
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void purgeInternals(int alertDefinitionId) {
    try {/*  w ww  .j  a v a 2 s.c  o  m*/
        Query alertDampeningEventPurgeQuery = entityManager
                .createNamedQuery(AlertDampeningEvent.QUERY_DELETE_BY_ALERT_DEFINITION_ID);
        Query unmatchedAlertConditionLogPurgeQuery = entityManager
                .createNamedQuery(AlertConditionLog.QUERY_DELETE_UNMATCHED_BY_ALERT_DEFINITION_ID);

        alertDampeningEventPurgeQuery.setParameter("alertDefinitionId", alertDefinitionId);
        unmatchedAlertConditionLogPurgeQuery.setParameter("alertDefinitionId", alertDefinitionId);

        int alertDampeningEventPurgeCount = alertDampeningEventPurgeQuery.executeUpdate();
        int unmatchedAlertConditionLogPurgeCount = unmatchedAlertConditionLogPurgeQuery.executeUpdate();

        if (LOG.isDebugEnabled()) {
            LOG.debug("Update to AlertDefinition[id=" + alertDefinitionId
                    + " caused a purge of internal, dampening constructs.");
            if (alertDampeningEventPurgeCount > 0) {
                LOG.debug("Removed " + alertDampeningEventPurgeCount + " AlertDampeningEvent"
                        + (alertDampeningEventPurgeCount == 1 ? "" : "s"));
            }
            if (unmatchedAlertConditionLogPurgeCount > 0) {
                LOG.debug("Removed " + unmatchedAlertConditionLogPurgeCount + " unmatched AlertConditionLog"
                        + (unmatchedAlertConditionLogPurgeCount == 1 ? "" : "s"));
            }
        }
    } catch (Throwable t) {
        LOG.debug("Could not purge internal alerting constructs for: " + alertDefinitionId, t);
    }
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void updateLastAvailabilityReport(int agentId) {
    // should we catch exceptions here, or allow them to bubble up and be caught?

    /*/*from   w ww.j av a  2  s  . co  m*/
     * since we already know we have to update the agent row with the last avail report time, might as well
     * set the backfilled to false here (as opposed to called agentManager.setBackfilled(agentId, false)
     */
    String updateStatement = "" //
            + "UPDATE Agent " //
            + "   SET lastAvailabilityReport = :reportTime, backFilled = FALSE " //
            + " WHERE id = :agentId ";

    Query query = entityManager.createQuery(updateStatement);
    query.setParameter("reportTime", System.currentTimeMillis());
    query.setParameter("agentId", agentId);

    query.executeUpdate();
}

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

@SuppressWarnings("unchecked")
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void updateAgentResourceAvailabilities(int agentId, AvailabilityType platformAvailType,
        AvailabilityType childAvailType) {

    platformAvailType = (null == platformAvailType) ? AvailabilityType.UNKNOWN : platformAvailType;
    childAvailType = (null == childAvailType) ? AvailabilityType.UNKNOWN : childAvailType;

    // get the platform resource as well as all child resources not already at childAvailType (since these are the
    // ones we need to change)
    Query query = entityManager/*from  ww  w.j av a 2 s .  c o  m*/
            .createNamedQuery(Availability.FIND_PLATFORM_COMPOSITE_BY_AGENT_AND_NONMATCHING_TYPE);
    query.setParameter("agentId", agentId);
    query.setParameter("availabilityType", platformAvailType);
    // should be 0 or 1 entry
    List<ResourceIdWithAvailabilityComposite> platformResourcesWithStatus = query.getResultList();

    // get the platform resource as well as all child resources not disabled and not already at childAvailType
    // (since these are the ones we need to change)
    query = entityManager.createNamedQuery(Availability.FIND_CHILD_COMPOSITE_BY_AGENT_AND_NONMATCHING_TYPE);
    query.setParameter("agentId", agentId);
    query.setParameter("availabilityType", childAvailType);
    query.setParameter("disabled", AvailabilityType.DISABLED);
    List<ResourceIdWithAvailabilityComposite> resourcesWithStatus = query.getResultList();

    // The above queries only return resources if they have at least one row in Availability.
    // This may be a problem in the future, and may need to be fixed.
    // If a resource has 0 rows of availability, then it is by definition "unknown". If,
    // availabilityType is null, we don't have to do anything since the unknown state hasn't changed.
    // If this method is told to set all agent resources to something of other than unknown (null)
    // availability, then we may need to completely rethink the query we do above so it returns composite
    // objects for all resources, even those that have 0 rows of availability.  Remember though, that once
    // we get an availability report from an agent, a resource will have at least 1 availability row.  So,
    // a resource should rarely have 0 avail rows; if it does, it normally gets one within a minute
    // (since the agent sends avail reports every 60 seconds or so by default).  So this problem might not
    // be as bad as first thought.

    if (log.isDebugEnabled()) {
        log.debug("Agent #[" + agentId + "] is going to have [" + resourcesWithStatus.size()
                + "] resources backfilled with [" + childAvailType.getName() + "]");
    }

    Date now = new Date();

    int newAvailsSize = platformResourcesWithStatus.size() + resourcesWithStatus.size();
    List<Availability> newAvailabilities = new ArrayList<Availability>(newAvailsSize);

    // if the platform is being set to a new status handle it now
    if (!platformResourcesWithStatus.isEmpty()) {
        Availability newAvailabilityInterval = getNewInterval(platformResourcesWithStatus.get(0), now,
                platformAvailType);
        if (newAvailabilityInterval != null) {
            newAvailabilities.add(newAvailabilityInterval);
        }

        resourceAvailabilityManager.updateAgentResourcesLatestAvailability(agentId, platformAvailType, true);
    }

    // for those resources that have a current availability status that is different, change them       
    for (ResourceIdWithAvailabilityComposite record : resourcesWithStatus) {
        Availability newAvailabilityInterval = getNewInterval(record, now, childAvailType);
        if (newAvailabilityInterval != null) {
            newAvailabilities.add(newAvailabilityInterval);
        }
    }

    resourceAvailabilityManager.updateAgentResourcesLatestAvailability(agentId, childAvailType, false);

    // To handle backfilling process, which will mark them unknown
    notifyAlertConditionCacheManager("setAllAgentResourceAvailabilities",
            newAvailabilities.toArray(new Availability[newAvailabilities.size()]));

    if (log.isDebugEnabled()) {
        log.debug("Resources for agent #[" + agentId + "] have been fully backfilled.");
    }

    return;
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public ContentServiceRequest createRemoveRequest(int resourceId, String username, int[] installedPackageIds,
        String requestNotes) {//  w w w. j a  va  2s  . c o m
    Resource resource = entityManager.find(Resource.class, resourceId);

    ContentServiceRequest persistedRequest = new ContentServiceRequest(resource, username,
            ContentRequestType.DELETE);
    persistedRequest.setStatus(ContentRequestStatus.IN_PROGRESS);
    persistedRequest.setNotes(requestNotes);

    long timestamp = System.currentTimeMillis();

    for (int installedPackageId : installedPackageIds) {
        // Load the InstalledPackage to get its package version for the relationship
        InstalledPackage ip = entityManager.find(InstalledPackage.class, installedPackageId);
        PackageVersion packageVersion = ip.getPackageVersion();

        // Create the history entity
        InstalledPackageHistory history = new InstalledPackageHistory();
        history.setContentServiceRequest(persistedRequest);
        history.setPackageVersion(packageVersion);
        history.setResource(resource);
        history.setStatus(InstalledPackageHistoryStatus.BEING_DELETED);
        history.setTimestamp(timestamp);

        persistedRequest.addInstalledPackageHistory(history);
    }

    entityManager.persist(persistedRequest);

    return persistedRequest;
}

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

@RequiredPermission(Permission.MANAGE_REPOSITORIES)
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@TransactionTimeout(45 * 60)/*w  ww.ja  va 2  s  .co  m*/
public void downloadDistributionBits(Subject subject, ContentSource contentSource) {
    try {
        log.debug("downloadDistributionBits invoked");
        DistributionManagerLocal distManager = LookupUtil.getDistributionManagerLocal();
        ContentServerPluginContainer pc = ContentManagerHelper.getPluginContainer();
        int contentSourceId = contentSource.getId();
        ContentProviderManager cpMgr = pc.getAdapterManager();
        ContentProvider provider = cpMgr.getIsolatedContentProvider(contentSource.getId());
        if (!(provider instanceof DistributionSource)) {
            return;
        }

        DistributionSource distSource = (DistributionSource) provider;

        //
        // Following same sort of workaround done in ContentProviderManager for synchronizeContentProvider
        // Assume this will need to be updated when we place syncing in repo layer
        //
        RepoCriteria reposForContentSource = new RepoCriteria();
        reposForContentSource.addFilterContentSourceIds(contentSourceId);
        reposForContentSource.addFilterCandidate(false); // Don't sync distributions for candidates
        Subject overlord = LookupUtil.getSubjectManager().getOverlord();
        List<Repo> repos = repoManager.findReposByCriteria(overlord, reposForContentSource);
        log.debug("downloadDistributionBits found " + repos.size()
                + " repos associated with this contentSourceId " + contentSourceId);
        for (Repo repo : repos) {
            log.debug(
                    "downloadDistributionBits operating on repo: " + repo.getName() + " id = " + repo.getId());
            // Look up Distributions associated with this ContentSource.
            PageControl pageControl = PageControl.getUnlimitedInstance();
            log.debug("Looking up existing distributions for repoId: " + repo.getId());
            List<Distribution> dists = repoManager.findAssociatedDistributions(overlord, repo.getId(),
                    pageControl);
            log.debug("Found " + dists.size() + " Distributions for repoId " + repo.getId());

            for (Distribution dist : dists) {
                log.debug("Looking up DistributionFiles for dist: " + dist);
                List<DistributionFile> distFiles = distManager.getDistributionFilesByDistId(dist.getId());
                log.debug("Found " + distFiles.size() + " DistributionFiles");
                for (DistributionFile dFile : distFiles) {
                    String relPath = dist.getBasePath() + "/" + dFile.getRelativeFilename();
                    File outputFile = getDistLocalFileAndCreateParentDir(dist.getLabel(), relPath);
                    log.debug("Checking if file exists at: " + outputFile.getAbsolutePath());
                    if (outputFile.exists()) {
                        log.debug("File " + outputFile.getAbsolutePath() + " exists, checking md5sum");
                        String expectedMD5 = (dFile.getMd5sum() != null) ? dFile.getMd5sum()
                                : "<unspecified MD5>";
                        String actualMD5 = MessageDigestGenerator.getDigestString(outputFile);
                        if (!expectedMD5.trim().toLowerCase().equals(actualMD5.toLowerCase())) {
                            log.error("Expected [" + expectedMD5 + "] versus actual [" + actualMD5
                                    + "] md5sums for file " + outputFile.getAbsolutePath() + " do not match.");
                            log.error("Need to re-fetch file.  Will download from DistributionSource"
                                    + " and overwrite local file.");
                        } else {
                            log.info(outputFile + " exists and md5sum matches [" + actualMD5
                                    + "] no need to re-download");
                            continue; // skip the download from bitsStream
                        }
                    }
                    log.debug("Attempting download of " + dFile.getRelativeFilename() + " from contentSourceId "
                            + contentSourceId);
                    String remoteFetchLoc = distSource.getDistFileRemoteLocation(repo.getName(),
                            dist.getLabel(), dFile.getRelativeFilename());
                    InputStream bitsStream = pc.getAdapterManager().loadDistributionFileBits(contentSourceId,
                            remoteFetchLoc);
                    StreamUtil.copy(bitsStream, new FileOutputStream(outputFile), true);
                    bitsStream = null;
                    log.debug("DistributionFile has been downloaded to: " + outputFile.getAbsolutePath());
                }
            }
        }
    } catch (Throwable t) {
        log.error(t);
        throw new RuntimeException(t);
    }
}

From source file:org.ejbca.core.ejb.services.ServiceSessionBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@Override/*from  ww  w  .  j  av  a  2 s.  c o  m*/
public Map<Integer, Long> getNewServiceTimeouts(HashSet<Serializable> existingTimers) {
    Map<Integer, Long> ret = new HashMap<Integer, Long>();
    HashMap<Integer, String> idToNameMap = getServiceIdToNameMap();
    Collection<Integer> allServices = idToNameMap.keySet();
    Iterator<Integer> iter2 = allServices.iterator();
    while (iter2.hasNext()) {
        Integer id = iter2.next();
        ServiceData htp = serviceDataSession.findById(id);
        if (htp != null) {
            if (!existingTimers.contains(id)) {
                ServiceConfiguration serviceConfiguration = htp.getServiceConfiguration();
                IWorker worker = getWorker(serviceConfiguration, idToNameMap.get(id), htp.getRunTimeStamp(),
                        htp.getNextRunTimeStamp());
                if (worker != null && serviceConfiguration.isActive()
                        && worker.getNextInterval() != IInterval.DONT_EXECUTE) {
                    ret.put(id, Long.valueOf((worker.getNextInterval()) * 1000));
                }
            }
        } else {
            // Service does not exist, strange, but no panic.
            log.debug("Can not find service with id " + id);
        }
    }
    return ret;
}