Search in sources :

Example 1 with TransactionalEventListener

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);
        }
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity) ProjectStateChangedEvent(de.tudarmstadt.ukp.clarin.webanno.api.event.ProjectStateChangedEvent) ProjectStateChangeMessage(de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.webhooks.json.ProjectStateChangeMessage) DocumentStateChangedEvent(de.tudarmstadt.ukp.clarin.webanno.api.event.DocumentStateChangedEvent) AnnotationStateChangeMessage(de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.webhooks.json.AnnotationStateChangeMessage) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) RestTemplate(org.springframework.web.client.RestTemplate) AnnotationStateChangeEvent(de.tudarmstadt.ukp.clarin.webanno.api.event.AnnotationStateChangeEvent) DocumentStateChangeMessage(de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.webhooks.json.DocumentStateChangeMessage) Async(org.springframework.scheduling.annotation.Async) TransactionalEventListener(org.springframework.transaction.event.TransactionalEventListener)

Example 2 with TransactionalEventListener

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);
    }
}
Also used : UpdateResponse(org.elasticsearch.action.update.UpdateResponse) IndexResponse(org.elasticsearch.action.index.IndexResponse) GetResponse(org.elasticsearch.action.get.GetResponse) TransactionalEventListener(org.springframework.transaction.event.TransactionalEventListener)

Example 3 with TransactionalEventListener

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);
}
Also used : DeleteResponse(org.elasticsearch.action.delete.DeleteResponse) TransactionalEventListener(org.springframework.transaction.event.TransactionalEventListener)

Example 4 with TransactionalEventListener

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);
}
Also used : Period(org.joda.time.Period) File(java.io.File) DateTime(org.joda.time.DateTime) Async(org.springframework.scheduling.annotation.Async) TransactionalEventListener(org.springframework.transaction.event.TransactionalEventListener)

Example 5 with TransactionalEventListener

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);
            }
        }
    }
}
Also used : ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) OperationResultDto(eu.bcvsolutions.idm.core.api.dto.OperationResultDto) TimeoutException(java.util.concurrent.TimeoutException) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) EventContext(eu.bcvsolutions.idm.core.api.event.EventContext) FutureTask(java.util.concurrent.FutureTask) CoreEvent(eu.bcvsolutions.idm.core.api.event.CoreEvent) DelegatingSecurityContextRunnable(org.springframework.security.concurrent.DelegatingSecurityContextRunnable) UUID(java.util.UUID) SysProvisioningOperationDto(eu.bcvsolutions.idm.acc.dto.SysProvisioningOperationDto) DelegatingTransactionContextRunnable(eu.bcvsolutions.idm.core.config.DelegatingTransactionContextRunnable) IdmRoleRequestDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleRequestDto) TimeoutException(java.util.concurrent.TimeoutException) IdmEntityEventDto(eu.bcvsolutions.idm.core.api.dto.IdmEntityEventDto) TransactionalEventListener(org.springframework.transaction.event.TransactionalEventListener) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

TransactionalEventListener (org.springframework.transaction.event.TransactionalEventListener)8 Async (org.springframework.scheduling.annotation.Async)4 DateTime (org.joda.time.DateTime)3 Period (org.joda.time.Period)3 File (java.io.File)2 UUID (java.util.UUID)2 Transactional (org.springframework.transaction.annotation.Transactional)2 AnnotationStateChangeEvent (de.tudarmstadt.ukp.clarin.webanno.api.event.AnnotationStateChangeEvent)1 DocumentStateChangedEvent (de.tudarmstadt.ukp.clarin.webanno.api.event.DocumentStateChangedEvent)1 ProjectStateChangedEvent (de.tudarmstadt.ukp.clarin.webanno.api.event.ProjectStateChangedEvent)1 AnnotationStateChangeMessage (de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.webhooks.json.AnnotationStateChangeMessage)1 DocumentStateChangeMessage (de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.webhooks.json.DocumentStateChangeMessage)1 ProjectStateChangeMessage (de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.webhooks.json.ProjectStateChangeMessage)1 SysProvisioningOperationDto (eu.bcvsolutions.idm.acc.dto.SysProvisioningOperationDto)1 IdmEntityEventDto (eu.bcvsolutions.idm.core.api.dto.IdmEntityEventDto)1 IdmRoleRequestDto (eu.bcvsolutions.idm.core.api.dto.IdmRoleRequestDto)1 OperationResultDto (eu.bcvsolutions.idm.core.api.dto.OperationResultDto)1 CoreEvent (eu.bcvsolutions.idm.core.api.event.CoreEvent)1 EventContext (eu.bcvsolutions.idm.core.api.event.EventContext)1 ResultCodeException (eu.bcvsolutions.idm.core.api.exception.ResultCodeException)1