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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
Source File: JobInstanceSqlMapDao.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Override
public JobInstance updateStateAndResult(final JobInstance jobInstance) {
    return (JobInstance) transactionTemplate.execute((TransactionCallback) status -> {
        transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                // Methods not extracted in order to make synchronization visible.
                synchronized (cacheKeyForJobPlan(jobInstance.getId())) {
                    removeCachedJobPlan(jobInstance);
                }
                synchronized (cacheKeyForActiveJobIds()) {
                    goCache.remove(cacheKeyForActiveJobIds());
                }
                String activeJobKey = cacheKeyForActiveJob(jobInstance.getId());
                synchronized (activeJobKey) {
                    goCache.remove(activeJobKey);
                }
                removeCachedJobInstance(jobInstance);
            }
        });
        logIfJobIsCompleted(jobInstance);
        updateStatus(jobInstance);
        updateResult(jobInstance);
        return jobInstance;
    });

}
 
Example #14
Source File: MaterialRepository.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void removeLatestCachedModification(final MaterialInstance materialInstance, Modification latest) {
    transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
            String cacheKey = latestMaterialModificationsKey(materialInstance);
            synchronized (cacheKey) {
                goCache.remove(cacheKey);
            }
        }
    });
}
 
Example #15
Source File: MaterialRepository.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void removeCachedModificationsFor(final MaterialInstance materialInstance) {
    transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
            String key = materialModificationsWithPaginationKey(materialInstance);
            synchronized (key) {
                goCache.remove(key);
            }
        }
    });
}
 
Example #16
Source File: MaterialRepository.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void removeCachedModificationCountFor(final MaterialInstance materialInstance) {
    transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
            String key = materialModificationCountKey(materialInstance);
            synchronized (key) {
                goCache.remove(key);
            }
        }
    });
}
 
Example #17
Source File: AgentDao.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void registerAfterCommitCallback(Runnable runnable) {
    synchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
            runnable.run();
        }
    });
}
 
Example #18
Source File: JobInstanceService.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void notifyJobCancelled(final JobInstance instance) {
    if (instance.isAssignedToAgent()) {
        transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                jobResultTopic.post(new JobResultMessage(instance.getIdentifier(), instance.getResult(), instance.getAgentUuid()));
            }
        });
    }
}
 
Example #19
Source File: StageService.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void notifyStageStatusChangeListeners(final Stage savedStage) {
    transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
            StageStatusListener[] prototype = new StageStatusListener[0];
            for (StageStatusListener stageStatusListener : stageStatusListeners.toArray(prototype)) {
                try {
                    stageStatusListener.stageStatusChanged(savedStage);
                } catch (Throwable e) {
                    LOGGER.error("error notifying listener for stage {}", savedStage, e);
                }
            }
        }
    });
}
 
Example #20
Source File: StageService.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void updateStageWithoutNotifications(final Stage stage, String username) {
    stage.calculateResult();
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    clearCachedCompletedStageFeeds(stage.getIdentifier().getPipelineName());
                }
            });
            stageDao.updateResult(stage, stage.getResult(), username);
        }
    });
}
 
Example #21
Source File: GoCache.java    From gocd with Apache License 2.0 5 votes vote down vote up
public void stopServingForTransaction() {
    if (transactionSynchronizationManager.isTransactionBodyExecuting() && !doNotServeForTransaction()) {
        doNotServeForTransaction.set(true);
        transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void beforeCompletion() {
                doNotServeForTransaction.set(false);
            }
        });
    }
}
 
Example #22
Source File: LazyCache.java    From gocd with Apache License 2.0 5 votes vote down vote up
public void flushOnCommit() {
    transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
            ehcache.flush();
        }
    });
}
 
Example #23
Source File: TransactionTemplateTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAllowRegistrationOfTransactionSynchronization_inTransactionSurroundingBlock_andExecuteAppropriateHooks() {
    final TransactionTemplate template = new TransactionTemplate(transactionTemplate);

    final boolean[] afterCommitHappened = new boolean[1];
    final boolean[] transactionWasActiveInSurrounding = new boolean[1];
    final boolean[] transactionWasActiveInTransaction = new boolean[1];

    String returnVal = (String) template.transactionSurrounding(new TransactionTemplate.TransactionSurrounding<RuntimeException>() {
        @Override
        public Object surrounding() {
            transactionWasActiveInSurrounding[0] = transactionSynchronizationManager.isTransactionBodyExecuting();

            transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override public void afterCommit() {
                    afterCommitHappened[0] = true;
                }
            });
            return template.execute(new org.springframework.transaction.support.TransactionCallback() {
                @Override
                public Object doInTransaction(TransactionStatus status) {
                    transactionWasActiveInTransaction[0] = transactionSynchronizationManager.isTransactionBodyExecuting();
                    return "foo";
                }
            });
        }
    });

    assertThat(returnVal, is("foo"));
    assertThat(afterCommitHappened[0], is(true));
    assertThat(transactionWasActiveInSurrounding[0], is(false));
    assertThat(transactionWasActiveInTransaction[0], is(true));
}
 
Example #24
Source File: TransactionTemplateTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void should_NOT_useSynchronizationsFromOneSurroundingBlockInAnother() {
    final 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 "foo";
        }
    });

    assertThat(returnVal, is("foo"));
    assertThat(afterCommitHappened[0], is(false));//because no transaction happened

    returnVal = (String) template.transactionSurrounding(new TransactionTemplate.TransactionSurrounding<RuntimeException>() {
        @Override
        public Object surrounding() {
            return template.execute(new org.springframework.transaction.support.TransactionCallback() {
                @Override
                public Object doInTransaction(TransactionStatus status) {
                    return "bar";
                }
            });
        }
    });

    assertThat(returnVal, is("bar"));
    assertThat(afterCommitHappened[0], is(false));//because it registered no synchronization
}
 
Example #25
Source File: TransactionTemplateTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@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>() {
            @Override
            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));
}
 
Example #26
Source File: TransactionTemplateTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void setTxnBodyActiveFlag(final boolean[] inTransactionInBody, final boolean[] inTransactionInAfterCommit, final boolean[] inTransactionInAfterComplete, final int depth) {
    inTransactionInBody[depth] = transactionSynchronizationManager.isTransactionBodyExecuting();

    transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override public void afterCommit() {
            inTransactionInAfterCommit[depth] = transactionSynchronizationManager.isTransactionBodyExecuting();
        }

        @Override public void afterCompletion(int status) {
            inTransactionInAfterComplete[depth] = transactionSynchronizationManager.isTransactionBodyExecuting();
        }
    });
}
 
Example #27
Source File: TransactionTemplateTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void registerSynchronization() {
    transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override public void afterCommit() {
            txnCommited = true;
        }

        @Override public void afterCompletion(int status) {
            txnCompleted = true;
        }
    });
}
 
Example #28
Source File: GitMaterial.java    From gocd with Apache License 2.0 5 votes vote down vote up
private GitCommand git(ConsoleOutputStreamConsumer outputStreamConsumer, final File workingFolder, int preferredCloneDepth, SubprocessExecutionContext executionContext) throws Exception {
    if (isSubmoduleFolder()) {
        return new GitCommand(getFingerprint(), new File(workingFolder.getPath()), GitMaterialConfig.DEFAULT_BRANCH, true, secrets());
    }

    GitCommand gitCommand = new GitCommand(getFingerprint(), workingFolder, getBranch(), false, secrets());
    if (!isGitRepository(workingFolder) || isRepositoryChanged(gitCommand, workingFolder)) {
        LOG.debug("Invalid git working copy or repository changed. Delete folder: {}", workingFolder);
        deleteDirectoryNoisily(workingFolder);
    }
    createParentFolderIfNotExist(workingFolder);
    if (!workingFolder.exists()) {
        TransactionSynchronizationManager txManager = new TransactionSynchronizationManager();
        if (txManager.isActualTransactionActive()) {
            txManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCompletion(int status) {
                    if (status != TransactionSynchronization.STATUS_COMMITTED) {
                        FileUtils.deleteQuietly(workingFolder);
                    }
                }
            });
        }
        int cloneDepth = shallowClone ? preferredCloneDepth : Integer.MAX_VALUE;
        int returnValue;
        if (executionContext.isServer()) {
            returnValue = gitCommand.cloneWithNoCheckout(outputStreamConsumer, urlForCommandLine());
        } else {
            returnValue = gitCommand.clone(outputStreamConsumer, urlForCommandLine(), cloneDepth);
        }
        bombIfFailedToRunCommandLine(returnValue, "Failed to run git clone command");
    }
    return gitCommand;
}
 
Example #29
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 #30
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);
	}
}