类javax.ejb.TransactionAttribute源码实例Demo

下面列出了怎么用javax.ejb.TransactionAttribute的API类实例代码及写法,或者点击链接到github查看源代码。

@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void saveOperatorRevenueShare(long serviceKey,
        RevenueShareModel newRevenueShare, int newRevenueShareVersion)
        throws ValidationException, ConcurrentModificationException,
        ObjectNotFoundException, ServiceOperationException {

    ArgumentValidator.notNull("newRevenueShare", newRevenueShare);
    Product product = dm.getReference(Product.class, serviceKey);
    validateProductTemplate(product);
    validateOperatorRevenueShare(product);

    CatalogEntry ce = product.getCatalogEntries().get(0);
    try {
        updateRevenueShare(newRevenueShare, ce.getOperatorPriceModel(),
                newRevenueShareVersion);
    } catch (ValidationException e) {
        sessionCtx.setRollbackOnly();
        throw e;
    }

}
 
源代码2 项目: development   文件: AccountServiceBean.java
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public boolean removeOverdueOrganizations(long currentTime) {

    boolean successfulExecution = true;
    List<PlatformUser> overdueOrganizationAdmins = im
            .getOverdueOrganizationAdmins(currentTime);

    for (PlatformUser userToBeRemoved : overdueOrganizationAdmins) {
        try {
            // call has to be made by calling into the container again, so
            // that the new transactional behaviour is considered.
            prepareForNewTransaction().removeOverdueOrganization(
                    userToBeRemoved.getOrganization());
        } catch (Exception e) {
            successfulExecution = false;
            logger.logError(Log4jLogger.SYSTEM_LOG, e,
                    LogMessageIdentifier.ERROR_ORGANIZATION_DELETION_FAILED,
                    Long.toString(
                            userToBeRemoved.getOrganization().getKey()));
            // logging is sufficient for now, so simply proceed
        }
    }

    return successfulExecution;
}
 
源代码3 项目: datawave   文件: QueryExecutorBean.java
@POST
@Produces({"application/xml", "text/xml", "application/json", "text/yaml", "text/x-yaml", "application/x-yaml", "application/x-protobuf",
        "application/x-protostuff"})
@Path("/{logicName}/async/createAndNext")
@GZIP
@GenerateQuerySessionId(cookieBasePath = "/DataWave/Query/")
@EnrichQueryMetrics(methodType = MethodType.CREATE_AND_NEXT)
@Interceptors({ResponseInterceptor.class, RequiredInterceptor.class})
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@Asynchronous
@Timed(name = "dw.query.createAndNextAsync", absolute = true)
public void createQueryAndNextAsync(@Required("logicName") @PathParam("logicName") String logicName, MultivaluedMap<String,String> queryParameters,
                @Suspended AsyncResponse asyncResponse) {
    try {
        BaseQueryResponse response = createQueryAndNext(logicName, queryParameters);
        asyncResponse.resume(response);
    } catch (Throwable t) {
        asyncResponse.resume(t);
    }
}
 
源代码4 项目: solace-integration-guides   文件: XAProducerSB.java
@TransactionAttribute(value = TransactionAttributeType.REQUIRED)
@Override
public void sendMessage() throws JMSException {

    Connection conn = null;
    Session session = null;
    MessageProducer prod = null;

    try {
        conn = myCF.createConnection();
        session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        prod = session.createProducer(myReplyQueue);

        ObjectMessage msg = session.createObjectMessage();
        msg.setObject("Hello world!");
        prod.send(msg, DeliveryMode.PERSISTENT, 0, 0);
    } finally {
        if (prod != null)
            prod.close();
        if (session != null)
            session.close();
        if (conn != null)
            conn.close();
    }
}
 
源代码5 项目: development   文件: PaymentServiceBean.java
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void deregisterPaymentInPSPSystem(PaymentInfo payment)
        throws PaymentDeregistrationException,
        OperationNotPermittedException {

    // check pre-conditions
    if (payment == null
            || payment.getPaymentType().getCollectionType() != PaymentCollectionType.PAYMENT_SERVICE_PROVIDER) {
        return;
    }
    PlatformUser currentUser = dm.getCurrentUser();
    PermissionCheck.owns(payment, currentUser.getOrganization(), logger);

    RequestData data = createRequestData(currentUser.getLocale(), payment);

    deregisterPaymentInfo(payment.getPaymentType().getPsp().getWsdlUrl(),
            data);

}
 
源代码6 项目: development   文件: LocalizerServiceBean.java
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public Properties loadLocalizedPropertiesFromDatabase(long objectKey,
        LocalizedObjectTypes objectType, String localeString) {
    Properties properties = new Properties();
    LocalizedResource template = new LocalizedResource(localeString,
            objectKey, objectType);
    LocalizedResource resource = (LocalizedResource) dm.find(template);
    if (resource != null && resource.getValue().length() > 0) {
        try {
            // Property files are always encoded in ISO-8859-1:
            final InputStream inputStream = new ByteArrayInputStream(
                    resource.getValue().getBytes("ISO-8859-1"));
            properties.load(inputStream);
            inputStream.close();
        } catch (IOException e) {
            logger.logError(Log4jLogger.SYSTEM_LOG, e,
                    LogMessageIdentifier.ERROR_OBJECT_ENCODING_FAILED);
        }
    }

    return properties;
}
 
源代码7 项目: development   文件: SharesCalculatorBean.java
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void performSupplierSharesCalculationRun(long startOfLastMonth,
        long endOfLastMonth, Long supplierKey) throws Exception {

    SupplierShareResultAssembler assembler = new SupplierShareResultAssembler(
            sharesRetrievalService);
    SupplierRevenueShareResult supplierShareResult = assembler.build(
            supplierKey, startOfLastMonth, endOfLastMonth);

    supplierShareResult.calculateAllShares();

    saveBillingSharesResult(startOfLastMonth, endOfLastMonth,
            BillingSharesResultType.SUPPLIER, supplierShareResult,
            supplierKey);
}
 
/**
 * Load the list of UsageLicense objects that belong to the subscription and
 * thus the product. The list will be ordered by userobjkey ASC, objVersion
 * DESC.
 *
 * @return list of usage licenses, may be empty but never null.
 */
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public List<UsageLicenseHistory> loadUsageLicenses(long subscriptionKey,
        long startTimeForPeriod, long endTimeForPeriod) {

    Query query = dm
            .createNamedQuery("UsageLicenseHistory.getForSubKey_VersionDESC");
    Date startDate = new Date(startTimeForPeriod);
    query.setParameter("startTimeAsDate", startDate);
    query.setParameter("subscriptionKey", Long.valueOf(subscriptionKey));
    Date endDate = new Date(endTimeForPeriod);
    query.setParameter("endTimeAsDate", endDate);

    final List<UsageLicenseHistory> usageLicenseHistoryElements = ParameterizedTypes
            .list(query.getResultList(), UsageLicenseHistory.class);

    setUserIdsForUsageLicenses(usageLicenseHistoryElements);

    return usageLicenseHistoryElements;
}
 
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public SubscriptionHistory loadPreviousSubscriptionHistoryForPriceModel(
        final long priceModelKey, final long timeMillis) {
    TypedQuery<SubscriptionHistory> query = dm.createNamedQuery(
            "SubscriptionHistory.findPreviousForPriceModel",
            SubscriptionHistory.class);
    query.setParameter("priceModelKey", Long.valueOf(priceModelKey));
    query.setParameter("modDate", new Date(timeMillis));

    List<SubscriptionHistory> resultList = query.getResultList();
    if (resultList.size() > 0) {
        return resultList.get(0);
    } else {
        return null;
    }
}
 
源代码10 项目: development   文件: AWSController.java
/**
 * Starts the modification of an application instance.
 * <p>
 * The internal status <code>MODIFICATION_REQUESTED</code> is stored as a
 * controller configuration setting. It is evaluated and handled by the
 * status dispatcher, which is invoked at regular intervals by APP through
 * the <code>getInstanceStatus</code> method.
 * 
 * @param instanceId
 *            the ID of the application instance to be modified
 * @param currentSettings
 *            a <code>ProvisioningSettings</code> object specifying the
 *            current service parameters and configuration settings
 * @param newSettings
 *            a <code>ProvisioningSettings</code> object specifying the
 *            modified service parameters and configuration settings
 * @return an <code>InstanceStatus</code> instance with the overall status
 *         of the application instance
 * @throws APPlatformException
 */
@Override
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public InstanceStatus modifyInstance(String instanceId,
        ProvisioningSettings currentSettings,
        ProvisioningSettings newSettings) throws APPlatformException {
    LOGGER.info("modifyInstance({})", LogAndExceptionConverter
            .getLogText(instanceId, currentSettings));
    try {
        PropertyHandler ph = PropertyHandler.withSettings(newSettings);
        ph.setOperation(Operation.EC2_MODIFICATION);
        ph.setState(FlowState.MODIFICATION_REQUESTED);

        InstanceStatus result = new InstanceStatus();
        result.setChangedParameters(newSettings.getParameters());
        result.setChangedAttributes(newSettings.getAttributes());
        return result;
    } catch (Throwable t) {
        throw LogAndExceptionConverter.createAndLogPlatformException(t,
                Context.MODIFICATION);
    }
}
 
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public Map<Long, RoleDefinitionHistory> loadRoleDefinitionsForPriceModel(
        long priceModelKey, long periodEndTime) {
    List<RoleDefinitionHistory> tempResult = findRoleDefinitionsForPriceModel(
            priceModelKey, periodEndTime);

    Map<Long, RoleDefinitionHistory> result = new HashMap<Long, RoleDefinitionHistory>();
    Set<Long> containedRoleKeys = new HashSet<Long>();

    for (RoleDefinitionHistory currentHist : tempResult) {
        if (containedRoleKeys.add(Long.valueOf(currentHist.getObjKey()))) {
            result.put(Long.valueOf(currentHist.getObjKey()), currentHist);
        }
    }

    return result;
}
 
源代码12 项目: development   文件: SharesCalculatorBean.java
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void performBrokerShareCalculationRun(long startOfLastMonth,
        long endOfLastMonth, Long brokerKey) throws Exception {
    // build the result object tree
    BrokerRevenueShareResult brokerShareResult = new BrokerShareResultAssembler(
            sharesRetrievalService, billingRetrievalService).build(
            brokerKey, startOfLastMonth, endOfLastMonth);

    // calculate all shares
    brokerShareResult.calculateAllShares();

    // serialize the result object and persist
    saveBillingSharesResult(startOfLastMonth, endOfLastMonth,
            BillingSharesResultType.BROKER, brokerShareResult, brokerKey);
}
 
源代码13 项目: development   文件: AWSController.java
/**
 * Starts the deactivation of an application instance.
 * <p>
 * The internal status <code>DEACTIVATION_REQUESTED</code> is stored as a
 * controller configuration setting. It is evaluated and handled by the
 * status dispatcher, which is invoked at regular intervals by APP through
 * the <code>getInstanceStatus</code> method.
 * 
 * @param instanceId
 *            the ID of the application instance to be activated
 * @param settings
 *            a <code>ProvisioningSettings</code> object specifying the
 *            service parameters and configuration settings
 * @return an <code>InstanceStatus</code> instance with the overall status
 *         of the application instance
 * @throws APPlatformException
 */
@Override
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public InstanceStatus deactivateInstance(String instanceId,
        ProvisioningSettings settings) throws APPlatformException {
    LOGGER.info("deactivateInstance({})",
            LogAndExceptionConverter.getLogText(instanceId, settings));
    try {
        // Set status to store for application instance
        PropertyHandler ph = PropertyHandler.withSettings(settings);
        ph.setOperation(Operation.EC2_ACTIVATION);
        ph.setState(FlowState.DEACTIVATION_REQUESTED);

        InstanceStatus result = new InstanceStatus();
        result.setChangedParameters(settings.getParameters());
        result.setChangedAttributes(settings.getAttributes());
        return result;
    } catch (Throwable t) {
        throw LogAndExceptionConverter.createAndLogPlatformException(t,
                Context.DEACTIVATION);
    }
}
 
源代码14 项目: development   文件: IaasController.java
@Override
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public InstanceStatus deleteInstance(String instanceId,
        ProvisioningSettings settings) throws APPlatformException {

    try {
        PropertyHandler paramHandler = new PropertyHandler(settings);
        defineOperation(Operation.DELETION, paramHandler);
        // Schedule instance deletion
        if (paramHandler.isVirtualSystemProvisioning()) {
            paramHandler.setState(FlowState.VSYSTEM_DELETION_REQUESTED);
        } else {
            paramHandler.setState(FlowState.VSERVER_DELETION_REQUESTED);
        }
        InstanceStatus result = new InstanceStatus();
        result.setChangedParameters(settings.getParameters());
        result.setChangedAttributes(settings.getAttributes());
        return result;
    } catch (Exception e) {
        logger.error("Error while scheduling VSERVER instance deletion", e);
        APPlatformException exception = getPlatformException(e,
                "error_deletion_overall");
        throw exception;
    }
}
 
源代码15 项目: development   文件: ImageResourceServiceBean.java
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void save(ImageResource imageResource) {
    

    ImageResource template = new ImageResource(
            imageResource.getObjectKey(), imageResource.getImageType());
    ImageResource storedImageResource = (ImageResource) ds.find(template);
    boolean persistFlag = false;
    if (storedImageResource == null) {
        storedImageResource = new ImageResource();
        persistFlag = true;
    }
    storedImageResource.setContentType(imageResource.getContentType());
    storedImageResource.setBuffer(imageResource.getBuffer());
    if (persistFlag) {
        try {
            ds.persist(imageResource);
            ds.flush();
        } catch (NonUniqueBusinessKeyException e) {
            SaaSSystemException sse = new SaaSSystemException(
                    "Image Resource could not be persisted although prior check was performed, "
                            + imageResource, e);
            logger.logError(
                    Log4jLogger.SYSTEM_LOG,
                    sse,
                    LogMessageIdentifier.ERROR_PERSIST_IMAGE_RESOURCE_FAILED_PRIOR_CHECK_PERFORMED,
                    String.valueOf(imageResource));
            throw sse;
        }
    }

    
}
 
源代码16 项目: wildfly-camel   文件: Accounting.java
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void transferCamel(int amount) throws Exception {
    Account accountA = em.getReference(Account.class, 1);
    Account accountB = em.getReference(Account.class, 2);

    // update the from balance
    accountA.setBalance(accountA.getBalance() - amount);

    // do something in camel that is transactional
    CamelContext camelctx = new DefaultCamelContext(new JndiBeanRepository());
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .wireTap("log:org.wildfly.camel.test.jpa?level=WARN")
            .to("sql:update Account set balance = :#${body} where id = 3?dataSource=java:jboss/datasources/ExampleDS");
        }
    });

    camelctx.start();
    try {
        ProducerTemplate producer = camelctx.createProducerTemplate();
        producer.requestBody("direct:start", accountA.getBalance());
    } finally {
        camelctx.close();
    }

    // rollback if from balance is < 0
    if (accountA.getBalance() < 0) {
        context.setRollbackOnly();
        return;
    }

    // update the to balance
    accountB.setBalance(accountB.getBalance() + amount);
}
 
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public long loadChargingOrgKeyForSubscription(long subscriptionKey) {
    List<OrganizationRoleType> roles = loadVendorRolesForSubscription(subscriptionKey);
    long result;
    if (roles.contains(OrganizationRoleType.BROKER)) {
        result = loadSupplierKeyForSubscription(subscriptionKey);
    } else {
        result = loadVendorKeyForSubscription(subscriptionKey);
    }
    return result;
}
 
源代码18 项目: development   文件: VMController.java
@Override
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public InstanceStatus deleteUsers(String instanceId,
        ProvisioningSettings settings, List<ServiceUser> users)
        throws APPlatformException {
    return null;
}
 
源代码19 项目: development   文件: VMController.java
@Override
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public InstanceStatusUsers createUsers(String instanceId,
        ProvisioningSettings settings, List<ServiceUser> users)
        throws APPlatformException {
    return null;
}
 
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public List<UdaBillingData> loadUdasForCustomer(long customerKey,
        long chargingOrkKey) {

    List<Object[]> udas = findUdaBillingDataForOrg(customerKey,
            chargingOrkKey);
    return getUdaBillingDataFromResultList(udas);
}
 
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void saveServiceLocalization(long serviceKey,
        VOServiceLocalization localization) throws ObjectNotFoundException,
        OperationNotPermittedException, ValidationException,
        ConcurrentModificationException {

    if (!checkIsAllowedForLocalizingService(serviceKey)) {
        throw new OperationNotPermittedException(
                "No rights for setting product localizations.");
    }

    for (VOLocalizedText name : localization.getNames()) {
        BLValidator.isName(ProductAssembler.FIELD_NAME_NAME,
                name.getText(), false);
    }

    Product product = ds.getReference(Product.class, serviceKey);
    VOServiceLocalization storedServiceLocalization = getServiceLocalization(product);
    if (ds.getCurrentUser().hasRole(UserRoleType.SERVICE_MANAGER)) {
        localizer.setLocalizedValues(serviceKey,
                LocalizedObjectTypes.PRODUCT_MARKETING_DESC,
                localization.getDescriptions());
        localizer.setLocalizedValues(serviceKey,
                LocalizedObjectTypes.PRODUCT_MARKETING_NAME,
                localization.getNames());
        localizer.setLocalizedValues(serviceKey,
                LocalizedObjectTypes.PRODUCT_SHORT_DESCRIPTION,
                localization.getShortDescriptions());
        localizer.setLocalizedValues(serviceKey,
                LocalizedObjectTypes.PRODUCT_CUSTOM_TAB_NAME,
                localization.getCustomTabNames());
    }
    serviceAudit.localizeService(ds, product, storedServiceLocalization,
            localization);

}
 
源代码22 项目: sample.daytrader7   文件: TradeSLSBBean.java
@Override
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public RunStatsDataBean resetTrade(boolean deleteAll) throws Exception {
    if (Log.doTrace()) {
        Log.trace("TradeSLSBBean:resetTrade", deleteAll);
    }

    return new com.ibm.websphere.samples.daytrader.direct.TradeDirect(false).resetTrade(deleteAll);
}
 
源代码23 项目: development   文件: APPTimerServiceBean.java
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void cancelTimers() {
    Collection<Timer> timers = timerService.getTimers();
    for (Timer th : timers) {
        if (APP_TIMER_INFO.equals(th.getInfo())) {
            th.cancel();
            return;
        }
    }
}
 
源代码24 项目: development   文件: ApplicationServiceStub.java
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void deactivateInstance(Subscription subscription)
        throws TechnicalServiceNotAliveException,
        TechnicalServiceOperationException {
    deactivated = true;
}
 
源代码25 项目: development   文件: APPConfigurationServiceBean.java
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void storeControllerOrganizations(
        HashMap<String, String> controllerOrganizations) {

    LOGGER.debug("Storing configured controllers");
    Query query = em
            .createNamedQuery("ConfigurationSetting.getControllersForKey");
    query.setParameter("key",
            ControllerConfigurationKey.BSS_ORGANIZATION_ID.name());
    List<?> resultList = query.getResultList();
    for (Object entry : resultList) {
        ConfigurationSetting currentCs = (ConfigurationSetting) entry;
        String cId = currentCs.getControllerId();
        if (controllerOrganizations.containsKey(cId)) {
            String value = controllerOrganizations.get(cId);
            if (value == null || value.trim().length() == 0) {
                em.remove(currentCs);
            } else {
                currentCs.setSettingValue(value);
                em.persist(currentCs);
            }
            controllerOrganizations.remove(cId);
        }
    }
    for (String key : controllerOrganizations.keySet()) {
        if (controllerOrganizations.get(key) != null
                && controllerOrganizations.get(key).trim().length() > 0) {
            ConfigurationSetting newSetting = new ConfigurationSetting();
            newSetting.setControllerId(key);
            newSetting.setSettingKey(
                    ControllerConfigurationKey.BSS_ORGANIZATION_ID.name());
            newSetting.setSettingValue(controllerOrganizations.get(key));
            em.persist(newSetting);
        }
    }
}
 
源代码26 项目: tomee   文件: AutoConnectionTrackerTest.java
@Override
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void nonleakyNonTxMethod() throws Exception {
    final FakeConnection connection = cf.getConnection();
    connection.sendMessage("Test message");
    connection.close();
}
 
/**
 * Returns the handler suitable for the given bean implementation class.
 * 
 * @param beanClass
 * @return
 */
public static IInvocationHandler getHandlerFor(Class<?> beanClass) {
    TransactionAttribute attr = beanClass
            .getAnnotation(TransactionAttribute.class);
    if (attr != null) {
        return getHandlerFor(attr.value());
    }
    // Default is REQUIRED (see EJB 3.0 Core Spec, 13.3.7)
    return TX_REQUIRED;
}
 
源代码28 项目: eplmp   文件: ProductManagerBean.java
@RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID)
@TransactionAttribute(value = TransactionAttributeType.REQUIRES_NEW)
@Override
public Conversion createConversion(PartIterationKey partIterationKey) throws UserNotFoundException, WorkspaceNotFoundException, UserNotActiveException, PartRevisionNotFoundException, AccessRightException, PartIterationNotFoundException, CreationException, WorkspaceNotEnabledException {
    checkPartRevisionWriteAccess(partIterationKey.getPartRevision());
    PartIteration partIteration = partIterationDAO.loadPartI(partIterationKey);
    Conversion conversion = new Conversion(partIteration);
    conversionDAO.createConversion(conversion);
    return conversion;
}
 
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public BigDecimal loadMarketplaceRevenueSharePercentage(long mpKey,
        long endPeriod) {
    Invariants.assertGreaterThan(mpKey, 0);
    Invariants.assertGreaterThan(endPeriod, 0);

    RevenueShareModelHistory revenueShareModelHistory = findMarketplaceRevenueShareWithinPeriod(
            mpKey, endPeriod);
    if (revenueShareModelHistory == null) {
        return null;
    }

    return revenueShareModelHistory.getDataContainer().getRevenueShare();
}
 
/**
 * @see BillingDataRetrievalServiceLocal#loadSteppedPricesForPriceModel(long,
 *      long)
 */
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public List<SteppedPriceData> loadSteppedPricesForPriceModel(
        long priceModelKey, long periodEndTime) {
    List<SteppedPriceHistory> steppedPrices = findSteppedPricesForPriceModel(
            priceModelKey, periodEndTime);

    List<SteppedPriceData> result = new ArrayList<SteppedPriceData>();
    for (SteppedPriceHistory steppedPrice : steppedPrices) {
        result.add(new SteppedPriceData(steppedPrice));
    }
    return result;
}