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.ResourceFactoryManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public CreateResourceHistory persistCreateHistory(Subject user, int parentResourceId, int resourceTypeId,
        String createResourceName, PackageVersion packageVersion, Configuration deploymentTimeConfiguration) {
    // Load relationships
    Resource parentResource = entityManager.getReference(Resource.class, parentResourceId);
    ResourceType resourceType = entityManager.getReference(ResourceType.class, resourceTypeId);

    // Persist and establish relationships
    // TODO: Note, InstalledPackage is set to null because it doesn't really make sense. An InstalledPackage
    // represents a backing package relationship between a Resource and a PackageVersion, not its parent.
    // I think it should probably be removed from the history entity. -jshaughn 9/1/09.
    CreateResourceHistory history = new CreateResourceHistory(parentResource, resourceType, user.getName(),
            (InstalledPackage) null);/*  w  w  w.  ja  v  a2  s .co  m*/
    history.setCreatedResourceName(createResourceName);
    history.setConfiguration(deploymentTimeConfiguration);
    history.setStatus(CreateResourceStatus.IN_PROGRESS);

    entityManager.persist(history);
    parentResource.addCreateChildResourceHistory(history);

    // Caller will need this
    parentResource.getAgent();

    return history;
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void addTraitData(Set<MeasurementDataTrait> data) {
    if ((data == null) || (data.isEmpty())) {
        return;//from ww  w  . ja va2 s.  com
    }

    Connection conn = null;
    PreparedStatement ps = null;
    try {
        conn = rhqDs.getConnection();
        ps = conn.prepareStatement(TRAIT_INSERT_STATEMENT);

        for (MeasurementDataTrait aData : data) {
            // time_stamp, schedule_id, value, schedule_id, schedule_id, value, value, value, value
            ps.setLong(1, aData.getTimestamp());
            ps.setInt(2, aData.getScheduleId());
            ps.setString(3, aData.getValue());
            ps.setInt(4, aData.getScheduleId());
            ps.setInt(5, aData.getScheduleId());
            ps.setString(6, aData.getValue());
            ps.setString(7, aData.getValue());
            ps.setString(8, aData.getValue());
            ps.setString(9, aData.getValue());
            ps.addBatch();
        }

        int[] res = ps.executeBatch();
        if (res.length != data.size()) {
            throw new MeasurementStorageException("Failure to store measurement trait data.");
            // It is expected that some of these batch updates didn't update anything as the previous value was the same
        }

        notifyAlertConditionCacheManager("mergeMeasurementReport",
                data.toArray(new MeasurementData[data.size()]));
    } catch (SQLException e) {
        log.warn("Failure saving measurement trait data:\n" + ThrowableUtil.getAllMessages(e));
    } catch (Exception e) {
        log.error("Error persisting trait data", e);
    } finally {
        JDBCUtil.safeClose(conn, ps, null);
    }
}

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

@RequiredPermission(Permission.MANAGE_INVENTORY)
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
// required for the recalculation thread
public void calculateGroupMembership(Subject subject, int groupDefinitionId)
        throws ResourceGroupDeleteException, GroupDefinitionDeleteException, GroupDefinitionNotFoundException,
        InvalidExpressionException, ResourceGroupUpdateException {
    /*/*from w ww.  j  a  v a 2  s  .co m*/
     * even though this method declares to throw it, it should never generate an InvalidExpressionException because
     * the definition's expression set was validated before it was persisted.  conceivably, if the group definition
     * is persisted without being passed to the validating updateGroupDefinition( GroupDefinition ) method, then it
     * could throw a validation exception.
     *
     * so, callers to this method should catch InvalidExpressionException just in case, and give the user a chance to
     * correct the expression set before attempting to calculate the effective group again.
     */

    long startTime = System.currentTimeMillis();

    GroupDefinition groupDefinition = getById(groupDefinitionId);
    groupDefinition.setLastCalculationTime(System.currentTimeMillis()); // we're calculating now

    ExpressionEvaluator evaluator = new ExpressionEvaluator();
    for (String expression : groupDefinition.getExpressionAsList()) {
        evaluator.addExpression(expression);
    }

    Collection<Integer> doomedResourceGroupIds = new ArrayList<Integer>();
    for (Integer managedGroupId : getManagedResourceGroupIdsForGroupDefinition(groupDefinitionId)) {
        doomedResourceGroupIds.add(managedGroupId);
    }

    for (ExpressionEvaluator.Result result : evaluator) {
        if (result == null) {
            /*
             * skip null result elements, which represent queries that returned some null element -- this could be
             * remedied by supporting "IS NULL" for parameter-replacement aside from just "= :bindArg" syntax
             */
            continue;
        }

        /*
         * do one group at a time, to help prevent xaction timeouts
         *
         * note: we don't need to pass the overlord here because all group definition / dynagroup functionality
         *       is hidden behind the MANAGE_INVENTORY permission, which is sufficient for all operations on a
         *       resource group including creation, deletion, and membership changes
         */
        Integer nextResourceGroupId = groupDefinitionManager.calculateGroupMembership_helper(subject,
                groupDefinitionId, result);

        /*
         * as a result of recalculation, the membership may have changed such that a group which was previously
         * marked as compatible now becomes a mixed group.  if that happens, then the GroupCategory needs to be
         * updated and any compatible group constructs need to be removed from this group.  the following method
         * will achieve both of those goals
         */
        resourceGroupManager.setResourceType(nextResourceGroupId);

        /*
         * remove all ids returned from the helper.  by the time we're done looping over all
         * ExpressionEvaluator.Result objects, the remaining objects in managedResourceGroupIds should represent
         * groups that no longer managed by this definition (either due to an inventory or expression change), and
         * are thus doomed
         */
        doomedResourceGroupIds.remove(nextResourceGroupId);
    }

    /*
     * and ids that are left over are doomed, but since deleting a resource group is related to the size of the
     * group, remove each group in it's own transaction
     *
     * note: we don't need to pass the overlord here because all group definition / dynagroup functionality
     *       is hidden behind the MANAGE_INVENTORY permission, which is sufficient for all operations on a
     *       resource group including creation, deletion, and membership changes
     */
    for (Integer doomedGroupId : doomedResourceGroupIds) {
        groupDefinitionManager.removeManagedResource_helper(subject, groupDefinitionId, doomedGroupId);
    }

    long endTime = System.currentTimeMillis();

    log.debug("calculateGroupMembership took " + (endTime - startTime) + " millis");
}

From source file:dk.dma.msinm.service.MessageService.java

/**
 * Updates the status of the given message
 *
 * @param messageId the id of the message
 * @param status    the status//from www  . ja v  a2 s.c o  m
 */
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public Message setStatus(Integer messageId, Status status) {
    Message msg = getByPrimaryKey(Message.class, messageId);

    // TODO: Proper publishing
    if (msg.getStatus() == Status.DRAFT && status == Status.PUBLISHED) {
        int number = newSeriesIdentifierNumber(msg.getType(), msg.getSeriesIdentifier().getAuthority(),
                msg.getSeriesIdentifier().getYear());
        msg.getSeriesIdentifier().setNumber(number);
    }

    msg.setStatus(status);

    // And let publishers have a say
    publishingService.setStatus(msg);

    msg = saveMessage(msg);

    // Broadcast the update
    sendStatusUpdate(msg);

    return msg;
}

From source file:org.rhq.enterprise.server.core.AgentManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void setAgentBackfilled(int agentId, boolean backfilled) {
    Query query = entityManager.createNamedQuery(Agent.QUERY_SET_AGENT_BACKFILLED);
    query.setParameter("agentId", agentId);
    query.setParameter("backfilled", backfilled);
    query.executeUpdate();//from  w  w w.j av a2  s.c o  m
}

From source file:org.rhq.enterprise.server.cloud.instance.ServerManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void beat() {
    Server server = getServer();//w  ww  . j a  v  a  2s .  c o  m
    server.setMtime(System.currentTimeMillis());

    // Handles server mode state changes 
    // note: this call should be fast. if not we need to break the heart beat into its own job
    establishCurrentServerMode();
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void insertCallTimeDataKeys(Set<CallTimeData> callTimeDataSet) {

    int[] results;
    String insertKeySql;/*w w w  .  j ava 2  s  . c  o  m*/
    PreparedStatement ps = null;
    Connection conn = null;

    try {
        conn = rhqDs.getConnection();
        DatabaseType dbType = DatabaseTypeFactory.getDatabaseType(conn);

        if (dbType instanceof Postgresql83DatabaseType) {
            Statement st = null;
            try {
                // Take advantage of async commit here
                st = conn.createStatement();
                st.execute("SET synchronous_commit = off");
            } finally {
                JDBCUtil.safeClose(st);
            }
        }

        if (dbType instanceof PostgresqlDatabaseType || dbType instanceof OracleDatabaseType
                || dbType instanceof H2DatabaseType) {
            String keyNextvalSql = JDBCUtil.getNextValSql(conn, "RHQ_calltime_data_key");
            insertKeySql = String.format(CALLTIME_KEY_INSERT_STATEMENT, keyNextvalSql);
        } else if (dbType instanceof SQLServerDatabaseType) {
            insertKeySql = CALLTIME_KEY_INSERT_STATEMENT_AUTOINC;
        } else {
            throw new IllegalArgumentException("Unknown database type, can't continue: " + dbType);
        }

        ps = conn.prepareStatement(insertKeySql);
        for (CallTimeData callTimeData : callTimeDataSet) {
            ps.setInt(1, callTimeData.getScheduleId());
            ps.setInt(3, callTimeData.getScheduleId());
            Set<String> callDestinations = callTimeData.getValues().keySet();
            for (String callDestination : callDestinations) {
                ps.setString(2, callDestination);
                ps.setString(4, callDestination);
                ps.addBatch();
            }
        }

        results = ps.executeBatch();

        int insertedRowCount = 0;
        for (int i = 0; i < results.length; i++) {
            if (((results[i] < 0) || (results[i] > 1)) && (results[i] != -2)) // oracle returns -2 because it can't count updated rows
            {
                throw new MeasurementStorageException("Failed to insert call-time data key rows - result ["
                        + results[i] + "] for batch command [" + i + "] is less than 0 or greater than 1.");
            }

            insertedRowCount += results[i] == -2 ? 1 : results[i]; // If Oracle returns -2, just count 1 row
        }

        log.debug(
                "Inserted new call-time data key rows for " + ((insertedRowCount >= 0) ? insertedRowCount : "?")
                        + " out of " + results.length + " reported key-value pairs.");
    } catch (SQLException e) {
        logSQLException("Failed to persist call-time data keys", e);
    } catch (Throwable t) {
        log.error("Failed to persist call-time data keys", t);
    } finally {
        JDBCUtil.safeClose(conn, ps, null);
    }
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void deleteStudyInNewTransaction(Long studyId, boolean deleteFromIndex) {
    deleteStudy(studyId, deleteFromIndex);
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public BooleanExpression getConditionExpression(int alertDefinitionId) {
    Query query = entityManager.createQuery("" //
            + "SELECT ad.conditionExpression " //
            + "  FROM AlertDefinition ad " //
            + " WHERE ad.id = :alertDefinitionId");
    query.setParameter("alertDefinitionId", alertDefinitionId);
    BooleanExpression expression = (BooleanExpression) query.getSingleResult();
    return expression;
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public DeleteResourceHistory persistDeleteHistory(Subject user, int resourceId) {
    // Load relationships
    Resource resource = entityManager.find(Resource.class, resourceId);

    // Persist and establish relationships
    DeleteResourceHistory history = new DeleteResourceHistory(resource, user.getName());
    history.setStatus(DeleteResourceStatus.IN_PROGRESS);

    entityManager.persist(history);//from  w w  w  . j  ava 2s .c  o  m
    resource.addDeleteResourceHistory(history);

    // Caller will need this
    resource.getAgent();

    return history;
}