下面列出了怎么用javax.ejb.TransactionAttributeType的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
@SuppressWarnings("unused")
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void onRefreshComplete(@Observes RefreshLifecycle refreshLifecycle) {
switch (refreshLifecycle) {
case INITIATED:
flushAllException = null;
break;
case COMPLETE:
// Now that the refresh is complete, throw any flush principals exception that might have happened.
// We want to let the rest of the refresh complete internally before throwing the error so that we
// don't leave this server in an inconsistent state.
if (flushAllException != null) {
throw new RuntimeException("Error flushing principals cache: " + flushAllException.getMessage(), flushAllException);
}
break;
}
}
@POST
@Produces({"application/xml", "text/xml", "application/json", "text/yaml", "text/x-yaml", "application/x-yaml", "application/x-protobuf",
"application/x-protostuff"})
@Path("/{logicName}/createAndNext")
@GZIP
@GenerateQuerySessionId(cookieBasePath = "/DataWave/Query/")
@EnrichQueryMetrics(methodType = MethodType.CREATE_AND_NEXT)
@Interceptors({ResponseInterceptor.class, RequiredInterceptor.class})
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@Timed(name = "dw.query.createAndNext", absolute = true)
public BaseQueryResponse createQueryAndNext(@Required("logicName") @PathParam("logicName") String logicName, MultivaluedMap<String,String> queryParameters,
@Context HttpHeaders httpHeaders) {
CreateQuerySessionIDFilter.QUERY_ID.set(null);
GenericResponse<String> createResponse = createQuery(logicName, queryParameters, httpHeaders);
String queryId = createResponse.getResult();
CreateQuerySessionIDFilter.QUERY_ID.set(queryId);
return next(queryId, false);
}
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public BuildConfiguration save(BuildConfiguration buildConfiguration) {
Integer id = buildConfiguration.getId();
BuildConfiguration persisted = queryById(id);
if (persisted != null) {
if (!areParametersEqual(persisted, buildConfiguration)
|| !equalAuditedValues(persisted, buildConfiguration)) {
// always increment the revision of main entity when the child collection is updated
// the @PreUpdate method in BuildConfiguration was removed, the calculation of whether the
// lastModificationTime needs to be changed is done here
buildConfiguration.setLastModificationTime(new Date());
} else {
// No changes to audit, reset the lastModificationUser to previous existing
buildConfiguration.setLastModificationUser(persisted.getLastModificationUser());
}
}
return springRepository.save(buildConfiguration);
}
@POST
@Produces("*/*")
@Path("/{logicName}/async/execute")
@GZIP
@Interceptors({ResponseInterceptor.class, RequiredInterceptor.class})
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@Asynchronous
@Timed(name = "dw.query.executeQueryAsync", absolute = true)
public void executeAsync(@PathParam("logicName") String logicName, MultivaluedMap<String,String> queryParameters, @Context HttpHeaders httpHeaders,
@Suspended AsyncResponse asyncResponse) {
try {
StreamingOutput output = execute(logicName, queryParameters, httpHeaders);
asyncResponse.resume(output);
} catch (Throwable t) {
asyncResponse.resume(t);
}
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public List<SubscriptionHistory> loadSubscriptionsForCustomer(
long organizationKey, List<Long> unitKeys, long startDate,
long endDate, int cutOffDay) {
if (unitKeys == null || unitKeys.isEmpty()) {
return new ArrayList<SubscriptionHistory>();
}
Query query = dm
.createNamedQuery("SubscriptionHistory.getSubscriptionsForOrganizationAndUnits_VersionDesc");
query.setParameter("organizationKey", Long.valueOf(organizationKey));
query.setParameter("units", unitKeys);
query.setParameter("startDate", new Date(startDate));
query.setParameter("endDate", new Date(endDate));
query.setParameter("cutOffDay", Integer.valueOf(cutOffDay));
query.setParameter("external", true);
@SuppressWarnings("unchecked")
List<SubscriptionHistory> result = query.getResultList();
return result;
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void resetUserPassword(PlatformUser platformUser,
String marketplaceId)
throws UserActiveException, MailOperationException {
// determine if the user has an active session, if so, throw an
// exception
List<Session> sessionsForUserKey = prodSessionMgmt
.getSessionsForUserKey(platformUser.getKey());
if (sessionsForUserKey.size() > 0) {
UserActiveException uae = new UserActiveException(
"Reset of password for user '" + platformUser.getKey()
+ "' failed, as the user is still active",
new Object[] { platformUser.getUserId() });
logger.logWarn(Log4jLogger.SYSTEM_LOG, uae,
LogMessageIdentifier.WARN_OPERATOR_RESET_PASSWORD_FAILED);
throw uae;
}
// reset the password
resetPasswordForUser(platformUser, getMarketplace(marketplaceId));
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void updateMarketplaceName(Marketplace marketplace,
String newMarketplaceName) throws OperationNotPermittedException {
LocalizerFacade facade = new LocalizerFacade(localizer,
ds.getCurrentUser().getLocale());
String persistedMarketplaceName = facade.getText(marketplace.getKey(),
LocalizedObjectTypes.MARKETPLACE_NAME);
if (!persistedMarketplaceName.equals(newMarketplaceName)) {
if (!ds.getCurrentUser().hasRole(UserRoleType.MARKETPLACE_OWNER)) {
throw new OperationNotPermittedException();
}
checkMarketplaceOwner(marketplace.getMarketplaceId());
localizer.storeLocalizedResource(ds.getCurrentUser().getLocale(),
marketplace.getKey(), LocalizedObjectTypes.MARKETPLACE_NAME,
newMarketplaceName);
}
}
/**
* Starts the creation of an application instance and returns the instance
* ID.
* <p>
* The internal status <code>CREATION_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 settings
* a <code>ProvisioningSettings</code> object specifying the
* service parameters and configuration settings
* @return an <code>InstanceDescription</code> instance describing the
* application instance
* @throws APPlatformException
*/
@Override
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public InstanceDescription createInstance(ProvisioningSettings settings)
throws APPlatformException {
// Set status to store for application instance
PropertyHandler paramHandler = new PropertyHandler(settings);
paramHandler.setState(Status.CREATION_REQUESTED);
// Return generated instance information
InstanceDescription id = new InstanceDescription();
id.setInstanceId("Instance_" + System.currentTimeMillis());
id.setChangedParameters(settings.getParameters());
id.setChangedAttributes(settings.getAttributes());
return id;
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void removeMarketingPermissions(TechnicalProduct technicalProduct) {
Query query = ds
.createNamedQuery("MarketingPermission.findForTechnicalService");
query.setParameter("tp", technicalProduct);
List<MarketingPermission> result = ParameterizedTypes.list(
query.getResultList(), MarketingPermission.class);
// remove permissions
Set<Long> affectedReferences = new HashSet<Long>();
for (MarketingPermission mp : result) {
affectedReferences.add(Long.valueOf(mp
.getOrganizationReferenceKey()));
ds.remove(mp);
}
// remove organization reference
removeObsoleteOrgRefs(affectedReferences);
}
/**
* Returns the current overall status of the application instance.
* <p>
* For retrieving the status, the method calls the status dispatcher with
* the currently stored controller configuration settings. These settings
* include the internal status set by the controller or the dispatcher
* itself. The overall status of the instance depends on this internal
* status.
*
* @param instanceId
* the ID of the application instance to be checked
* @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 getInstanceStatus(String instanceId,
ProvisioningSettings settings) throws APPlatformException {
LOGGER.debug("getInstanceStatus({})",
LogAndExceptionConverter.getLogText(instanceId, settings));
try {
PropertyHandler ph = new PropertyHandler(settings);
ProvisioningValidator.validateTimeout(instanceId, ph,
platformService);
Dispatcher dp = new Dispatcher(platformService, instanceId, ph);
InstanceStatus status = dp.dispatch();
return status;
} catch (Exception t) {
throw LogAndExceptionConverter.createAndLogPlatformException(t,
Context.STATUS);
}
}
@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;
}
}
@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);
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public List<PlatformUser> getOrganizationUsers() {
// The organization is determined by the currently logged in user. To
// obtain the users for this organization, the organization domain
// object has to be loaded, which then references the users.
PlatformUser user = dm.getCurrentUser();
// 1. determine the correlating organization
Organization organization = user.getOrganization();
Query q = dm.createNamedQuery("PlatformUser.getVisibleForOrganization");
q.setParameter("organization", organization);
return ParameterizedTypes.list(q.getResultList(), PlatformUser.class);
}
/**
* 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 void updateBillingSubscriptionStatus(long subscriptionKey,
long endOfLastBilledPeriod) throws NonUniqueBusinessKeyException {
BillingSubscriptionStatus billingSubStatus = new BillingSubscriptionStatus();
billingSubStatus.setSubscriptionKey(subscriptionKey);
billingSubStatus = (BillingSubscriptionStatus) dm
.find(billingSubStatus);
if (billingSubStatus != null) {
billingSubStatus.setEndOfLastBilledPeriod(Math.max(
billingSubStatus.getEndOfLastBilledPeriod(),
endOfLastBilledPeriod));
} else {
billingSubStatus = new BillingSubscriptionStatus();
billingSubStatus.setSubscriptionKey(subscriptionKey);
billingSubStatus.setEndOfLastBilledPeriod(endOfLastBilledPeriod);
dm.persist(billingSubStatus);
dm.flush();
}
}
/**
* 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);
}
}
@Override
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public InstanceStatus activateInstance(String instanceId,
ProvisioningSettings settings) throws APPlatformException {
try {
PropertyHandler paramHandler = new PropertyHandler(settings);
if (paramHandler.isVirtualSystemProvisioning()) {
paramHandler.setOperation(Operation.VSYSTEM_ACTIVATION);
paramHandler.setState(FlowState.VSYSTEM_ACTIVATION_REQUESTED);
} else {
paramHandler.setOperation(Operation.VSERVER_ACTIVATION);
paramHandler.setState(FlowState.VSERVER_ACTIVATION_REQUESTED);
}
InstanceStatus result = new InstanceStatus();
result.setChangedParameters(settings.getParameters());
result.setChangedAttributes(settings.getAttributes());
return result;
} catch (Exception e) {
logger.error("Error while scheduling instance activation", e);
throw getPlatformException(e, "error_activation_overall");
}
}
@Override
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public InstanceStatus deleteUsers(String instanceId,
ProvisioningSettings settings, List<ServiceUser> users)
throws APPlatformException {
return null;
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public boolean doesAccessToMarketplaceExistForOrganization(
long marketplaceKey, long organizationKey) {
MarketplaceAccess marketplaceAccess = new MarketplaceAccess();
marketplaceAccess.setMarketplace_tkey(marketplaceKey);
marketplaceAccess.setOrganization_tkey(organizationKey);
try {
ds.getReferenceByBusinessKey(marketplaceAccess);
} catch (ObjectNotFoundException e) {
return false;
}
return marketplaceAccess != null;
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void persistChanges(ChangeSet changeSet) throws ConcurrencyException, DuplicateCommitException {
if (changeSet == null)
throw new IllegalArgumentException("changeSet must not be null");
String body = createSerializedBody(changeSet);
log.log(Level.FINE, "writing {0} as serialized {1}",
new Object[]{changeSet.changeSetId(), body});
EventStoreEntry entry = createEntry(changeSet, body);
doPersist(changeSet.bucketId(), entry);
log.log(Level.FINE, "wrote ChangeSet {0} to event store, id #{1}",
new Object[]{changeSet.changeSetId(),
Long.toString(entry.id() == null ? -1 : entry.id())});
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void updateUsers(Subscription subscription,
List<UsageLicense> licenses)
throws TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
userModificationCallReceived = true;
}
/**
* @see BillingDataRetrievalServiceLocal#getOrganizationBillingAddressFromHistory(long)
*/
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public OrganizationAddressData loadOrganizationBillingDataFromHistory(
long organizationKey, long subscriptionKey) {
Organization org = new Organization();
org.setKey(organizationKey);
OrganizationHistory orgHistory = (OrganizationHistory) dm
.findLastHistory(org);
if (orgHistory == null) {
return null;
}
String organizationId = orgHistory.getOrganizationId();
String name = orgHistory.getOrganizationName();
String address = orgHistory.getAddress();
String email = orgHistory.getEmail();
String paymentTypeId = loadPaymentTypeIdForSubscription(subscriptionKey);
BillingContactHistory billingContactHistory = loadBillingContact(subscriptionKey);
if (billingContactHistory != null
&& !billingContactHistory.isOrgAddressUsed()) {
name = billingContactHistory.getCompanyName();
address = billingContactHistory.getAddress();
email = billingContactHistory.getEmail();
}
name = name == null ? "" : name;
OrganizationAddressData data = new OrganizationAddressData(address == null ? "" : address,
name == null ? "" : name, email == null ? "" : email, organizationId);
data.setPaymentTypeId(paymentTypeId);
return data;
}
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public List<PlatformUser> getOrganizationAdmins(long organizationKey) {
Query query = dataManager
.createNamedQuery("Organization.getAdministrators");
query.setParameter("orgkey", Long.valueOf(organizationKey));
return ParameterizedTypes.list(query.getResultList(),
PlatformUser.class);
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void deleteUser(PlatformUser pUser, String marketplaceId)
throws OperationNotPermittedException,
UserDeletionConstraintException, TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
// Check whether user belongs to same organization than the caller
PermissionCheck.sameOrg(dm.getCurrentUser(), pUser, logger);
deletePlatformUser(pUser, false, false, getMarketplace(marketplaceId));
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public List<PlatformUser> getOrganizationAdmins(long organizationKey) {
Query query = dm.createNamedQuery("Organization.getAdministrators");
query.setParameter("orgkey", Long.valueOf(organizationKey));
return ParameterizedTypes.list(query.getResultList(),
PlatformUser.class);
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public PriceModelHistory loadOldestPriceModelHistory(long priceModelKey,
long modDate) {
List<PriceModelHistory> resultList = loadPriceModelHistories(
priceModelKey, modDate);
if (resultList.isEmpty()) {
throw new BillingRunFailed(
"History data is missing for price model with key "
+ priceModelKey + " before " + new Date(modDate));
}
return resultList.get(0);
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public long loadVendorKeyForSubscription(long subscriptionKey) {
Query query = dm.createNamedQuery("SubscriptionHistory.getVendorKey");
query.setParameter("subscriptionKey", Long.valueOf(subscriptionKey));
Long result = (Long) query.getSingleResult();
return result.longValue();
}
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public HashMap<String, Setting> getAllProxyConfigurationSettings()
throws ConfigurationException {
LOGGER.debug("Retrieving all configuration settings for proxy");
HashMap<String, Setting> result = new HashMap<>();
Query query = em.createNamedQuery("ConfigurationSetting.getAllProxy");
List<?> resultList = query.getResultList();
for (Object entry : resultList) {
ConfigurationSetting currentCs = (ConfigurationSetting) entry;
result.put(currentCs.getSettingKey(), new Setting(
currentCs.getSettingKey(), currentCs.getDecryptedValue()));
}
PlatformConfigurationKey[] keys = PlatformConfigurationKey.values();
StringBuffer missing = new StringBuffer();
for (int i = 0; i < keys.length; i++) {
if (keys[i].isMandatory() && !result.containsKey(keys[i].name())) {
if (missing.length() > 0) {
missing.append(", ");
}
missing.append(keys[i].name());
}
}
if (missing.length() > 0) {
throw new ConfigurationException(
"The configuration is missing the following parameter(s): "
+ missing.toString(),
missing.toString());
}
return result;
}
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void createFooNotSupported(String name){
Foo foo = new Foo(name);
em.persist(foo); //will fail out of a transaction
// NOTE: only as example... usually would not have a "persist" in
// a NOT_SUPPORTED method
}