use of org.springframework.transaction.event.TransactionalEventListener in project webanno by webanno.
the class WebhookService method onApplicationEvent.
@TransactionalEventListener(fallbackExecution = true)
@Async
public void onApplicationEvent(ApplicationEvent aEvent) {
String topic = EVENT_TOPICS.get(aEvent.getClass());
if (topic == null) {
return;
}
Object message;
switch(topic) {
case PROJECT_STATE:
message = new ProjectStateChangeMessage((ProjectStateChangedEvent) aEvent);
break;
case DOCUMENT_STATE:
message = new DocumentStateChangeMessage((DocumentStateChangedEvent) aEvent);
break;
case ANNOTATION_STATE:
message = new AnnotationStateChangeMessage((AnnotationStateChangeEvent) aEvent);
break;
default:
return;
}
for (Webhook hook : configuration.getGlobalHooks()) {
if (!hook.isEnabled() || !hook.getTopics().contains(topic)) {
continue;
}
try {
// Configure rest template without SSL certification check if that is disabled.
RestTemplate restTemplate;
if (hook.isVerifyCertificates()) {
restTemplate = restTemplateBuilder.build();
} else {
restTemplate = restTemplateBuilder.requestFactory(getNonValidatingRequestFactory()).build();
}
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
requestHeaders.set(X_AERO_NOTIFICATION, topic);
// If a secret is set, then add a digest header that allows the client to verify
// the message integrity
String json = JSONUtil.toJsonString(message);
if (isNotBlank(hook.getSecret())) {
String digest = DigestUtils.shaHex(hook.getSecret() + json);
requestHeaders.set(X_AERO_SIGNATURE, digest);
}
HttpEntity<?> httpEntity = new HttpEntity<Object>(json, requestHeaders);
restTemplate.postForEntity(hook.getUrl(), httpEntity, Void.class);
} catch (Exception e) {
log.error("Unable to invoke webhook [{}]", hook, e);
}
}
}
use of org.springframework.transaction.event.TransactionalEventListener in project syncope by apache.
the class ElasticsearchIndexManager method after.
@TransactionalEventListener
public void after(final AnyCreatedUpdatedEvent<Any<?>> event) throws IOException {
GetResponse getResponse = client.prepareGet(AuthContextUtils.getDomain().toLowerCase(), event.getAny().getType().getKind().name(), event.getAny().getKey()).get();
if (getResponse.isExists()) {
LOG.debug("About to update index for {}", event.getAny());
UpdateResponse response = client.prepareUpdate(AuthContextUtils.getDomain().toLowerCase(), event.getAny().getType().getKind().name(), event.getAny().getKey()).setRetryOnConflict(elasticsearchUtils.getRetryOnConflict()).setDoc(elasticsearchUtils.builder(event.getAny())).get();
LOG.debug("Index successfully updated for {}: {}", event.getAny(), response);
} else {
LOG.debug("About to create index for {}", event.getAny());
IndexResponse response = client.prepareIndex(AuthContextUtils.getDomain().toLowerCase(), event.getAny().getType().getKind().name(), event.getAny().getKey()).setSource(elasticsearchUtils.builder(event.getAny())).get();
LOG.debug("Index successfully created for {}: {}", event.getAny(), response);
}
}
use of org.springframework.transaction.event.TransactionalEventListener in project syncope by apache.
the class ElasticsearchIndexManager method after.
@TransactionalEventListener
public void after(final AnyDeletedEvent event) {
LOG.debug("About to delete index for {}[{}]", event.getAnyTypeKind(), event.getAnyKey());
DeleteResponse response = client.prepareDelete(AuthContextUtils.getDomain().toLowerCase(), event.getAnyTypeKind().name(), event.getAnyKey()).get();
LOG.debug("Index successfully deleted for {}[{}]: {}", event.getAnyTypeKind(), event.getAnyKey(), response);
}
use of org.springframework.transaction.event.TransactionalEventListener in project dhis2-core by dhis2.
the class FileResourceEventListener method saveImageFile.
@TransactionalEventListener
@Async
public void saveImageFile(ImageFileSavedEvent imageFileSavedEvent) {
DateTime startTime = DateTime.now();
Map<ImageFileDimension, File> imageFiles = imageFileSavedEvent.getImageFiles();
FileResource fileResource = fileResourceService.getFileResource(imageFileSavedEvent.getFileResource());
String storageId = fileResourceContentStore.saveFileResourceContent(fileResource, imageFiles);
if (storageId != null) {
fileResource.setHasMultipleStorageFiles(true);
fileResourceService.updateFileResource(fileResource);
}
Period timeDiff = new Period(startTime, DateTime.now());
logMessage(storageId, fileResource, timeDiff);
}
use of org.springframework.transaction.event.TransactionalEventListener in project CzechIdMng by bcvsolutions.
the class DefaultProvisioningExecutor method executeInternal.
/**
* We need to wait to transaction commit, when provisioning is executed - all accounts have to be prepared.
* Next processing is executed outside a transaction
* => operation states has to be saved in new transactions
* => rollback on the target system is not possible anyway
*
* @param provisioningOperation
* @return
*/
@TransactionalEventListener
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public SysProvisioningOperationDto executeInternal(SysProvisioningOperationDto provisioningOperation) {
Assert.notNull(provisioningOperation, "Provisioning operation is required.");
Assert.notNull(provisioningOperation.getSystemEntity(), "System entity is required.");
Assert.notNull(provisioningOperation.getProvisioningContext(), "Provisioning context is required.");
//
try {
boolean checkNotExecuted = provisioningOperation.isSynchronousProvisioning();
if (provisioningOperationService.isNew(provisioningOperation)) {
provisioningOperation = persistOperation(provisioningOperation);
checkNotExecuted = true;
}
if (checkNotExecuted && provisioningOperation.getResult() != null && OperationState.NOT_EXECUTED == provisioningOperation.getResult().getState()) {
return provisioningOperation;
}
//
CoreEvent<SysProvisioningOperationDto> event = new CoreEvent<SysProvisioningOperationDto>(provisioningOperation.getOperationType(), provisioningOperation);
try {
// set a global provisioning timeout even for synchronous call
FutureTask<EventContext<SysProvisioningOperationDto>> futureTask = new FutureTask<EventContext<SysProvisioningOperationDto>>(new Callable<EventContext<SysProvisioningOperationDto>>() {
@Override
public EventContext<SysProvisioningOperationDto> call() {
return entityEventManager.process(event);
}
});
// thread pool is not used here
Thread thread = new Thread(new DelegatingSecurityContextRunnable(new DelegatingTransactionContextRunnable(futureTask)));
thread.start();
//
// global timeout by configuration
long timeout = provisioningConfiguration.getTimeout();
try {
// TODO: non blocking wait if possible (refactoring is needed + java 9 helps)
EventContext<SysProvisioningOperationDto> context = futureTask.get(timeout, TimeUnit.MILLISECONDS);
//
return context.getContent();
} catch (InterruptedException ex) {
futureTask.cancel(true);
// propagate exception to upper catch
throw ex;
} catch (TimeoutException ex) {
futureTask.cancel(true);
// put thread into queue and wait => timeout too => retry mecchanism will work
throw new ResultCodeException(AccResultCode.PROVISIONING_TIMEOUT, ImmutableMap.of("name", provisioningOperation.getSystemEntityUid(), "system", provisioningOperation.getSystem(), "operationType", provisioningOperation.getOperationType(), "objectClass", provisioningOperation.getProvisioningContext().getConnectorObject().getObjectClass(), "timeout", String.valueOf(timeout)), ex);
}
} catch (Exception ex) {
return provisioningOperationService.handleFailed(provisioningOperation, ex);
} finally {
try {
UUID roleRequestId = provisioningOperation.getRoleRequestId();
if (roleRequestId != null) {
// Check of the state for whole request
// Create mock request -> we don't wont load request from DB -> optimization
IdmRoleRequestDto mockRequest = new IdmRoleRequestDto();
mockRequest.setId(roleRequestId);
mockRequest.setState(RoleRequestState.EXECUTED);
IdmRoleRequestDto returnedReqeust = roleRequestService.refreshSystemState(mockRequest);
OperationResultDto systemState = returnedReqeust.getSystemState();
if (systemState == null) {
// State on system of request was not changed (may be not all provisioning operations are
// resolved)
} else {
// We have final state on systems
IdmRoleRequestDto requestDto = roleRequestService.get(roleRequestId);
if (requestDto != null) {
requestDto.setSystemState(systemState);
roleRequestService.save(requestDto);
} else {
LOG.info(MessageFormat.format("Refresh role-request system state: Role-request with ID [{0}] was not found (maybe was deleted).", roleRequestId));
}
}
}
} catch (Exception ex) {
return provisioningOperationService.handleFailed(provisioningOperation, ex);
}
}
} finally {
UUID eventId = provisioningOperation.getManualEventId();
if (eventId != null) {
IdmEntityEventDto startEvent = entityEventManager.getEvent(eventId);
if (startEvent != null) {
// Complete a manual event (for ensure end of the sync).
entityEventManager.completeManualEvent(startEvent);
}
}
}
}
Aggregations