Search in sources :

Example 21 with TransactionCallback

use of org.springframework.transaction.support.TransactionCallback in project gocd by gocd.

the class JobInstanceSqlMapDaoTest method savedJobForAgent.

private JobInstance savedJobForAgent(final String jobName, final String uuid, final boolean runOnAllAgents, final boolean runMultipleInstance) {
    return (JobInstance) transactionTemplate.execute(new TransactionCallback() {

        public Object doInTransaction(TransactionStatus status) {
            JobInstance jobInstance = scheduled(jobName, new DateTime().plusMinutes(1).toDate());
            jobInstance.setRunOnAllAgents(runOnAllAgents);
            jobInstance.setRunMultipleInstance(runMultipleInstance);
            jobInstanceService.save(savedStage.getIdentifier(), stageId, jobInstance);
            jobInstance.changeState(JobState.Building);
            jobInstance.setAgentUuid(uuid);
            jobInstanceDao.updateStateAndResult(jobInstance);
            return jobInstance;
        }
    });
}
Also used : TransactionCallback(org.springframework.transaction.support.TransactionCallback) TransactionStatus(org.springframework.transaction.TransactionStatus) DateTime(org.joda.time.DateTime)

Example 22 with TransactionCallback

use of org.springframework.transaction.support.TransactionCallback in project opennms by OpenNMS.

the class NxosGpbAdapter method handleMessage.

@Override
public Optional<CollectionSetWithAgent> handleMessage(TelemetryMessage message, TelemetryMessageLog messageLog) throws Exception {
    final TelemetryBis.Telemetry msg = tryParsingTelemetryMessage(message.getByteArray());
    CollectionAgent agent = null;
    try {
        LOG.debug(" Telemetry message content : {} ", msg);
        final InetAddress inetAddress = InetAddress.getByName(msg.getNodeIdStr());
        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: {}", msg.getNodeIdStr());
    }
    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) {
                OnmsNode node = Iterables.getFirst(nodeDao.findByLabelForLocation(msg.getNodeIdStr(), messageLog.getLocation()), null);
                if (node == null) {
                    // If there is no matching label , Try matching with foreignId
                    node = Iterables.getFirst(nodeDao.findByForeignIdForLocation(msg.getNodeIdStr(), messageLog.getLocation()), 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 interface for system id: {}", msg.getNodeIdStr());
        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, msg);
    return Optional.of(new CollectionSetWithAgent(agent, collectionSet));
}
Also used : OnmsNode(org.opennms.netmgt.model.OnmsNode) UnknownHostException(java.net.UnknownHostException) TransactionStatus(org.springframework.transaction.TransactionStatus) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) 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) TelemetryBis(org.opennms.netmgt.telemetry.adapters.nxos.proto.TelemetryBis) CollectionSetWithAgent(org.opennms.netmgt.telemetry.adapters.collection.CollectionSetWithAgent) Telemetry(org.opennms.netmgt.telemetry.adapters.nxos.proto.TelemetryBis.Telemetry) CollectionAgent(org.opennms.netmgt.collection.api.CollectionAgent) InetAddress(java.net.InetAddress)

Example 23 with TransactionCallback

use of org.springframework.transaction.support.TransactionCallback in project opennms by OpenNMS.

the class BSFNotificationStrategy method declareBeans.

private static void declareBeans(BSFNotificationStrategy obj) throws BSFException {
    // Retrieve the parameters before accessing them
    obj.retrieveParams();
    Integer nodeId;
    try {
        nodeId = Integer.valueOf(obj.m_notifParams.get(NotificationManager.PARAM_NODE));
    } catch (NumberFormatException nfe) {
        nodeId = null;
    }
    OnmsNode node = null;
    OnmsAssetRecord assets = null;
    final List<String> categories = new ArrayList<>();
    String nodeLabel = null;
    String foreignSource = null;
    String foreignId = null;
    if (nodeId != null) {
        final BeanFactoryReference bf = BeanUtils.getBeanFactory("notifdContext");
        final NodeDao nodeDao = BeanUtils.getBean(bf, "nodeDao", NodeDao.class);
        final TransactionTemplate transTemplate = BeanUtils.getBean(bf, "transactionTemplate", TransactionTemplate.class);
        try {
            // Redeclare the node id as final
            final int theNodeId = nodeId;
            node = transTemplate.execute(new TransactionCallback<OnmsNode>() {

                @Override
                public OnmsNode doInTransaction(final TransactionStatus status) {
                    final OnmsNode node = nodeDao.get(theNodeId);
                    // Retrieve the categories in the context of the transaction
                    if (node != null) {
                        for (OnmsCategory cat : node.getCategories()) {
                            categories.add(cat.getName());
                        }
                    }
                    return node;
                }
            });
            if (node == null) {
                LOG.error("Could not find a node with id: {}", theNodeId);
            } else {
                nodeLabel = node.getLabel();
                assets = node.getAssetRecord();
                foreignSource = node.getForeignSource();
                foreignId = node.getForeignId();
            }
        } catch (final RuntimeException e) {
            LOG.error("Error while retrieving node with id {}", nodeId, e);
        }
    }
    s_bsfManager.declareBean("bsf_notif_strategy", obj, BSFNotificationStrategy.class);
    s_bsfManager.declareBean("logger", LOG, Logger.class);
    s_bsfManager.declareBean("notif_params", obj.m_notifParams, Map.class);
    s_bsfManager.declareBean("node_label", nodeLabel, String.class);
    s_bsfManager.declareBean("foreign_source", foreignSource, String.class);
    s_bsfManager.declareBean("foreign_id", foreignId, String.class);
    s_bsfManager.declareBean("node_assets", assets, OnmsAssetRecord.class);
    s_bsfManager.declareBean("node_categories", categories, List.class);
    s_bsfManager.declareBean("node", node, OnmsNode.class);
    for (Argument arg : obj.m_arguments) {
        if (NotificationManager.PARAM_TEXT_MSG.equals(arg.getSwitch()))
            s_bsfManager.declareBean("text_message", arg.getValue(), String.class);
        if (NotificationManager.PARAM_NUM_MSG.equals(arg.getSwitch()))
            s_bsfManager.declareBean("numeric_message", arg.getValue(), String.class);
        if (NotificationManager.PARAM_NODE.equals(arg.getSwitch()))
            s_bsfManager.declareBean("node_id", arg.getValue(), String.class);
        if (NotificationManager.PARAM_INTERFACE.equals(arg.getSwitch()))
            s_bsfManager.declareBean("ip_addr", arg.getValue(), String.class);
        if (NotificationManager.PARAM_SERVICE.equals(arg.getSwitch()))
            s_bsfManager.declareBean("svc_name", arg.getValue(), String.class);
        if (NotificationManager.PARAM_SUBJECT.equals(arg.getSwitch()))
            s_bsfManager.declareBean("subject", arg.getValue(), String.class);
        if (NotificationManager.PARAM_EMAIL.equals(arg.getSwitch()))
            s_bsfManager.declareBean("email", arg.getValue(), String.class);
        if (NotificationManager.PARAM_PAGER_EMAIL.equals(arg.getSwitch()))
            s_bsfManager.declareBean("pager_email", arg.getValue(), String.class);
        if (NotificationManager.PARAM_XMPP_ADDRESS.equals(arg.getSwitch()))
            s_bsfManager.declareBean("xmpp_address", arg.getValue(), String.class);
        if (NotificationManager.PARAM_TEXT_PAGER_PIN.equals(arg.getSwitch()))
            s_bsfManager.declareBean("text_pin", arg.getValue(), String.class);
        if (NotificationManager.PARAM_NUM_PAGER_PIN.equals(arg.getSwitch()))
            s_bsfManager.declareBean("numeric_pin", arg.getValue(), String.class);
        if (NotificationManager.PARAM_WORK_PHONE.equals(arg.getSwitch()))
            s_bsfManager.declareBean("work_phone", arg.getValue(), String.class);
        if (NotificationManager.PARAM_HOME_PHONE.equals(arg.getSwitch()))
            s_bsfManager.declareBean("home_phone", arg.getValue(), String.class);
        if (NotificationManager.PARAM_MOBILE_PHONE.equals(arg.getSwitch()))
            s_bsfManager.declareBean("mobile_phone", arg.getValue(), String.class);
        if (NotificationManager.PARAM_TUI_PIN.equals(arg.getSwitch()))
            s_bsfManager.declareBean("phone_pin", arg.getValue(), String.class);
        if (NotificationManager.PARAM_MICROBLOG_USERNAME.equals(arg.getSwitch()))
            s_bsfManager.declareBean("microblog_username", arg.getValue(), String.class);
    }
}
Also used : OnmsNode(org.opennms.netmgt.model.OnmsNode) Argument(org.opennms.netmgt.model.notifd.Argument) OnmsAssetRecord(org.opennms.netmgt.model.OnmsAssetRecord) ArrayList(java.util.ArrayList) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus) BeanFactoryReference(org.springframework.beans.factory.access.BeanFactoryReference) NodeDao(org.opennms.netmgt.dao.api.NodeDao) TransactionCallback(org.springframework.transaction.support.TransactionCallback) OnmsCategory(org.opennms.netmgt.model.OnmsCategory)

Example 24 with TransactionCallback

use of org.springframework.transaction.support.TransactionCallback in project nakadi by zalando.

the class EventTypeControllerTestCase method init.

@Before
public void init() throws Exception {
    final NakadiSettings nakadiSettings = new NakadiSettings(0, 0, 0, TOPIC_RETENTION_TIME_MS, 0, 60, NAKADI_POLL_TIMEOUT, NAKADI_SEND_TIMEOUT, 0, NAKADI_EVENT_MAX_BYTES, NAKADI_SUBSCRIPTION_MAX_PARTITIONS, "service", "nakadi", "I am warning you");
    final PartitionsCalculator partitionsCalculator = new KafkaConfig().createPartitionsCalculator("t2.large", TestUtils.OBJECT_MAPPER, nakadiSettings);
    when(timelineService.getTopicRepository((Timeline) any())).thenReturn(topicRepository);
    when(timelineService.getTopicRepository((EventTypeBase) any())).thenReturn(topicRepository);
    when(transactionTemplate.execute(any())).thenAnswer(invocation -> {
        final TransactionCallback callback = (TransactionCallback) invocation.getArguments()[0];
        return callback.doInTransaction(null);
    });
    final EventTypeService eventTypeService = new EventTypeService(eventTypeRepository, timelineService, partitionResolver, enrichment, subscriptionRepository, schemaEvolutionService, partitionsCalculator, featureToggleService, authorizationValidator, timelineSync, transactionTemplate, nakadiSettings, nakadiKpiPublisher, "et-log-event-type");
    final EventTypeOptionsValidator eventTypeOptionsValidator = new EventTypeOptionsValidator(TOPIC_RETENTION_MIN_MS, TOPIC_RETENTION_MAX_MS);
    final EventTypeController controller = new EventTypeController(eventTypeService, featureToggleService, eventTypeOptionsValidator, applicationService, adminService, nakadiSettings);
    doReturn(randomUUID).when(uuid).randomUUID();
    doReturn(true).when(applicationService).exists(any());
    doReturn(true).when(featureToggleService).isFeatureEnabled(CHECK_PARTITIONS_KEYS);
    mockMvc = standaloneSetup(controller).setMessageConverters(new StringHttpMessageConverter(), TestUtils.JACKSON_2_HTTP_MESSAGE_CONVERTER).setCustomArgumentResolvers(new ClientResolver(settings, featureToggleService)).setControllerAdvice(new ExceptionHandling()).build();
}
Also used : TransactionCallback(org.springframework.transaction.support.TransactionCallback) PartitionsCalculator(org.zalando.nakadi.repository.kafka.PartitionsCalculator) EventTypeService(org.zalando.nakadi.service.EventTypeService) EventTypeOptionsValidator(org.zalando.nakadi.validation.EventTypeOptionsValidator) ClientResolver(org.zalando.nakadi.security.ClientResolver) NakadiSettings(org.zalando.nakadi.config.NakadiSettings) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) KafkaConfig(org.zalando.nakadi.repository.kafka.KafkaConfig) Before(org.junit.Before)

Example 25 with TransactionCallback

use of org.springframework.transaction.support.TransactionCallback in project vladmihalcea.wordpress.com by vladmihalcea.

the class HibernateBagMultiLevelFetchTest method test.

@Test
public void test() {
    final Long forestId = transactionTemplate.execute(new TransactionCallback<Long>() {

        @Override
        public Long doInTransaction(TransactionStatus transactionStatus) {
            BagForest forest = new BagForest();
            BagTree tree1 = new BagTree();
            tree1.setIndex(0);
            BagBranch branch11 = new BagBranch();
            branch11.setIndex(0);
            BagLeaf leaf111 = new BagLeaf();
            leaf111.setIndex(0);
            BagLeaf leaf112 = new BagLeaf();
            leaf111.setIndex(1);
            BagLeaf leaf113 = new BagLeaf();
            leaf111.setIndex(2);
            BagLeaf leaf114 = new BagLeaf();
            leaf111.setIndex(3);
            branch11.addLeaf(leaf111);
            branch11.addLeaf(leaf112);
            branch11.addLeaf(leaf113);
            branch11.addLeaf(leaf114);
            BagBranch branch12 = new BagBranch();
            branch12.setIndex(1);
            BagLeaf leaf121 = new BagLeaf();
            leaf121.setIndex(1);
            BagLeaf leaf122 = new BagLeaf();
            leaf122.setIndex(2);
            BagLeaf leaf123 = new BagLeaf();
            leaf123.setIndex(3);
            BagLeaf leaf124 = new BagLeaf();
            leaf124.setIndex(4);
            branch12.addLeaf(leaf121);
            branch12.addLeaf(leaf122);
            branch12.addLeaf(leaf123);
            branch12.addLeaf(leaf124);
            tree1.addBranch(branch11);
            tree1.addBranch(branch12);
            BagTree tree2 = new BagTree();
            tree2.setIndex(1);
            BagBranch branch21 = new BagBranch();
            branch21.setIndex(0);
            BagLeaf leaf211 = new BagLeaf();
            leaf211.setIndex(0);
            BagLeaf leaf212 = new BagLeaf();
            leaf111.setIndex(1);
            BagLeaf leaf213 = new BagLeaf();
            leaf111.setIndex(2);
            BagLeaf leaf214 = new BagLeaf();
            leaf111.setIndex(3);
            branch21.addLeaf(leaf211);
            branch21.addLeaf(leaf212);
            branch21.addLeaf(leaf213);
            branch21.addLeaf(leaf214);
            BagBranch branch22 = new BagBranch();
            branch22.setIndex(2);
            BagLeaf leaf221 = new BagLeaf();
            leaf121.setIndex(0);
            BagLeaf leaf222 = new BagLeaf();
            leaf121.setIndex(1);
            BagLeaf leaf223 = new BagLeaf();
            leaf121.setIndex(2);
            branch22.addLeaf(leaf221);
            branch22.addLeaf(leaf222);
            branch22.addLeaf(leaf223);
            tree2.addBranch(branch21);
            tree2.addBranch(branch22);
            forest.addTree(tree1);
            forest.addTree(tree2);
            entityManager.persist(forest);
            entityManager.flush();
            return forest.getId();
        }
    });
    BagForest forest = transactionTemplate.execute(new TransactionCallback<BagForest>() {

        @Override
        public BagForest doInTransaction(TransactionStatus transactionStatus) {
            return entityManager.find(BagForest.class, forestId);
        }
    });
    try {
        navigateForest(forest);
        fail("Should have thrown LazyInitializationException!");
    } catch (LazyInitializationException expected) {
    }
    forest = transactionTemplate.execute(new TransactionCallback<BagForest>() {

        @Override
        public BagForest doInTransaction(TransactionStatus transactionStatus) {
            BagForest forest = entityManager.find(BagForest.class, forestId);
            navigateForest(forest);
            return forest;
        }
    });
    try {
        forest = transactionTemplate.execute(new TransactionCallback<BagForest>() {

            @Override
            public BagForest doInTransaction(TransactionStatus transactionStatus) {
                BagForest forest = entityManager.createQuery("select f " + "from BagForest f " + "join fetch f.trees t " + "join fetch t.branches b " + "join fetch b.leaves l ", BagForest.class).getSingleResult();
                return forest;
            }
        });
        fail("Should have thrown MultipleBagFetchException!");
    } catch (PersistenceException expected) {
        assertEquals(MultipleBagFetchException.class, expected.getCause().getClass());
    }
    List<BagLeaf> leaves = transactionTemplate.execute(new TransactionCallback<List<BagLeaf>>() {

        @Override
        public List<BagLeaf> doInTransaction(TransactionStatus transactionStatus) {
            List<BagLeaf> leaves = entityManager.createQuery("select l " + "from BagLeaf l " + "inner join fetch l.branch b " + "inner join fetch b.tree t " + "inner join fetch t.forest f " + "where f.id = :forestId", BagLeaf.class).setParameter("forestId", forestId).getResultList();
            return leaves;
        }
    });
    forest = reconstructForest(leaves, forestId);
    navigateForest(forest);
    final BagBranch firstBranch = forest.getTrees().get(0).getBranches().get(0);
    firstBranch.getLeaves().clear();
    final BagForest toMergeForest = forest;
    transactionTemplate.execute(new TransactionCallback<Void>() {

        @Override
        public Void doInTransaction(TransactionStatus status) {
            BagForest savedForest = entityManager.merge(toMergeForest);
            if (!firstBranch.getLeaves().equals(savedForest.getTrees().get(0).getBranches().get(0).getLeaves())) {
                LOG.error("Unsafe reusing the bag, changes haven't propagated!");
            }
            entityManager.flush();
            return null;
        }
    });
    transactionTemplate.execute(new TransactionCallback<Void>() {

        @Override
        public Void doInTransaction(TransactionStatus status) {
            BagForest savedForest = entityManager.find(BagForest.class, forestId);
            if (!firstBranch.getLeaves().equals(savedForest.getTrees().get(0).getBranches().get(0).getLeaves())) {
                LOG.error("Unsafe reusing the bag, changes haven't propagated!");
            }
            return null;
        }
    });
}
Also used : BagBranch(com.vladmihalcea.hibernate.model.baglist.BagBranch) TransactionStatus(org.springframework.transaction.TransactionStatus) BagTree(com.vladmihalcea.hibernate.model.baglist.BagTree) TransactionCallback(org.springframework.transaction.support.TransactionCallback) BagLeaf(com.vladmihalcea.hibernate.model.baglist.BagLeaf) LazyInitializationException(org.hibernate.LazyInitializationException) BagForest(com.vladmihalcea.hibernate.model.baglist.BagForest) PersistenceException(javax.persistence.PersistenceException) List(java.util.List) MultipleBagFetchException(org.hibernate.loader.MultipleBagFetchException) Test(org.junit.Test)

Aggregations

TransactionCallback (org.springframework.transaction.support.TransactionCallback)101 TransactionStatus (org.springframework.transaction.TransactionStatus)76 Test (org.junit.Test)28 ArrayList (java.util.ArrayList)16 Test (org.junit.jupiter.api.Test)14 TransactionTemplate (org.springframework.transaction.support.TransactionTemplate)11 DefaultTransactionDefinition (org.springframework.transaction.support.DefaultTransactionDefinition)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