Search in sources :

Example 61 with TransactionCallback

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;
    }
}
Also used : StaleMaterialsOnBuildCause(com.thoughtworks.go.server.materials.StaleMaterialsOnBuildCause) Builder(com.thoughtworks.go.domain.builder.Builder) TransactionStatus(org.springframework.transaction.TransactionStatus) TransactionCallback(org.springframework.transaction.support.TransactionCallback) EnvironmentVariableContext(com.thoughtworks.go.util.command.EnvironmentVariableContext)

Example 62 with TransactionCallback

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);
        }
    });
}
Also used : Modification(com.thoughtworks.go.domain.materials.Modification) JobInstance(com.thoughtworks.go.domain.JobInstance) MaterialRevisions(com.thoughtworks.go.domain.MaterialRevisions) TransactionStatus(org.springframework.transaction.TransactionStatus) CaseInsensitiveString(com.thoughtworks.go.config.CaseInsensitiveString) Pipeline(com.thoughtworks.go.domain.Pipeline) JobStateTransition(com.thoughtworks.go.domain.JobStateTransition) TransactionCallback(org.springframework.transaction.support.TransactionCallback) Username(com.thoughtworks.go.server.domain.Username) Stage(com.thoughtworks.go.domain.Stage) MaterialInstance(com.thoughtworks.go.domain.MaterialInstance) MaterialRevision(com.thoughtworks.go.domain.MaterialRevision)

Example 63 with TransactionCallback

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));
}
Also used : OnmsNode(org.opennms.netmgt.model.OnmsNode) UnknownHostException(java.net.UnknownHostException) TransactionStatus(org.springframework.transaction.TransactionStatus) UnknownHostException(java.net.UnknownHostException) CollectionSet(org.opennms.netmgt.collection.api.CollectionSet) TransactionCallback(org.springframework.transaction.support.TransactionCallback) ScriptedCollectionSetBuilder(org.opennms.netmgt.telemetry.adapters.collection.ScriptedCollectionSetBuilder) OnmsIpInterface(org.opennms.netmgt.model.OnmsIpInterface) CollectionSetWithAgent(org.opennms.netmgt.telemetry.adapters.collection.CollectionSetWithAgent) TelemetryTop(org.opennms.netmgt.telemetry.adapters.jti.proto.TelemetryTop) CollectionAgent(org.opennms.netmgt.collection.api.CollectionAgent) InetAddress(java.net.InetAddress)

Example 64 with TransactionCallback

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);
    });
}
Also used : TransactionCallback(org.springframework.transaction.support.TransactionCallback) Before(org.junit.Before)

Example 65 with TransactionCallback

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);
}
Also used : TransactionCallback(org.springframework.transaction.support.TransactionCallback) TransactionStatus(org.springframework.transaction.TransactionStatus) DateTime(org.joda.time.DateTime) Test(org.junit.Test)

Aggregations

TransactionCallback (org.springframework.transaction.support.TransactionCallback)100 TransactionStatus (org.springframework.transaction.TransactionStatus)75 Test (org.junit.Test)28 ArrayList (java.util.ArrayList)16 Test (org.junit.jupiter.api.Test)14 DefaultTransactionDefinition (org.springframework.transaction.support.DefaultTransactionDefinition)10 TransactionTemplate (org.springframework.transaction.support.TransactionTemplate)10 CaseInsensitiveString (com.thoughtworks.go.config.CaseInsensitiveString)9 PreparedStatement (java.sql.PreparedStatement)8 List (java.util.List)8 GitMaterial (com.thoughtworks.go.config.materials.git.GitMaterial)7 MaterialInstance (com.thoughtworks.go.domain.MaterialInstance)7 Modification (com.thoughtworks.go.domain.materials.Modification)7 PackageMaterialInstance (com.thoughtworks.go.domain.materials.packagematerial.PackageMaterialInstance)7 PluggableSCMMaterialInstance (com.thoughtworks.go.domain.materials.scm.PluggableSCMMaterialInstance)7 Query (org.hibernate.Query)7 BaseDbTest (com.alibaba.otter.node.etl.BaseDbTest)6 DbDialect (com.alibaba.otter.node.etl.common.db.dialect.DbDialect)6 Modifications (com.thoughtworks.go.domain.materials.Modifications)6 HgMaterialInstance (com.thoughtworks.go.domain.materials.mercurial.HgMaterialInstance)6