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.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void initializeAndUpgradeCA(Integer caid) throws CADoesntExistsException {
    caSession.getCAInfoInternal(caid);/*  ww w .  ja v a2  s.  c o  m*/
}

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

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void resetInNewTransaction() {
    for (StorageNode storageNode : getClusterNodes()) {
        storageNode.setErrorMessage(null);
        storageNode.setFailedOperation(null);
    }//  w  ww .  j  a  v  a 2s.com
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void insertCallTimeDataValues(Set<CallTimeData> callTimeDataSet) {
    int[] results;
    String insertValueSql;/*from w w w . j av  a2  s  .co  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 valueNextvalSql = JDBCUtil.getNextValSql(conn, "RHQ_calltime_data_value");
            insertValueSql = String.format(CALLTIME_VALUE_INSERT_STATEMENT, valueNextvalSql);
        } else if (dbType instanceof SQLServerDatabaseType) {
            insertValueSql = CALLTIME_VALUE_INSERT_STATEMENT_AUTOINC;
        } else {
            throw new IllegalArgumentException("Unknown database type, can't continue: " + dbType);
        }

        ps = conn.prepareStatement(insertValueSql);
        for (CallTimeData callTimeData : callTimeDataSet) {
            ps.setInt(7, callTimeData.getScheduleId());
            Set<String> callDestinations = callTimeData.getValues().keySet();
            for (String callDestination : callDestinations) {
                CallTimeDataValue callTimeDataValue = callTimeData.getValues().get(callDestination);
                ps.setLong(1, callTimeDataValue.getBeginTime());
                ps.setLong(2, callTimeDataValue.getEndTime());
                ps.setDouble(3, callTimeDataValue.getMinimum());
                ps.setDouble(4, callTimeDataValue.getMaximum());
                ps.setDouble(5, callTimeDataValue.getTotal());
                ps.setLong(6, callTimeDataValue.getCount());
                ps.setString(8, callDestination);
                ps.addBatch();
            }
        }

        results = ps.executeBatch();

        int insertedRowCount = 0;
        for (int i = 0; i < results.length; i++) {
            if ((results[i] != 1) && (results[i] != -2)) // Oracle likes to return -2 becuase it doesn't track batch update counts
            {
                throw new MeasurementStorageException("Failed to insert call-time data value rows - result ["
                        + results[i] + "] for batch command [" + i + "] does not equal 1.");
            }

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

        notifyAlertConditionCacheManager("insertCallTimeDataValues",
                callTimeDataSet.toArray(new CallTimeData[callTimeDataSet.size()]));

        if (insertedRowCount > 0) {
            MeasurementMonitor.getMBean().incrementCalltimeValuesInserted(insertedRowCount);

            log.debug("Inserted " + insertedRowCount + " call-time data value rows.");
        }

    } catch (SQLException e) {
        logSQLException("Failed to persist call-time data values", e);
    } catch (Throwable t) {
        log.error("Failed to persist call-time data values", t);
    } 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)
public Integer calculateGroupMembership_helper(Subject overlord, int groupDefinitionId,
        ExpressionEvaluator.Result result) throws ResourceGroupDeleteException,
        GroupDefinitionNotFoundException, GroupDefinitionNotFoundException {
    long startTime = System.currentTimeMillis();

    GroupDefinition groupDefinition = getById(groupDefinitionId);

    String groupByClause = result.getGroupByClause();
    ResourceGroup resourceGroup = resourceGroupManager
            .getByGroupDefinitionAndGroupByClause(groupDefinition.getId(), groupByClause);
    int resourceGroupId = 0;
    if (resourceGroup == null) {
        String newDynamicGroupName = getDynamicGroupName(groupDefinition.getName(), groupByClause);

        resourceGroup = new ResourceGroup(newDynamicGroupName);
        resourceGroupId = resourceGroupManager.createResourceGroup(overlord, resourceGroup).getId();

        resourceGroup.setRecursive(groupDefinition.isRecursive());
        resourceGroup.setGroupByClause(groupByClause);
        groupDefinition.addResourceGroup(resourceGroup);
    } else {/*from  ww w  . j ava2 s . c o  m*/
        resourceGroupId = resourceGroup.getId();
    }

    /*
     * group additions/deletions are actions made to the explicit group, the implicit group is modified (based on
     * the recursive bit) by the existing code in the resourceGroupManager
     *
     * use resourceManager.getExplicitResourceIdsByResourceGroup instead of resourceGroup.getExplicitResources to keep
     * the data we need to pull across the line from the database as small as possible
     */
    Collection<Integer> existingResourceIds = resourceManager
            .findExplicitResourceIdsByResourceGroup(resourceGroup.getId());

    Set<Integer> idsToAdd = new HashSet<Integer>(result.getData());
    idsToAdd.removeAll(existingResourceIds);

    Set<Integer> idsToRemove = new HashSet<Integer>(existingResourceIds);
    idsToRemove.removeAll(result.getData());

    resourceGroupManager.addResourcesToGroup(overlord, resourceGroupId, ArrayUtils.unwrapCollection(idsToAdd));
    resourceGroupManager.removeResourcesFromGroup(overlord, resourceGroupId,
            ArrayUtils.unwrapCollection(idsToRemove));

    long endTime = System.currentTimeMillis();

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

    return resourceGroupId;
}

From source file:org.meveo.service.billing.impl.InvoiceService.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void createAgregatesAndInvoice(BillingAccount billingAccount, Long billingRunId, User currentUser)
        throws BusinessException, Exception {
    log.debug("createAgregatesAndInvoice tx status={}", txReg.getTransactionStatus());
    EntityManager em = getEntityManager();
    BillingRun billingRun = em.find(BillingRun.class, billingRunId);
    em.refresh(billingRun);/*w  w  w.  j  av  a  2 s  .c  o  m*/
    try {
        billingAccount = em.find(billingAccount.getClass(), billingAccount.getId());
        em.refresh(billingAccount);
        currentUser = em.find(currentUser.getClass(), currentUser.getId());
        em.refresh(currentUser);

        Long startDate = System.currentTimeMillis();
        BillingCycle billingCycle = billingRun.getBillingCycle();
        if (billingCycle == null) {
            billingCycle = billingAccount.getBillingCycle();
        }
        if (billingCycle == null) {
            throw new BusinessException("Cant find the billing cycle");
        }
        InvoiceType invoiceType = billingCycle.getInvoiceType();
        if (invoiceType == null) {
            invoiceType = invoiceTypeService.getDefaultCommertial(currentUser);
        }
        Invoice invoice = new Invoice();
        invoice.setInvoiceType(invoiceType);
        invoice.setBillingAccount(billingAccount);
        invoice.setBillingRun(billingRun);
        invoice.setAuditable(billingRun.getAuditable());
        invoice.setProvider(billingRun.getProvider());
        // ticket 680
        Date invoiceDate = billingRun.getInvoiceDate();
        invoice.setInvoiceDate(invoiceDate);

        Integer delay = billingCycle.getDueDateDelay();
        Date dueDate = invoiceDate;
        if (delay != null) {
            dueDate = DateUtils.addDaysToDate(invoiceDate, delay);
        }
        invoice.setDueDate(dueDate);

        PaymentMethodEnum paymentMethod = billingAccount.getPaymentMethod();
        if (paymentMethod == null) {
            paymentMethod = billingAccount.getCustomerAccount().getPaymentMethod();
        }
        invoice.setPaymentMethod(paymentMethod);
        invoice.setProvider(billingRun.getProvider());

        em.persist(invoice);

        // create(invoice, currentUser, currentUser.getProvider());
        log.debug("created invoice entity with id={},  tx status={}, em open={}", invoice.getId(),
                txReg.getTransactionStatus(), em.isOpen());
        ratedTransactionService.createInvoiceAndAgregates(billingAccount, invoice,
                billingRun.getLastTransactionDate(), currentUser);
        log.debug("created aggregates tx status={}, em open={}", txReg.getTransactionStatus(), em.isOpen());
        em.joinTransaction();

        if (billingRun.getProvider().isDisplayFreeTransacInInvoice()) {
            em.createNamedQuery("RatedTransaction.updateInvoicedDisplayFree")
                    .setParameter("billingAccount", billingAccount)
                    .setParameter("lastTransactionDate", billingRun.getLastTransactionDate())
                    .setParameter("billingRun", billingRun).setParameter("invoice", invoice).executeUpdate();
        } else {
            em.createNamedQuery("RatedTransaction.updateInvoiced")
                    .setParameter("billingAccount", billingAccount)
                    .setParameter("lastTransactionDate", billingRun.getLastTransactionDate())
                    .setParameter("billingRun", billingRun).setParameter("invoice", invoice).executeUpdate();

        }

        StringBuffer num1 = new StringBuffer("000000000");
        num1.append(invoice.getId() + "");
        String invoiceNumber = num1.substring(num1.length() - 9);
        int key = 0;

        for (int i = 0; i < invoiceNumber.length(); i++) {
            key = key + Integer.parseInt(invoiceNumber.substring(i, i + 1));
        }

        invoice.setTemporaryInvoiceNumber(invoiceNumber + "-" + key % 10);
        // getEntityManager().merge(invoice);
        Long endDate = System.currentTimeMillis();

        log.info("createAgregatesAndInvoice BR_ID=" + billingRun.getId() + ", BA_ID=" + billingAccount.getId()
                + ", Time en ms=" + (endDate - startDate));
    } catch (Exception e) {
        log.error("Error for BA=" + billingAccount.getCode() + " : ", e);

        RejectedBillingAccount rejectedBA = new RejectedBillingAccount(billingAccount, billingRun,
                e.getMessage());
        rejectedBillingAccountService.create(rejectedBA, currentUser);
    }
}

From source file:org.rhq.enterprise.server.plugin.ServerPluginManagerBean.java

@RequiredPermission(Permission.MANAGE_SETTINGS)
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void setServerPluginEnabledFlag(Subject subject, int pluginId, boolean enabled) throws Exception {
    Query q = entityManager.createNamedQuery(ServerPlugin.UPDATE_PLUGIN_ENABLED_BY_ID);
    q.setParameter("id", pluginId);
    q.setParameter("enabled", Boolean.valueOf(enabled));
    q.executeUpdate();//from  ww  w . jav  a2  s .c o  m
    log.info((enabled ? "Enabling" : "Disabling") + " server plugin [" + pluginId + "]");
    return;
}

From source file:org.rhq.enterprise.server.plugin.ServerPluginManagerBean.java

@RequiredPermission(Permission.MANAGE_SETTINGS)
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void setServerPluginStatus(Subject subject, List<Integer> pluginIds, PluginStatusType status)
        throws Exception {
    if (pluginIds == null || pluginIds.size() == 0) {
        return; // nothing to do
    }//  www .  j  a  v  a 2  s  .  co  m
    List<ServerPlugin> plugins = getServerPluginsById(pluginIds);
    for (ServerPlugin plugin : plugins) {
        plugin.setStatus(status);
        updateServerPluginExceptContent(subject, plugin);
    }
    return;
}

From source file:org.rhq.enterprise.server.discovery.DiscoveryBossBean.java

/**
 * Updates statuses according to the inventory rules. This is used internally - never call this yourself without
 * knowing what you do. See {@link #updateInventoryStatus(Subject, List, List, InventoryStatus)} for the "public"
 * version.//from  w ww . j  av a  2 s . com
 */
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void updateInventoryStatus(Subject user, InventoryStatus status, List<Resource> platforms,
        List<Resource> servers) {
    for (Resource platform : platforms) {
        resourceManager.setResourceStatus(user, platform, status, false);
    }

    for (Resource server : servers) {
        resourceManager.setResourceStatus(user, server, status, true);
    }
    if (status == InventoryStatus.COMMITTED) {
        List<Integer> allResourceIds = new ArrayList<Integer>();
        for (Resource platform : platforms) {
            allResourceIds.add(platform.getId());
        }
        for (Resource server : servers) {
            allResourceIds.add(server.getId());
        }
        resourceAvailabilityManager.insertNeededAvailabilityForImportedResources(allResourceIds);
    }
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public Configuration getResourceConfiguration(int resourceId) {
    // Ensure that we return a non-proxied Configuration object that can survive after the
    // Hibernate session goes away.
    Query query = entityManager.createNamedQuery(Configuration.QUERY_GET_RESOURCE_CONFIG_BY_RESOURCE_ID);
    query.setParameter("resourceId", resourceId);

    Configuration resourceConfiguration = (Configuration) query.getSingleResult();

    // Mask the configuration before returning it.
    Resource resource = resourceManager.getResourceById(subjectManager.getOverlord(), resourceId);
    ConfigurationDefinition resourceConfigurationDefinition = getResourceConfigurationDefinitionForResourceType(
            subjectManager.getOverlord(), resource.getResourceType().getId());
    // We do not want the masked configurations persisted, so detach all entities before masking the configurations.
    resourceConfiguration.getMap().size();
    entityManager.clear();//from  w w w . j  av a  2 s.  c  o  m
    ConfigurationMaskingUtility.maskConfiguration(resourceConfiguration, resourceConfigurationDefinition);

    return resourceConfiguration;
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public MeasurementBaseline calculateAutoBaselineInNewTransaction(Subject subject, Integer measurementScheduleId,
        long startDate, long endDate, boolean save)
        throws BaselineCreationException, MeasurementNotFoundException {

    MeasurementBaseline baseline;//w  w  w.ja  va2 s .c  om
    MeasurementSchedule sched = entityManager.find(MeasurementSchedule.class, measurementScheduleId);

    if (sched != null) {
        Resource resource = sched.getResource();

        // only check permissions if the user is attempting to save a new baseline
        if (save && !authorizationManager.hasResourcePermission(subject, Permission.MANAGE_MEASUREMENTS,
                resource.getId())) {
            log.error("Cannot calculate baseline - permission denied. " + "resource=" + resource + "; user="
                    + subject + "; perm=" + Permission.MANAGE_MEASUREMENTS);
            throw new PermissionException(
                    "Cannot calculate baseline - you do not have permission on this resource");
        }
    } else {
        throw new MeasurementNotFoundException(
                "Scheduled measurement [" + measurementScheduleId + "] not found");
    }

    try {
        baseline = calculateBaseline(sched, true, startDate, endDate, save);
        if (save) {
            // We have changed the baseline information for the schedule, so remove the now outdated OOB info.
            oobManager.removeOOBsForSchedule(subject, sched);
        }
    } catch (DataNotAvailableException e) {
        throw new BaselineCreationException(
                "Error fetching data for baseline calculation for measurementSchedule[id="
                        + measurementScheduleId + "]");
    }

    return baseline;
}