Search in sources :

Example 66 with TransactionCallback

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

the class StatusMessageServiceTest method shouldSaveNotificationRules.

@Test
public void shouldSaveNotificationRules() {
    NotificationRule notificationRule1 = new NotificationRule("rec1", ActionType.EMAIL, Level.CRITICAL, "admin");
    NotificationRule notificationRule2 = new NotificationRule("rec2", ActionType.SMS, Level.CRITICAL, "admin");
    NotificationRule notificationRule3 = new NotificationRule("rec3", ActionType.SMS, Level.CRITICAL, "admin");
    notificationRule2.setId(1L);
    notificationRule3.setId(1L);
    when(notificationRulesDataService.findById(1L)).thenReturn(notificationRule3);
    statusMessageService.saveNotificationRules(asList(notificationRule1, notificationRule2));
    ArgumentCaptor<TransactionCallback> transactionCaptor = ArgumentCaptor.forClass(TransactionCallback.class);
    verify(notificationRulesDataService, times(2)).doInTransaction(transactionCaptor.capture());
    transactionCaptor.getAllValues().get(0).doInTransaction(null);
    transactionCaptor.getAllValues().get(1).doInTransaction(null);
    ArgumentCaptor<NotificationRule> captor = ArgumentCaptor.forClass(NotificationRule.class);
    verify(notificationRulesDataService).create(captor.capture());
    assertNull(captor.getValue().getId());
    assertEquals("rec1", captor.getValue().getRecipient());
    assertEquals(ActionType.EMAIL, captor.getValue().getActionType());
    verify(notificationRulesDataService).findById(1L);
    verify(notificationRulesDataService).update(captor.capture());
    assertEquals(1L, captor.getValue().getId().longValue());
    assertEquals("rec2", captor.getValue().getRecipient());
    assertEquals(ActionType.SMS, captor.getValue().getActionType());
}
Also used : TransactionCallback(org.springframework.transaction.support.TransactionCallback) NotificationRule(org.motechproject.admin.domain.NotificationRule) Test(org.junit.Test)

Example 67 with TransactionCallback

use of org.springframework.transaction.support.TransactionCallback in project camunda-bpm-platform by camunda.

the class SpringTransactionInterceptor method execute.

@SuppressWarnings("unchecked")
public <T> T execute(final Command<T> command) {
    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    transactionTemplate.setPropagationBehavior(transactionPropagation);
    T result = (T) transactionTemplate.execute(new TransactionCallback() {

        public Object doInTransaction(TransactionStatus status) {
            return next.execute(command);
        }
    });
    return result;
}
Also used : TransactionCallback(org.springframework.transaction.support.TransactionCallback) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus)

Example 68 with TransactionCallback

use of org.springframework.transaction.support.TransactionCallback in project ma-core-public by infiniteautomation.

the class DataPointDao method copy.

@Override
public int copy(final int existingId, final String newXid, final String newName) {
    TransactionCallback<Integer> callback = new TransactionCallback<Integer>() {

        @Override
        public Integer doInTransaction(TransactionStatus status) {
            DataPointVO dataPoint = get(existingId);
            // Copy the vo
            DataPointVO copy = dataPoint.copy();
            copy.setId(Common.NEW_ID);
            copy.setXid(generateUniqueXid());
            copy.setName(dataPoint.getName());
            copy.setDeviceName(dataPoint.getDeviceName());
            copy.setDataSourceId(dataPoint.getDataSourceId());
            copy.setEnabled(dataPoint.isEnabled());
            copy.getComments().clear();
            // Copy the event detectors
            List<AbstractEventDetectorVO<?>> existing = EventDetectorDao.instance.getWithSourceId(EventType.EventTypeNames.DATA_POINT, dataPoint.getId());
            List<AbstractPointEventDetectorVO<?>> detectors = new ArrayList<AbstractPointEventDetectorVO<?>>(existing.size());
            for (AbstractEventDetectorVO<?> ed : existing) {
                AbstractPointEventDetectorVO<?> ped = (AbstractPointEventDetectorVO<?>) ed;
                ped.setId(Common.NEW_ID);
                ped.njbSetDataPoint(copy);
            }
            copy.setEventDetectors(detectors);
            Common.runtimeManager.saveDataPoint(copy);
            // Copy permissions.
            return copy.getId();
        }
    };
    return getTransactionTemplate().execute(callback);
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DataPointVO(com.serotonin.m2m2.vo.DataPointVO) TransactionCallback(org.springframework.transaction.support.TransactionCallback) AbstractPointEventDetectorVO(com.serotonin.m2m2.vo.event.detector.AbstractPointEventDetectorVO) AbstractEventDetectorVO(com.serotonin.m2m2.vo.event.detector.AbstractEventDetectorVO) ArrayList(java.util.ArrayList) TransactionStatus(org.springframework.transaction.TransactionStatus)

Example 69 with TransactionCallback

use of org.springframework.transaction.support.TransactionCallback in project otter by alibaba.

the class AbstractOperationInterceptor method init.

private void init(final JdbcTemplate jdbcTemplate, final String markTableName, final String markTableColumn) {
    int count = jdbcTemplate.queryForInt(MessageFormat.format(checkDataSql, markTableName, GLOBAL_THREAD_COUNT - 1));
    if (count != GLOBAL_THREAD_COUNT) {
        if (logger.isInfoEnabled()) {
            logger.info("Interceptor: init " + markTableName + "'s data.");
        }
        TransactionTemplate transactionTemplate = new TransactionTemplate();
        transactionTemplate.setTransactionManager(new DataSourceTransactionManager(jdbcTemplate.getDataSource()));
        // 注意这里强制使用非事务,保证多线程的可见性
        transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
        transactionTemplate.execute(new TransactionCallback() {

            public Object doInTransaction(TransactionStatus status) {
                jdbcTemplate.execute(MessageFormat.format(deleteDataSql, markTableName));
                String batchSql = MessageFormat.format(updateSql, new Object[] { markTableName, markTableColumn });
                jdbcTemplate.batchUpdate(batchSql, new BatchPreparedStatementSetter() {

                    public void setValues(PreparedStatement ps, int idx) throws SQLException {
                        ps.setInt(1, idx);
                        ps.setInt(2, 0);
                    // ps.setNull(3, Types.VARCHAR);
                    }

                    public int getBatchSize() {
                        return GLOBAL_THREAD_COUNT;
                    }
                });
                return null;
            }
        });
        if (logger.isInfoEnabled()) {
            logger.info("Interceptor: Init EROSA Client Data: " + updateSql);
        }
    }
}
Also used : TransactionCallback(org.springframework.transaction.support.TransactionCallback) BatchPreparedStatementSetter(org.springframework.jdbc.core.BatchPreparedStatementSetter) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus) PreparedStatement(java.sql.PreparedStatement) DataSourceTransactionManager(org.springframework.jdbc.datasource.DataSourceTransactionManager)

Example 70 with TransactionCallback

use of org.springframework.transaction.support.TransactionCallback in project otter by alibaba.

the class DbPerfIntergration method test_stack.

@Test
public void test_stack() {
    DbMediaSource dbMediaSource = new DbMediaSource();
    dbMediaSource.setId(1L);
    dbMediaSource.setDriver("com.mysql.jdbc.Driver");
    dbMediaSource.setUsername("otter");
    dbMediaSource.setPassword("otter");
    dbMediaSource.setUrl("jdbc:mysql://127.0.0.1:3306/retl");
    dbMediaSource.setEncode("UTF-8");
    dbMediaSource.setType(DataMediaType.MYSQL);
    DbDataMedia dataMedia = new DbDataMedia();
    dataMedia.setSource(dbMediaSource);
    dataMedia.setId(1L);
    dataMedia.setName("ljhtable1");
    dataMedia.setNamespace("otter");
    final DbDialect dbDialect = dbDialectFactory.getDbDialect(2L, dataMedia.getSource());
    want.object(dbDialect).clazIs(MysqlDialect.class);
    final TransactionTemplate transactionTemplate = dbDialect.getTransactionTemplate();
    // 插入数据准备
    int minute = 5;
    int nextId = 1;
    final int thread = 10;
    final int batch = 50;
    final String sql = "insert into otter.ljhtable1 values(? , ? , ? , ?)";
    final CountDownLatch latch = new CountDownLatch(thread);
    ExecutorService executor = new ThreadPoolExecutor(thread, thread, 60, TimeUnit.SECONDS, new ArrayBlockingQueue(thread * 2), new NamedThreadFactory("load"), new ThreadPoolExecutor.CallerRunsPolicy());
    for (int sec = 0; sec < minute * 60; sec++) {
        // 执行秒循环
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < thread; i++) {
            final int start = nextId + i * batch;
            executor.submit(new Runnable() {

                public void run() {
                    try {
                        transactionTemplate.execute(new TransactionCallback() {

                            public Object doInTransaction(TransactionStatus status) {
                                JdbcTemplate jdbcTemplate = dbDialect.getJdbcTemplate();
                                return jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {

                                    public void setValues(PreparedStatement ps, int idx) throws SQLException {
                                        int id = start + idx;
                                        StatementCreatorUtils.setParameterValue(ps, 1, Types.INTEGER, null, id);
                                        StatementCreatorUtils.setParameterValue(ps, 2, Types.VARCHAR, null, RandomStringUtils.randomAlphabetic(1000));
                                        // RandomStringUtils.randomAlphabetic()
                                        long time = new Date().getTime();
                                        StatementCreatorUtils.setParameterValue(ps, 3, Types.TIMESTAMP, new Timestamp(time));
                                        StatementCreatorUtils.setParameterValue(ps, 4, Types.TIMESTAMP, new Timestamp(time));
                                    }

                                    public int getBatchSize() {
                                        return batch;
                                    }
                                });
                            }
                        });
                    } finally {
                        latch.countDown();
                    }
                }
            });
        }
        long endTime = System.currentTimeMillis();
        try {
            latch.await(1000 * 60L - (endTime - startTime), TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (latch.getCount() != 0) {
            System.out.println("perf is not enough!");
            System.exit(-1);
        }
        endTime = System.currentTimeMillis();
        System.out.println("Time cost : " + (System.currentTimeMillis() - startTime));
        try {
            TimeUnit.MILLISECONDS.sleep(1000L - (endTime - startTime));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        nextId = nextId + thread * batch;
    }
    executor.shutdown();
}
Also used : SQLException(java.sql.SQLException) NamedThreadFactory(com.alibaba.otter.shared.common.utils.thread.NamedThreadFactory) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus) PreparedStatement(java.sql.PreparedStatement) CountDownLatch(java.util.concurrent.CountDownLatch) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) Timestamp(java.sql.Timestamp) Date(java.util.Date) TransactionCallback(org.springframework.transaction.support.TransactionCallback) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) DbDialect(com.alibaba.otter.node.etl.common.db.dialect.DbDialect) BatchPreparedStatementSetter(org.springframework.jdbc.core.BatchPreparedStatementSetter) ExecutorService(java.util.concurrent.ExecutorService) DbMediaSource(com.alibaba.otter.shared.common.model.config.data.db.DbMediaSource) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) DbDataMedia(com.alibaba.otter.shared.common.model.config.data.db.DbDataMedia) Test(org.testng.annotations.Test) BaseDbTest(com.alibaba.otter.node.etl.BaseDbTest)

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