org.springframework.transaction.support.TransactionSynchronizationAdapter Java Examples

The following examples show how to use org.springframework.transaction.support.TransactionSynchronizationAdapter. 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
Source File: AllianceServiceImpl.java    From retro-game with GNU Affero General Public License v3.0 6 votes vote down vote up
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
Source File: PlatformTransactionManagerAdapter.java    From teiid-spring-boot with Apache License 2.0 6 votes vote down vote up
@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 File: UsageStatisticsReportingSqlMapDao.java    From gocd with 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 File: PipelineSqlMapDao.java    From gocd with 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 File: UserSqlMapDao.java    From gocd with 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 File: UserSqlMapDao.java    From gocd with 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 File: StageSqlMapDao.java    From gocd with 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 File: StageSqlMapDao.java    From gocd with 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 File: JobInstanceService.java    From gocd with 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 File: DataSharingSettingsService.java    From gocd with 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 File: StageService.java    From gocd with 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 File: TransactionTemplateTest.java    From gocd with 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
Source File: TransactionAwareCacheDecorator.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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
Source File: TransactionAwareCacheDecorator.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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
Source File: TransactionAwareCacheDecorator.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void clear() {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
			@Override
			public void afterCommit() {
				targetCache.clear();
			}
		});
	}
	else {
		this.targetCache.clear();
	}
}
 
Example #16
Source File: TransactionAwareCacheDecorator.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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
Source File: TransactionAwareCacheDecorator.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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
Source File: TransactionAwareCacheDecorator.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void clear() {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
			@Override
			public void afterCommit() {
				targetCache.clear();
			}
		});
	}
	else {
		this.targetCache.clear();
	}
}
 
Example #19
Source File: AllianceServiceImpl.java    From retro-game with GNU Affero General Public License v3.0 5 votes vote down vote up
@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
Source File: AllianceServiceImpl.java    From retro-game with GNU Affero General Public License v3.0 5 votes vote down vote up
@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
Source File: EventScheduler.java    From retro-game with GNU Affero General Public License v3.0 5 votes vote down vote up
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 File: RelatedContentService.java    From activiti6-boot2 with 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
Source File: TransactionAwareCacheDecorator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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
Source File: TransactionAwareCacheDecorator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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
Source File: TransactionAwareCacheDecorator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void clear() {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
			@Override
			public void afterCommit() {
				targetCache.clear();
			}
		});
	}
	else {
		this.targetCache.clear();
	}
}
 
Example #26
Source File: TransactionAwareSessionContext.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * 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
Source File: EventPublishingEntityListenerAdapter.java    From integration-patterns with MIT License 5 votes vote down vote up
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
Source File: TransactionAwareCacheDecorator.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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
Source File: TransactionAwareCacheDecorator.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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
Source File: TransactionAwareCacheDecorator.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void clear() {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
			@Override
			public void afterCommit() {
				targetCache.clear();
			}
		});
	}
	else {
		this.targetCache.clear();
	}
}