Java Code Examples for org.springframework.transaction.support.TransactionSynchronizationAdapter

The following examples show how to use org.springframework.transaction.support.TransactionSynchronizationAdapter. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private void joinAlliance(Alliance alliance, User user) {
  AllianceMemberKey key = new AllianceMemberKey();
  key.setAlliance(alliance);
  key.setUser(user);

  Date now = Date.from(Instant.ofEpochSecond(Instant.now().getEpochSecond()));

  AllianceMember member = new AllianceMember();
  member.setKey(key);
  member.setRank(null);
  member.setJoinedAt(now);
  allianceMemberRepository.save(member);

  // Update cache.
  long allianceId = alliance.getId();
  long userId = user.getId();
  TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
    @Override
    public void afterCommit() {
      userAllianceCache.updateUserAlliance(userId, allianceId);
    }
  });
}
 
Example 2
@Override
public void registerSynchronization(final Synchronization synch)
        throws IllegalStateException, RollbackException, SystemException {
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void beforeCompletion() {
            synch.beforeCompletion();
        }

        @Override
        public void afterCompletion(int status) {
            switch (status) {
            case TransactionSynchronization.STATUS_COMMITTED:
                status = Status.STATUS_COMMITTED;
                break;
            case TransactionSynchronization.STATUS_ROLLED_BACK:
                status = Status.STATUS_ROLLEDBACK;
                break;
            case TransactionSynchronization.STATUS_UNKNOWN:
                status = Status.STATUS_UNKNOWN;
                break;
            }
            synch.afterCompletion(status);
        }
    });
}
 
Example 3
Source Project: gocd   Source File: UsageStatisticsReportingSqlMapDao.java    License: Apache License 2.0 6 votes vote down vote up
public void saveOrUpdate(UsageStatisticsReporting usageStatisticsReporting) {
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            synchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    String cacheKey = cacheKeyForUsageStatisticsReporting();
                    synchronized (cacheKey) {
                        goCache.remove(cacheKey);
                    }
                }
            });

            sessionFactory.getCurrentSession().saveOrUpdate(usageStatisticsReporting);
        }
    });
}
 
Example 4
Source Project: gocd   Source File: PipelineSqlMapDao.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Pipeline save(final Pipeline pipeline) {
    return (Pipeline) transactionTemplate.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    goCache.remove(cacheKeyForLatestPipelineIdByPipelineName(pipeline.getName()));
                    invalidateCacheConditionallyForPipelineInstancesTriggeredWithDependencyMaterial(pipeline);
                }
            });

            pipelineByBuildIdCache.flushOnCommit();
            getSqlMapClientTemplate().insert("insertPipeline", pipeline);
            savePipelineMaterialRevisions(pipeline, pipeline.getId());
            environmentVariableDao.save(pipeline.getId(), EnvironmentVariableType.Trigger, pipeline.scheduleTimeVariables());
            return pipeline;
        }
    });
}
 
Example 5
Source Project: gocd   Source File: UserSqlMapDao.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void saveOrUpdate(final User user) {
    assertUserNotAnonymous(user);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    clearEnabledUserCountFromCache();
                }
            });
            sessionFactory.getCurrentSession().saveOrUpdate(copyLoginToDisplayNameIfNotPresent(user));
        }
    });
}
 
Example 6
Source Project: gocd   Source File: UserSqlMapDao.java    License: Apache License 2.0 6 votes vote down vote up
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();
        }
    });
}
 
Example 7
Source Project: gocd   Source File: StageSqlMapDao.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Stage save(final Pipeline pipeline, final Stage stage) {
    return (Stage) transactionTemplate.execute((TransactionCallback) status -> {
        transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                String pipelineName = pipeline.getName();
                String stageName = stage.getName();

                clearStageHistoryPageCaches(stage, pipelineName, false);
                clearCachedStage(stage.getIdentifier());
                clearCachedAllStages(pipelineName, pipeline.getCounter(), stageName);
                removeFromCache(cacheKeyForStageCountForGraph(pipelineName, stageName));
            }
        });
        stage.setPipelineId(pipeline.getId());
        int maxStageCounter = getMaxStageCounter(pipeline.getId(), stage.getName());
        stage.setCounter(maxStageCounter + 1);

        getSqlMapClientTemplate().update("markPreviousStageRunsAsNotLatest", arguments("stageName", stage.getName()).and("pipelineId", pipeline.getId()).asMap());
        getSqlMapClientTemplate().insert("insertStage", stage);

        stage.setIdentifier(new StageIdentifier(pipeline, stage));
        return stage;
    });
}
 
Example 8
Source Project: gocd   Source File: StageSqlMapDao.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void updateResult(final Stage stage, final StageResult result, String username) {
    transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
            StageIdentifier identifier = stage.getIdentifier();
            clearStageHistoryPageCaches(stage, identifier.getPipelineName(), true);
            clearJobStatusDependentCaches(stage.getId(), identifier);
            removeFromCache(cacheKeyForStageCountForGraph(identifier.getPipelineName(), identifier.getStageName()));
        }
    });
    getSqlMapClientTemplate().update("updateStageStatus", arguments("stageId", stage.getId())
        .and("result", result.toString())
        .and("state", stage.getState())
        .and("cancelledBy", username)
        .and("completedByTransitionId", stage.getCompletedByTransitionId()).asMap());

    upddateLastTransitionedTime(stage);
}
 
Example 9
Source Project: gocd   Source File: JobInstanceService.java    License: Apache License 2.0 6 votes vote down vote up
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);
                }
        }
    });
}
 
Example 10
Source Project: gocd   Source File: DataSharingSettingsService.java    License: Apache License 2.0 6 votes vote down vote up
public void createOrUpdate(DataSharingSettings dataSharingSettings) {
    synchronized (mutexForDataSharingSettings) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                    @Override
                    public void afterCommit() {
                        entityHashingService.removeFromCache(dataSharingSettings, Long.toString(dataSharingSettings.getId()));
                        dataSharingSettingsSqlMapDao.invalidateCache();
                    }
                });
                try {
                    dataSharingSettingsSqlMapDao.saveOrUpdate(dataSharingSettings);
                } catch (DataSharingSettingsSqlMapDao.DuplicateDataSharingSettingsException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        dataSharingSettingsChangeListeners
                .stream()
                .forEach(listener -> listener.onDataSharingSettingsChange(dataSharingSettings));
    }
}
 
Example 11
Source Project: gocd   Source File: StageService.java    License: Apache License 2.0 6 votes vote down vote up
public synchronized void cancelStage(final Stage stage, String username) {
    cancel(stage, username);
    notifyStageStatusChangeListeners(stage);
    //Send a notification only if none of the jobs are assigned.
    // If any of the jobs are assigned. JobStatusListener.onMessage will send the stage cancel notification.
    transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
            JobInstances jobInstances = stage.getJobInstances();
            boolean noJobIsAssigned = jobInstances.stream().noneMatch(JobInstance::isAssignedToAgent);
            if (noJobIsAssigned) {
                stageStatusTopic.post(new StageStatusMessage(stage.getIdentifier(), stage.stageState(), stage.getResult(), SessionUtils.currentUsername()));
            }
        }
    });
}
 
Example 12
Source Project: gocd   Source File: TransactionTemplateTest.java    License: Apache License 2.0 6 votes vote down vote up
@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>() {
        @Override
        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));
}
 
Example 13
@Override
public void put(final Object key, @Nullable final Object value) {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
			@Override
			public void afterCommit() {
				TransactionAwareCacheDecorator.this.targetCache.put(key, value);
			}
		});
	}
	else {
		this.targetCache.put(key, value);
	}
}
 
Example 14
@Override
public void evict(final Object key) {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
			@Override
			public void afterCommit() {
				TransactionAwareCacheDecorator.this.targetCache.evict(key);
			}
		});
	}
	else {
		this.targetCache.evict(key);
	}
}
 
Example 15
@Override
public void clear() {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
			@Override
			public void afterCommit() {
				targetCache.clear();
			}
		});
	}
	else {
		this.targetCache.clear();
	}
}
 
Example 16
@Override
public void put(final Object key, @Nullable final Object value) {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
			@Override
			public void afterCommit() {
				TransactionAwareCacheDecorator.this.targetCache.put(key, value);
			}
		});
	}
	else {
		this.targetCache.put(key, value);
	}
}
 
Example 17
@Override
public void evict(final Object key) {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
			@Override
			public void afterCommit() {
				TransactionAwareCacheDecorator.this.targetCache.evict(key);
			}
		});
	}
	else {
		this.targetCache.evict(key);
	}
}
 
Example 18
@Override
public void clear() {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
			@Override
			public void afterCommit() {
				targetCache.clear();
			}
		});
	}
	else {
		this.targetCache.clear();
	}
}
 
Example 19
@Override
@Transactional(isolation = Isolation.REPEATABLE_READ)
public void leave(long bodyId, long allianceId) {
  UserAndAllianceAndMemberTuple tuple = getUserAndAllianceAndMember(allianceId);
  long userId = tuple.user.getId();

  if (tuple.alliance.getOwner().getId() == userId) {
    logger.warn("Leaving alliance failed, the owner cannot leave: userId={} allianceId={}", userId, allianceId);
    throw new OwnerCannotLeaveException();
  }

  AllianceMember member = tuple.member;
  if (member == null) {
    logger.warn("Leaving alliance failed, user is not a member of the alliance: userId={} allianceId={}",
        userId, allianceId);
    throw new UserIsNotAMemberException();
  }

  logger.info("Leaving alliance successful: userId={} allianceId={}", userId, allianceId);
  allianceMemberRepository.delete(member);

  // Update cache.
  TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
    @Override
    public void afterCommit() {
      userAllianceCache.removeUserAlliance(userId);
    }
  });
}
 
Example 20
@Override
@Transactional(isolation = Isolation.REPEATABLE_READ)
public void disband(long bodyId, long allianceId, String password) {
  if (!userServiceInternal.checkCurrentUserPassword(password)) {
    throw new WrongPasswordException();
  }

  UserAndAllianceAndMemberTuple tuple = getUserAndAllianceAndMember(allianceId);
  Alliance alliance = tuple.alliance;

  int privileges = getPrivileges(tuple.user, alliance, tuple.member);
  if (!hasPrivilege(privileges, AlliancePrivilege.DISBAND_ALLIANCE)) {
    logger.warn("Disbanding alliance failed, unauthorized access: userId={} allianceId={}", tuple.user.getId(),
        allianceId);
    throw new UnauthorizedAllianceAccessException();
  }

  // Get members for the update of cache.
  List<Long> memberIds = alliance.getMembers().stream()
      .map(m -> m.getUser().getId())
      .collect(Collectors.toList());

  logger.info("Disbanding alliance successful: userId={} allianceId={}", tuple.user.getId(), allianceId);
  allianceRepository.delete(alliance);

  // Update cache.
  TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
    @Override
    public void afterCommit() {
      for (Long id : memberIds) {
        userAllianceCache.removeUserAlliance(id);
      }
      allianceTagCache.removeTag(allianceId);
    }
  });
}
 
Example 21
void schedule(Event event) {
  eventRepository.save(event);
  TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
    @Override
    public void afterCommit() {
      try {
        lock.lock();
        condition.signal();
      } finally {
        lock.unlock();
      }
    }
  });
}
 
Example 22
Source Project: activiti6-boot2   Source File: RelatedContentService.java    License: Apache License 2.0 5 votes vote down vote up
@Transactional
public void deleteRelatedContent(RelatedContent content) {
    if (content.getContentStoreId() != null) {
        final String storeId = content.getContentStoreId();
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                contentStorage.deleteContentObject(storeId);
            }
        });
    }
    
    contentRepository.delete(content);
}
 
Example 23
@Override
public void put(final Object key, final Object value) {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
			@Override
			public void afterCommit() {
				TransactionAwareCacheDecorator.this.targetCache.put(key, value);
			}
		});
	}
	else {
		this.targetCache.put(key, value);
	}
}
 
Example 24
@Override
public void evict(final Object key) {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
			@Override
			public void afterCommit() {
				TransactionAwareCacheDecorator.this.targetCache.evict(key);
			}
		});
	}
	else {
		this.targetCache.evict(key);
	}
}
 
Example 25
@Override
public void clear() {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
			@Override
			public void afterCommit() {
				targetCache.clear();
			}
		});
	}
	else {
		this.targetCache.clear();
	}
}
 
Example 26
/**
    * 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);
    }
};
   }
 
Example 27
private void fireEvent(EventSource entity, DomainEvent event, String action) {
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
            eventPublisher.publishEvent(event.message(EventPublishingEntityListenerAdapter.this));
            LOG.debug("Published {} event for {} with id {}, version {}", action, entity.getClass(), entity.getId(),
                    entity.getVersion());
        }
    });
}
 
Example 28
@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);
	}
}
 
Example 29
@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);
	}
}
 
Example 30
@Override
public void clear() {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
			@Override
			public void afterCommit() {
				targetCache.clear();
			}
		});
	}
	else {
		this.targetCache.clear();
	}
}