private void handleComposeMessageCreateCommand(final Object obj) throws IOException { final ComposeMessageCreateCommand cmd = (ComposeMessageCreateCommand) obj; final Message message = new MessageBuilder().transferId(cmd.getTransferId()) .messageState(MessageState.TO_COMPOSE).build(); message.setInternalData(InternalDataUtils.convertInternalDataToJson(cmd.getData())); final BasicOutboundConfiguration configuration = basicConfigurationRepository.findOne(cmd.getConfigId()); message.setOutboundConfiguration(configuration); messageRepository.save((MessageImpl) message); final String actorId = getContext().parent().path().name(); TransactionSynchronizationManager .registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { LOG.info("Saved new [{}]", message); getSender().tell(new ComposeMessageCreatedEvent(actorId, message.getId()), getSelf()); stop(); } }); }
@Override public void execute(final AssignUsersMessage.Request request) throws Exception { request.getUserAssignments().forEach(assignment -> { final Subject subject = subjectRepository .getSubjectForSubjectModelInProcess(request.getPiId(), assignment.getSmId()); if (subject != null) { subject.setUser(assignment.getUserId()); subjectRepository.save((SubjectImpl) subject); LOG.info("New user for subject: {}", subject); } }); final ActorRef sender = getSender(); TransactionSynchronizationManager .registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { sender.tell(new AssignUsersMessage.Response(), getSelf()); } }); }
private void handleStoreExternalDataCommand(final Object obj) { final StoreExternalDataCommand cmd = (StoreExternalDataCommand) obj; final Message message = messageRepository.findOne(cmd.getId()); message.setExternalData(cmd.getData()); message.setMessageState(MessageState.COMPOSED); messageRepository.save((MessageImpl) message); final String actorId = getContext().parent().path().name(); final ActorRef sender = getSender(); TransactionSynchronizationManager .registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { LOG.info("Updated external data of [{}]", message); sender.tell(new ComposedMessageEvent(actorId, message.getId()), getSelf()); stop(); } }); }
@PostUpdate @Async public void postUpdate(Object object) { LOG.info("Listening to post update for object:" + object); // Entitys have to be annotated with @EventListeners and reference this class in that annotation, because of this // the usages of this class are not executed withing the handle of the Spring context. So now we have to use this funky // ass way of wiring in fields AS this method is being called. #sadface AutowireHelper.autowire(this); // Trying to just add @Transactional(Transactional.TxType.REQUIRES_NEW) to this method didn't work at all, it was just being ignored. // This wrapper is what ended up working. TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCompletion(int status) { super.afterCompletion(status); List<Webhook> hooks = webhookManager.retrieveWebhooksByEntityNameAndEventType(object.getClass().getSimpleName(), "post-update"); hooks.stream().forEach(wh -> webhookProcessor.notifyWebhook(wh, object)); } }); }
private void sendMail(final HarvestPermit permit, final GameSpecies species) { final Set<String> emails = findEmails(permit); final AllPartnersFinishedHuntingMailService.MailData data = getMailData(permit, species); TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { try { // NOTE: Must invoke through proxy to make sure new transaction is started mailService.sendEmailAsync(emails, data); } catch (RuntimeException ex) { // Exception should be handled, so that HTTP status code is not altered LOG.error("Error occurred while sending emails", ex); } } }); }
@Override public void storeFile(final FileType fileType, final PersistentFileMetadata metadata, final InputStream inputStream) throws IOException { final Path storageFolder = fileType.resolveLocalStorageFolder(this.storageBasePath); final Path storageFile = storageFolder.resolve(fileType.formatFilename(metadata)); TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCompletion(final int status) { // Remove file if transaction is rolled back if (status == STATUS_ROLLED_BACK) { deleteIfExists(storageFile, false); } } }); metadata.setResourceUrl(storageFile.toUri().toURL()); try { Files.copy(inputStream, storageFile, StandardCopyOption.REPLACE_EXISTING); } finally { inputStream.close(); } }
@Override @Transactional public T create(final T object) { validateCredentials(); final T createdInstance = repository.create(object); TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { if (allowCreateEvent) { sendEvent((Long) getId(createdInstance), CREATE); } } }); return createdInstance; }
@Override @Transactional public T update(final T object) { if (JDOHelper.getObjectState(object) == ObjectState.TRANSIENT) { return updateFromTransient(object); } else { validateCredentials(object); updateModificationData(object); final T updatedInstance = repository.update(object); TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { if (allowUpdateEvent) { sendEvent((Long) getId(updatedInstance), UPDATE); } } }); return updatedInstance; } }
@Transactional public Team changeSingleTeamHost(final ChangeTeamHost changeTeamHost) { final String teamKey = changeTeamHost.getTeamKey(); final String hostingParticipantKey = changeTeamHost.getHostingParticipantKey(); final Team team = repository.loadSingleTeamWithVisitationPlan(teamKey, false); validateChangeTeamHost(changeTeamHost, team); changeSingleTeamHost(team, hostingParticipantKey); // Publish event only after transaction is successfully committed: TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { eventPublisher.notifyTeamHostChangeByParticipant(team, changeTeamHost); } }); return team; }
public void associateCookie(final AgentIdentifier agentIdentifier, final String cookie) { final String uuid = agentIdentifier.getUuid(); final String key = agentCacheKey(uuid); synchronized (key) { transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { Agent agent = fetchAgentByUuid(uuid); if (agent == null) { agent = new Agent(uuid, cookie, agentIdentifier.getHostName(), agentIdentifier.getIpAddress()); } else { agent.update(cookie, agentIdentifier.getHostName(), agentIdentifier.getIpAddress()); } getHibernateTemplate().saveOrUpdate(agent); synchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { cache.remove(key); } }); } }); } }
public Pipeline save(final Pipeline pipeline) { return (Pipeline) transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { goCache.remove(cacheKeyForLatestPipelineIdByPipelineName(pipeline.getName())); invalidateCacheConditionallyForPipelineInstancesTriggeredWithDependencyMaterial(pipeline); } }); Long pipelineId = (Long) getSqlMapClientTemplate().insert("insertPipeline", pipeline); savePipelineMaterialRevisions(pipeline, pipelineId); environmentVariableDao.save(pipelineId, EnvironmentVariableType.Trigger, pipeline.scheduleTimeVariables()); return pipeline; } }); }
public void unlockPipeline(final String pipelineName) { synchronized (pipelineLockStateCacheKey(pipelineName)) { transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { clearLockedPipelineStateCache(pipelineName); } }); final String cacheKey = pipelineLockStateCacheKey(pipelineName); PipelineState fromCache = pipelineStateFor(pipelineName); PipelineState toBeSaved = null; if (fromCache == null) { toBeSaved = new PipelineState(pipelineName); } else { toBeSaved = (PipelineState) sessionFactory.getCurrentSession().load(PipelineState.class, fromCache.getId()); } toBeSaved.unlock(); sessionFactory.getCurrentSession().saveOrUpdate(toBeSaved); } }); } }
private void changeEnabledStatus(final List<String> usernames, final boolean enabled) { transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { clearEnabledUserCountFromCache(); } }); String queryString = String.format("update %s set enabled = :enabled where name in (:userNames)", User.class.getName()); Query query = sessionFactory.getCurrentSession().createQuery(queryString); query.setParameter("enabled", enabled); query.setParameterList("userNames", usernames); query.executeUpdate(); } }); }
private void notifyJobStatusChangeListeners(final JobInstance job) { transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { List<JobStatusListener> listeners1; synchronized (LISTENERS_MODIFICATION_MUTEX) { listeners1 = new ArrayList<>(listeners); } for (JobStatusListener jobStatusListener : listeners1) try { jobStatusListener.jobStatusChanged(job); } catch (Exception e) { LOGGER.error("error notifying listener for job {}", job, e); } } }); }
@Test public void shouldAllowRegistrationOfTransactionSynchronization_inTransactionSurroundingBlock_andNotExecuteSynchronizationIfTransactionNeverHappens() { TransactionTemplate template = new TransactionTemplate(transactionTemplate); final boolean[] afterCommitHappened = new boolean[1]; String returnVal = (String) template.transactionSurrounding(new TransactionTemplate.TransactionSurrounding<RuntimeException>() { public Object surrounding() { transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { afterCommitHappened[0] = true; } }); return "bar"; } }); assertThat(returnVal, is("bar")); assertThat(afterCommitHappened[0], is(false)); }
@Test public void shouldPropagateExceptionsOutOfTransactionSurrounding() throws IOException { TransactionTemplate template = new TransactionTemplate(transactionTemplate); final boolean[] afterCommitHappened = new boolean[1]; String returnVal = null; try { returnVal = (String) template.transactionSurrounding(new TransactionTemplate.TransactionSurrounding<IOException>() { public Object surrounding() throws IOException { transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { afterCommitHappened[0] = true; } }); throw new IOException("boo ha!"); } }); fail("should have propagated exception"); } catch (IOException e) { assertThat(e.getMessage(), is("boo ha!")); } assertThat(returnVal, nullValue()); assertThat(afterCommitHappened[0], is(false)); }
@EventListener public void blogAddedTransactionalOldSchool(final BlogAddedEvent blogAddedEvent) { //Note: *Old school* transaction handling before Spring 4.2 if (TransactionSynchronizationManager.isActualTransactionActive()) { //To not fail with "java.lang.IllegalStateException: Transaction synchronization is not active" TransactionSynchronizationManager.registerSynchronization( new TransactionSynchronizationAdapter() { @Override public void afterCommit() { internalSendBlogAddedNotification(blogAddedEvent); } }); } else { log.warn("No active transaction found. Sending notification immediately."); internalSendBlogAddedNotification(blogAddedEvent); } }
private void handleStateObjectChangeMessage(final StateObjectChangeMessage.Request request) throws Exception { final SubjectState subjectState = Optional .ofNullable( subjectStateRepository.getSubjectStateOfUser(request.getPiId(), request.getUserId())) .get(); sender = getSender(); final ActorRef bussinessObjectCheckActor = getContext().actorOf( springExtension.props("BusinessObjectCheckActor", subjectState.getCurrentState().getSId()), UUID.randomUUID().toString()); // must block thread since transaction is lost when using completable future final Future<Object> future = Patterns.ask(bussinessObjectCheckActor, request, Global.TIMEOUT); final boolean correct = ((Boolean) Await.result(future, Global.TIMEOUT.duration())).booleanValue(); if (!correct) { sender.tell(new Status.Failure( new IllegalArgumentException("Check of business objects returned false")), getSelf()); } else { initBusinessObjectInstances(subjectState, request); setValuesOfBusinessObjectFieldInstances(subjectState.getCurrentState(), request); sendMessages(subjectState, request); TransactionSynchronizationManager .registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { sender.tell(new EmptyMessage(), getSelf()); handleAdditionalActions(subjectState); } }); } }
@Override public void execute(final MessagesSendMessage.Request request) throws Exception { final List<CompletableFuture<Object>> futures = request.getUserMessageFlowIds() .stream().map(userMessageFlow -> convertToFuture(request.getPiId(), userMessageFlow.getLeft(), userMessageFlow.getRight())) .collect(Collectors.toList()); final ActorRef sender = getSender(); try { CompletableFuture.allOf(Iterables.toArray(futures, CompletableFuture.class)).get(); LOG.info("All users received the message in PI_ID [{}]", request.getPiId()); final SubjectState sendState = subjectStateRepository.findOne(request.getSendSubjectState()); sendState.setToSent(); subjectStateRepository.save((SubjectStateImpl) sendState); LOG.debug("{} is set to 'SENT'", sendState); } catch (final Exception e) { LOG.error("At least one user did not receive the message in PI_ID [{}]", request.getPiId()); sender.tell( new Status.Failure(new IllegalStateException( "Could not send message to all users in PI_ID [" + request.getPiId() + "]")), getSelf()); } TransactionSynchronizationManager .registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { sender.tell(new MessagesSendMessage.Response(), getSelf()); } }); }
@Override public void execute(final ProcessStopMessage.Request msg) throws Exception { final Optional<ProcessInstance> processOpt = Optional.ofNullable(processInstanceRepository.findOne(msg.getPiId())); if (!processOpt.isPresent()) { throw new IllegalArgumentException(); } final ProcessInstance process = processOpt.get(); if (!process.getState().equals(ProcessInstanceState.ACTIVE)) { throw new IllegalStateException(); } process.setState(ProcessInstanceState.CANCELLED_BY_USER); TransactionSynchronizationManager .registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { LOG.info("Process was stopped: {}", process); final ProcessInfoDTO dto = new ProcessInfoDTO(process.getPiId(), process.getStartTime(), process.getEndTime(), process.getProcessModel().getName(), process.getStartUserId(), process.getState().name()); getSender().tell(new ProcessStopMessage.Response(dto), getSelf()); callback(); } }); }
protected void publishEventAfterCommit(final ApplicationEvent<?> event) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { eventService.publishApplicationEvent(event); } }); }
private void publishEventAfterCommit(final ApplicationEvent<?> event) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { eventService.publishApplicationEvent(event); } }); }
protected void perItemPostProcess(final ItemOperationParams params) { final List<ApplicationEvent<?>> eventList = new ArrayList<ApplicationEvent<?>>(params.getAfterCommitEvents()); final List<Runnable> afterCommitHooks = new ArrayList<Runnable>(params.getAfterCommit()); TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { afterCommitOne(eventList, afterCommitHooks); } }); }
private void postProcessParameters(final ItemOperationParams params) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { afterCommitAll(params); } }); }
@Override public void put(final Object key, final Object value) { if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { targetCache.put(key, value); } }); } else { this.targetCache.put(key, value); } }
@Override public void evict(final Object key) { if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { targetCache.evict(key); } }); } else { this.targetCache.evict(key); } }
/** * Creates a transaction synchronization object for the specified session. * * @param session * Session to synchronize using the created object. Cannot be null. * @return A valid transaction synchronization. Never returns null. */ private TransactionSynchronization createTransactionSynchronization(final Session session) { return new TransactionSynchronizationAdapter() { @Override public void afterCompletion(final int status) { session.close(); ManagedSessionContext.unbind(sessionFactory); } }; }
@Override public void put(final Object key, final Object value, final long expiration) { if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { targetCache.put(key, value, expiration); } }); } else { this.targetCache.put(key, value, expiration); } }
private void sendNotificationEmail(final HuntingClub club, final SystemUser activeUser, final Occupation contactPerson, final Organisation rhy) { // Send notification email after transaction has committed successfully final HuntingClubDTO clubDTO = HuntingClubDTO.create(club, false, null, null); final OccupationDTO occupationDTO = OccupationDTO.createWithPerson(contactPerson); final OrganisationNameDTO rhyDTO = OrganisationNameDTO.create(rhy); final String contactPersonEmail = activeUser.getEmail(); final Iterable<String> rhyContactEmails = registerHuntingClubMailService.getRhyContactEmails(rhy); TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { try { // NOTE: Must invoke through proxy to make sure new transaction is started registerHuntingClubMailService.sendNotificationEmail( clubDTO, occupationDTO, rhyDTO, rhyContactEmails, contactPersonEmail); } catch (RuntimeException ex) { // Exception should be handled, so that HTTP status code is not altered LOG.error("Error occured while sending notification emails", ex); } } }); }
private static void doLogAfterTransaction(final String msg) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { doLog(msg); } }); }
@Override public void removeFromStorage(PersistentFileMetadata metadata) { final Path storageFile = getFileStoragePath(metadata); // Delay until transaction has completed with success. TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { deleteIfExists(storageFile, true); } }); }
@Override public void removeFromStorage(final PersistentFileMetadata metadata) { // Invoked before session closed final S3Util.BucketObjectPair s3Object = S3Util.parseResourceURL(metadata.getResourceUrl()); // Delay S3 object delete until transaction is complete and successful TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { removeInternal(s3Object); } }); }
@Override public void clear() { if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { targetCache.clear(); } }); } else { this.targetCache.clear(); } }
/** * Invoked on both the PostPersist and PostUpdate. The default implementation is to simply publish a Spring event * to the ApplicationContext after the transaction has completed. * * @param entity the newly-persisted Customer * @see CustomerPersistedEvent */ @PostPersist @PostUpdate public void customerUpdated(final Object entity) { if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { ApplicationContextHolder.getApplicationContext().publishEvent(new CustomerPersistedEvent((Customer) entity)); } }); } }
/** * Invoked on both the PostPersist and PostUpdate. The default implementation is to simply publish a Spring event * to the ApplicationContext to allow an event listener to respond appropriately (like resetting the current cart * in CartState) * * @param entity the newly-persisted Order * @see OrderPersistedEvent */ @PostPersist @PostUpdate public void customerUpdated(final Object entity) { if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { ApplicationContextHolder.getApplicationContext().publishEvent(new OrderPersistedEvent((Order) entity)); } }); } }
/** * * * @see org.cucina.engine.client.service.TransactionHandler#registerTxHandler * (java.lang.String, java.io.Serializable) */ @Override public void registerTxHandler(final String entityType, final Serializable... ids) { if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCompletion(int status) { handleStatus(status, entityType, ids); } }); } }