use of org.springframework.transaction.support.TransactionCallback in project gocd by gocd.
the class BuildAssignmentService method createWork.
private Work createWork(final AgentInstance agent, final JobPlan job) {
try {
return (Work) transactionTemplate.transactionSurrounding(new TransactionTemplate.TransactionSurrounding<RuntimeException>() {
public Object surrounding() {
final String agentUuid = agent.getUuid();
// TODO: Use fullPipeline and get the Stage from it?
final Pipeline pipeline;
try {
pipeline = scheduledPipelineLoader.pipelineWithPasswordAwareBuildCauseByBuildId(job.getJobId());
} catch (StaleMaterialsOnBuildCause e) {
return NO_WORK;
}
List<Task> tasks = goConfigService.tasksForJob(pipeline.getName(), job.getIdentifier().getStageName(), job.getName());
final List<Builder> builders = builderFactory.buildersForTasks(pipeline, tasks, resolver);
return transactionTemplate.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
if (scheduleService.updateAssignedInfo(agentUuid, job)) {
return NO_WORK;
}
EnvironmentVariableContext contextFromEnvironment = environmentConfigService.environmentVariableContextFor(job.getIdentifier().getPipelineName());
final ArtifactStores requiredArtifactStores = goConfigService.artifactStores().getArtifactStores(getArtifactStoreIdsRequiredByArtifactPlans(job.getArtifactPlans()));
BuildAssignment buildAssignment = BuildAssignment.create(job, pipeline.getBuildCause(), builders, pipeline.defaultWorkingFolder(), contextFromEnvironment, requiredArtifactStores);
return new BuildWork(buildAssignment, systemEnvironment.consoleLogCharset());
}
});
}
});
} catch (PipelineNotFoundException e) {
removeJobIfNotPresentInCruiseConfig(goConfigService.getCurrentConfig(), job);
throw e;
}
}
use of org.springframework.transaction.support.TransactionCallback in project gocd by gocd.
the class TestFailureSetup method setupPipelineInstnace.
private SavedStage setupPipelineInstnace(final boolean failStage, final String overriddenLabel, final List<Modification> modifications, final TestResultsStubbing test, final Date latestTransitionDate) {
return (SavedStage) transactionTemplate.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
MaterialInstance materialInstance = materialRepository.findOrCreateFrom(hgMaterial);
for (Modification mod : modifications) {
mod.setMaterialInstance(materialInstance);
}
MaterialRevision rev = new MaterialRevision(hgMaterial, modifications);
materialRepository.saveMaterialRevision(rev);
Pipeline pipeline = PipelineMother.schedule(pipelineConfig, BuildCause.createManualForced(new MaterialRevisions(rev), new Username(new CaseInsensitiveString("loser"))));
if (overriddenLabel != null) {
pipeline.setLabel(overriddenLabel);
}
for (JobInstance instance : pipeline.getStages().get(0).getJobInstances()) {
for (JobStateTransition jobStateTransition : instance.getTransitions()) {
jobStateTransition.setStateChangeTime(latestTransitionDate);
}
}
dbHelper.save(pipeline);
Stage barStage = pipeline.getFirstStage();
if (failStage) {
dbHelper.failStage(barStage, latestTransitionDate);
}
test.stub(barStage);
pipelineTimeline.update();
return new SavedStage(pipeline);
}
});
}
use of org.springframework.transaction.support.TransactionCallback in project opennms by OpenNMS.
the class JtiGpbAdapter method handleMessage.
@Override
public Optional<CollectionSetWithAgent> handleMessage(TelemetryMessage message, TelemetryMessageLog messageLog) throws Exception {
final TelemetryTop.TelemetryStream jtiMsg = TelemetryTop.TelemetryStream.parseFrom(message.getByteArray(), s_registry);
CollectionAgent agent = null;
try {
// Attempt to resolve the systemId to an InetAddress
final InetAddress inetAddress = InetAddress.getByName(jtiMsg.getSystemId());
final Optional<Integer> nodeId = interfaceToNodeCache.getFirstNodeId(messageLog.getLocation(), inetAddress);
if (nodeId.isPresent()) {
// NOTE: This will throw a IllegalArgumentException if the
// nodeId/inetAddress pair does not exist in the database
agent = collectionAgentFactory.createCollectionAgent(Integer.toString(nodeId.get()), inetAddress);
}
} catch (UnknownHostException e) {
LOG.debug("Could not convert system id to address: {}", jtiMsg.getSystemId());
}
if (agent == null) {
// We were unable to build the agent by resolving the systemId,
// try finding
// a node with a matching label
agent = transactionTemplate.execute(new TransactionCallback<CollectionAgent>() {
@Override
public CollectionAgent doInTransaction(TransactionStatus status) {
final OnmsNode node = Iterables.getFirst(nodeDao.findByLabel(jtiMsg.getSystemId()), null);
if (node != null) {
final OnmsIpInterface primaryInterface = node.getPrimaryInterface();
return collectionAgentFactory.createCollectionAgent(primaryInterface);
}
return null;
}
});
}
if (agent == null) {
LOG.warn("Unable to find node and inteface for system id: {}", jtiMsg.getSystemId());
return Optional.empty();
}
final ScriptedCollectionSetBuilder builder = scriptedCollectionSetBuilders.get();
if (builder == null) {
throw new Exception(String.format("Error compiling script '%s'. See logs for details.", script));
}
final CollectionSet collectionSet = builder.build(agent, jtiMsg);
return Optional.of(new CollectionSetWithAgent(agent, collectionSet));
}
use of org.springframework.transaction.support.TransactionCallback in project nakadi by zalando.
the class EventTypeServiceTest method setUp.
@Before
public void setUp() {
eventTypeService = new EventTypeService(eventTypeRepository, timelineService, partitionResolver, enrichment, subscriptionDbRepository, schemaEvolutionService, partitionsCalculator, featureToggleService, authorizationValidator, timelineSync, transactionTemplate, nakadiSettings, nakadiKpiPublisher, KPI_ET_LOG_EVENT_TYPE);
when(transactionTemplate.execute(any())).thenAnswer(invocation -> {
final TransactionCallback callback = (TransactionCallback) invocation.getArguments()[0];
return callback.doInTransaction(null);
});
}
use of org.springframework.transaction.support.TransactionCallback in project motech by motech.
the class AutoGenerationContextIT method shouldGenerateValues.
@Test
public void shouldGenerateValues() throws Exception {
Class<?> definition = getEntityClass();
final Object instance = definition.newInstance();
String createUsername = StringUtils.defaultIfBlank(SecurityUtil.getUsername(), "");
DateTime create = DateTime.now();
double hour = 60 * 60 * 1000;
Object instanceFromDb = getService().doInTransaction(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
return getService().create(instance);
}
});
assertEquals(createUsername, PropertyUtil.safeGetProperty(instanceFromDb, CREATOR_FIELD_NAME));
assertEquals(createUsername, PropertyUtil.safeGetProperty(instanceFromDb, OWNER_FIELD_NAME));
assertEquals(createUsername, PropertyUtil.safeGetProperty(instanceFromDb, MODIFIED_BY_FIELD_NAME));
assertEquals(create.getMillis(), ((DateTime) PropertyUtil.safeGetProperty(instanceFromDb, CREATION_DATE_FIELD_NAME)).getMillis(), hour);
assertEquals(create.getMillis(), ((DateTime) PropertyUtil.safeGetProperty(instanceFromDb, MODIFICATION_DATE_FIELD_NAME)).getMillis(), hour);
Thread.sleep(TimeUnit.SECONDS.toMillis(15));
String updateUsername = StringUtils.defaultIfBlank(SecurityUtil.getUsername(), "");
DateTime update = DateTime.now();
PropertyUtil.safeSetProperty(instance, VALUE_FIELD, "nukem");
instanceFromDb = getService().doInTransaction(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
return getService().update(instance);
}
});
assertEquals(createUsername, PropertyUtil.safeGetProperty(instanceFromDb, CREATOR_FIELD_NAME));
assertEquals(createUsername, PropertyUtil.safeGetProperty(instanceFromDb, OWNER_FIELD_NAME));
assertEquals(updateUsername, PropertyUtil.safeGetProperty(instanceFromDb, MODIFIED_BY_FIELD_NAME));
assertEquals(create.getMillis(), ((DateTime) PropertyUtil.safeGetProperty(instanceFromDb, CREATION_DATE_FIELD_NAME)).getMillis(), hour);
assertEquals(update.getMillis(), ((DateTime) PropertyUtil.safeGetProperty(instanceFromDb, MODIFICATION_DATE_FIELD_NAME)).getMillis(), hour);
}
Aggregations