Java 类org.springframework.transaction.support.TransactionTemplate 实例源码

项目:otter-G    文件:AbstractDbDialect.java   
public AbstractDbDialect(final JdbcTemplate jdbcTemplate, LobHandler lobHandler){
    this.jdbcTemplate = jdbcTemplate;
    this.lobHandler = lobHandler;
    // 初始化transction
    this.transactionTemplate = new TransactionTemplate();
    transactionTemplate.setTransactionManager(new DataSourceTransactionManager(jdbcTemplate.getDataSource()));
    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

    // 初始化一些数据
    jdbcTemplate.execute(new ConnectionCallback() {

        public Object doInConnection(Connection c) throws SQLException, DataAccessException {
            DatabaseMetaData meta = c.getMetaData();
            databaseName = meta.getDatabaseProductName();
            databaseMajorVersion = meta.getDatabaseMajorVersion();
            databaseMinorVersion = meta.getDatabaseMinorVersion();

            return null;
        }
    });

    initTables(jdbcTemplate);
}
项目:EasyTransaction    文件:ParentTrxStatusUpdateFilter.java   
@Override
public EasyTransResult invoke(EasyTransFilterChain filterChain, Map<String, Object> header,
        EasyTransRequest<?, ?> request) {

    Integer pTrxStatus = MetaDataFilter.getMetaData(EasytransConstant.CallHeadKeys.PARENT_TRANSACTION_STATUS);
    if(!pTrxStatus.equals(com.yiqiniu.easytrans.datasource.TransStatusLogger.TransactionStatus.UNKNOWN)){
        // start transaction to update 
        PlatformTransactionManager transactionManager = getTransactionManager(filterChain, request);
        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager,
                new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED));
        TransactionId pTrxId = MetaDataFilter.getMetaData(EasytransConstant.CallHeadKeys.PARENT_TRX_ID_KEY);
        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus status) {
                TransactionId trxId = pTrxId;
                transStatusLogger.updateExecuteFlagForSlaveTrx(trxId, request, pTrxStatus);
                return null;
            }
        });
        boolean commited = pTrxStatus.equals(com.yiqiniu.easytrans.datasource.TransStatusLogger.TransactionStatus.COMMITTED);
        //may be concurrent,but it's ok
        easyTransSynchronizer.cascadeExecuteCachedTransaction(pTrxId, commited);
    }

    return filterChain.invokeFilterChain(header, request);
}
项目:springboot-shiro-cas-mybatis    文件:JpaTicketRegistryTests.java   
Ticket getTicketInTransaction(final String ticketId) {
    return new TransactionTemplate(txManager).execute(new TransactionCallback<Ticket>() {
        @Override
        public Ticket doInTransaction(final TransactionStatus status) {
            return jpaTicketRegistry.getTicket(ticketId);
        }
    });
}
项目:springboot-shiro-cas-mybatis    文件:JpaLockingStrategyTests.java   
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    return new TransactionTemplate(txManager).execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(final TransactionStatus status) {
            try {
                final Object result = method.invoke(jpaLock, args);
                jpaLock.entityManager.flush();
                logger.debug("Performed {} on {}", method.getName(), jpaLock);
                return result;
                // Force result of transaction to database
            } catch (final Exception e) {
                throw new RuntimeException("Transactional method invocation failed.", e);
            }
        }
    });
}
项目:springboot-shiro-cas-mybatis    文件:JpaLockingStrategyTests.java   
/**
* {@inheritDoc}
*/
   @Override
   public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
       return new TransactionTemplate(txManager).execute(new TransactionCallback<Object>() {
           public Object doInTransaction(final TransactionStatus status) {
               try {
                   final Object result = method.invoke(jpaLock, args);
                   jpaLock.entityManager.flush();
                   logger.debug("Performed {} on {}", method.getName(), jpaLock);
                   return result;
                   // Force result of transaction to database
               } catch (final Exception e) {
                   throw new RuntimeException("Transactional method invocation failed.", e);
               }
           }
       });
   }
项目:cas4.0.x-server-wechat    文件:JpaLockingStrategyTests.java   
/** {@inheritDoc} */
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    return new TransactionTemplate(txManager).execute(new TransactionCallback<Object>() {
        public Object doInTransaction(final TransactionStatus status) {
            try {
                final Object result = method.invoke(jpaLock, args);
                jpaLock.entityManager.flush();
                logger.debug("Performed {} on {}", method.getName(), jpaLock);
                return result;
                // Force result of transaction to database
            } catch (final Exception e) {
                throw new RuntimeException("Transactional method invocation failed.", e);
            }
        }
    });
}
项目:org.ops4j.pax.transx    文件:ActiveMQTest.java   
@Test
public void testSpringLocalTx() throws Exception {
    ConnectionFactory cf = createCF(BROKER_URL);
    JmsTemplate jms = new JmsTemplate(cf);
    jms.setDefaultDestinationName(QUEUE);
    jms.setReceiveTimeout(1000);
    PlatformTransactionManager tm = new JmsTransactionManager(cf);
    TransactionTemplate localTx = new TransactionTemplate(tm);

    localTx.execute(ts -> {
        jms.convertAndSend("Hello");
        return null;
    });
    Object msg = localTx.execute(ts -> jms.receiveAndConvert());
    assertEquals("Hello", msg);

    localTx.execute(ts -> {
        jms.convertAndSend("Hello");
        ts.setRollbackOnly();
        return null;
    });
    msg = localTx.execute(ts -> jms.receiveAndConvert());
    assertNull(msg);
}
项目:org.ops4j.pax.transx    文件:HsqlTest.java   
@Test
public void testSpringXaTx() throws Exception {
    DataSource ds = wrap(createHsqlDataSource());
    JdbcTemplate jdbc = new JdbcTemplate(ds);
    TransactionTemplate tx = new TransactionTemplate(ptm);

    jdbc.execute(DROP_USER);
    jdbc.execute(CREATE_TABLE_USER);

    tx.execute(ts -> jdbc.update(INSERT_INTO_USER, 1, "user1"));
    User user = tx.execute(ts -> jdbc.queryForObject(SELECT_FROM_USER_BY_ID, new BeanPropertyRowMapper<>(User.class), 1));
    assertEquals(new User(1, "user1"), user);
    tx.execute(ts -> jdbc.update(DELETE_FROM_USER_BY_ID, 1));

    tx.execute(ts -> {
        int nb = jdbc.update(INSERT_INTO_USER, 1, "user1");
        ts.setRollbackOnly();
        return nb;
    });
    try {
        user = tx.execute(ts -> jdbc.queryForObject(SELECT_FROM_USER_BY_ID, new BeanPropertyRowMapper<>(User.class), 1));
        fail("Expected a EmptyResultDataAccessException");
    } catch (EmptyResultDataAccessException e) {
        // expected
    }
}
项目:org.ops4j.pax.transx    文件:HsqlTest.java   
@Test
public void testSpringLocalTx() throws Exception {
    DataSource ds = wrap(createHsqlDataSource());
    JdbcTemplate jdbc = new JdbcTemplate(ds);
    TransactionTemplate tx = new TransactionTemplate(new DataSourceTransactionManager(ds));

    jdbc.execute(DROP_USER);
    jdbc.execute(CREATE_TABLE_USER);

    tx.execute(ts -> jdbc.update(INSERT_INTO_USER, 1, "user1"));
    User user = tx.execute(ts -> jdbc.queryForObject(SELECT_FROM_USER_BY_ID, new BeanPropertyRowMapper<>(User.class), 1));
    assertEquals(new User(1, "user1"), user);
    tx.execute(ts -> jdbc.update(DELETE_FROM_USER_BY_ID, 1));

    tx.execute(ts -> {
        int nb = jdbc.update(INSERT_INTO_USER, 1, "user1");
        ts.setRollbackOnly();
        return nb;
    });
    try {
        user = tx.execute(ts -> jdbc.queryForObject(SELECT_FROM_USER_BY_ID, new BeanPropertyRowMapper<>(User.class), 1));
        fail("Expected a EmptyResultDataAccessException");
    } catch (EmptyResultDataAccessException e) {
        // expected
    }
}
项目:org.ops4j.pax.transx    文件:H2Test.java   
@Test
public void testSpringXaTx() throws Exception {
    DataSource ds = wrap(createH2DataSource());
    JdbcTemplate jdbc = new JdbcTemplate(ds);
    TransactionTemplate tx = new TransactionTemplate(ptm);

    jdbc.execute(DROP_USER);
    jdbc.execute(CREATE_TABLE_USER);

    tx.execute(ts -> jdbc.update(INSERT_INTO_USER, 1, "user1"));
    User user = tx.execute(ts -> jdbc.queryForObject(SELECT_FROM_USER_BY_ID, new BeanPropertyRowMapper<>(User.class), 1));
    assertEquals(new User(1, "user1"), user);
    tx.execute(ts -> jdbc.update(DELETE_FROM_USER_BY_ID, 1));

    tx.execute(ts -> {
        int nb = jdbc.update(INSERT_INTO_USER, 1, "user1");
        ts.setRollbackOnly();
        return nb;
    });
    try {
        user = tx.execute(ts -> jdbc.queryForObject(SELECT_FROM_USER_BY_ID, new BeanPropertyRowMapper<>(User.class), 1));
        fail("Expected a EmptyResultDataAccessException");
    } catch (EmptyResultDataAccessException e) {
        // expected
    }
}
项目:org.ops4j.pax.transx    文件:H2Test.java   
@Test
public void testSpringLocalTx() throws Exception {
    DataSource ds = wrap(createH2DataSource());
    JdbcTemplate jdbc = new JdbcTemplate(ds);
    TransactionTemplate tx = new TransactionTemplate(new DataSourceTransactionManager(ds));

    jdbc.execute(DROP_USER);
    jdbc.execute(CREATE_TABLE_USER);

    tx.execute(ts -> jdbc.update(INSERT_INTO_USER, 1, "user1"));
    User user = tx.execute(ts -> jdbc.queryForObject(SELECT_FROM_USER_BY_ID, new BeanPropertyRowMapper<>(User.class), 1));
    assertEquals(new User(1, "user1"), user);
    tx.execute(ts -> jdbc.update(DELETE_FROM_USER_BY_ID, 1));

    tx.execute(ts -> {
        int nb = jdbc.update(INSERT_INTO_USER, 1, "user1");
        ts.setRollbackOnly();
        return nb;
    });
    try {
        user = tx.execute(ts -> jdbc.queryForObject(SELECT_FROM_USER_BY_ID, new BeanPropertyRowMapper<>(User.class), 1));
        fail("Expected a EmptyResultDataAccessException");
    } catch (EmptyResultDataAccessException e) {
        // expected
    }
}
项目:cas-server-4.2.1    文件:JpaLockingStrategyTests.java   
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    return new TransactionTemplate(txManager).execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(final TransactionStatus status) {
            try {
                final Object result = method.invoke(jpaLock, args);
                jpaLock.entityManager.flush();
                logger.debug("Performed {} on {}", method.getName(), jpaLock);
                return result;
                // Force result of transaction to database
            } catch (final Exception e) {
                throw new RuntimeException("Transactional method invocation failed.", e);
            }
        }
    });
}
项目:bdf2    文件:DbService.java   
/**
 * 批处理更新操作
 * 
 * @param dbInfoId
 * @param sqls
 * @return 返回更新的列的数量
 * @throws Exception
 */
public int[] updateSql(String dbInfoId, String[] sqls) throws Exception {
    final String[] fsqls = this.getFormatArrays(sqls);
    if (log.isDebugEnabled()) {
        for (String s : fsqls) {
            log.debug(s);
        }
    }
    DataSource ds = getDataSourceByDbInfoId(dbInfoId);
    final TransactionTemplate transactionTemplate = SpringJdbcUtils.getTransactionTemplate(ds);
    return transactionTemplate.execute(new TransactionCallback<int[]>() {
        public int[] doInTransaction(TransactionStatus status) {
            JdbcTemplate jdbcTemplate = SpringJdbcUtils.getJdbcTemplate(transactionTemplate);
            int[] i = jdbcTemplate.batchUpdate(fsqls);
            return i;
        }
    });
}
项目:fahrschein    文件:TransactionHandlerIT.java   
@Test
public void shouldRollbackOnCursorManagerException() throws IOException {

    new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus transactionStatus) {
            assertFalse("Transaction should be active", transactionStatus.isRollbackOnly());

            try {
                batchHandler.processBatch(new IORunnable() {
                    @Override
                    public void run() throws IOException {
                        throw new IOException("commit failed");
                    }
                });
            } catch (IOException e) {
                LOG.info("Ignoring [{}] with message [{}]", e.getClass().getName(), e.getMessage());
            }

            assertTrue("Transaction should be marked as rollback only", transactionStatus.isRollbackOnly());

            return null;
        }
    });

}
项目:spring4-understanding    文件:PersistenceContextTransactionTests.java   
@Before
public void setUp() throws Exception {
    factory = mock(EntityManagerFactory.class);
    manager = mock(EntityManager.class);
    tx = mock(EntityTransaction.class);

    JpaTransactionManager tm = new JpaTransactionManager(factory);
    tt = new TransactionTemplate(tm);

    given(factory.createEntityManager()).willReturn(manager);
    given(manager.getTransaction()).willReturn(tx);
    given(manager.isOpen()).willReturn(true);

    bean = new EntityManagerHoldingBean();
    @SuppressWarnings("serial")
    PersistenceAnnotationBeanPostProcessor pabpp = new PersistenceAnnotationBeanPostProcessor() {
        @Override
        protected EntityManagerFactory findEntityManagerFactory(String unitName, String requestingBeanName) {
            return factory;
        }
    };
    pabpp.postProcessPropertyValues(null, null, bean, "bean");

    assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
项目:spring4-understanding    文件:JdoTransactionManagerTests.java   
@Test
public void testTransactionCommitWithPropagationSupports() {
    given(pmf.getPersistenceManager()).willReturn(pm);

    PlatformTransactionManager tm = new JdoTransactionManager(pmf);
    TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
    final List l = new ArrayList();
    l.add("test");
    assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf));

    Object result = tt.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf));
            assertTrue("Is not new transaction", !status.isNewTransaction());
            PersistenceManagerFactoryUtils.getPersistenceManager(pmf, true);
            return l;
        }
    });
    assertTrue("Correct result list", result == l);

    assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf));

    verify(pm, times(2)).close();
}
项目:spring4-understanding    文件:JdoTransactionManagerTests.java   
@Test
public void testIsolationLevel() {
    given(pmf.getPersistenceManager()).willReturn(pm);
    given(pm.currentTransaction()).willReturn(tx);

    PlatformTransactionManager tm = new JdoTransactionManager(pmf);
    TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
        }
    });
    verify(tx).setIsolationLevel(Constants.TX_SERIALIZABLE);
    verify(pm).close();
}
项目:flowable-engine    文件:SpringTransactionInterceptor.java   
@Override
public <T> T execute(final CommandConfig config, final Command<T> command) {
    LOGGER.debug("Running command with propagation {}", config.getTransactionPropagation());

    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    transactionTemplate.setPropagationBehavior(getPropagation(config));

    T result = transactionTemplate.execute(new TransactionCallback<T>() {
        @Override
        public T doInTransaction(TransactionStatus status) {
            return next.execute(config, command);
        }
    });

    return result;
}
项目:spring4-understanding    文件:TransactionSupportTests.java   
@Test
public void transactionTemplateWithException() {
    TestTransactionManager tm = new TestTransactionManager(false, true);
    TransactionTemplate template = new TransactionTemplate(tm);
    final RuntimeException ex = new RuntimeException("Some application exception");
    try {
        template.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                throw ex;
            }
        });
        fail("Should have propagated RuntimeException");
    }
    catch (RuntimeException caught) {
        // expected
        assertTrue("Correct exception", caught == ex);
        assertTrue("triggered begin", tm.begin);
        assertTrue("no commit", !tm.commit);
        assertTrue("triggered rollback", tm.rollback);
        assertTrue("no rollbackOnly", !tm.rollbackOnly);
    }
}
项目:flowable-engine    文件:SpringTransactionInterceptor.java   
@Override
public <T> T execute(final CommandConfig config, final Command<T> command) {
    LOGGER.debug("Running command with propagation {}", config.getTransactionPropagation());

    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    transactionTemplate.setPropagationBehavior(getPropagation(config));

    T result = transactionTemplate.execute(new TransactionCallback<T>() {
        @Override
        public T doInTransaction(TransactionStatus status) {
            return next.execute(config, command);
        }
    });

    return result;
}
项目:spring4-understanding    文件:JtaTransactionManagerTests.java   
@Test
public void jtaTransactionManagerWithRollbackAndSynchronizationNever() throws Exception {
    UserTransaction ut = mock(UserTransaction.class);
    given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE);

    JtaTransactionManager ptm = newJtaTransactionManager(ut);
    TransactionTemplate tt = new TransactionTemplate(ptm);
    ptm.setTransactionSynchronizationName("SYNCHRONIZATION_NEVER");
    tt.setTimeout(10);
    ptm.afterPropertiesSet();

    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
            status.setRollbackOnly();
        }
    });
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

    verify(ut).setTransactionTimeout(10);
    verify(ut).begin();
    verify(ut, atLeastOnce()).getStatus();
    verify(ut).rollback();
}
项目:spring4-understanding    文件:JtaTransactionManagerTests.java   
@Test
public void jtaTransactionManagerWithExistingTransactionAndRollbackOnly() throws Exception {
    UserTransaction ut = mock(UserTransaction.class);
    given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

    final TransactionSynchronization synch = mock(TransactionSynchronization.class);

    JtaTransactionManager ptm = newJtaTransactionManager(ut);
    TransactionTemplate tt = new TransactionTemplate(ptm);
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
            TransactionSynchronizationManager.registerSynchronization(synch);
            status.setRollbackOnly();
        }
    });
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

    verify(ut).setRollbackOnly();
    verify(synch).beforeCompletion();
    verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
}
项目:spring4-understanding    文件:JtaTransactionManagerTests.java   
@Test
public void jtaTransactionManagerWithExistingTransactionAndRollbackOnlyAndNoGlobalRollback() throws Exception {
    UserTransaction ut = mock(UserTransaction.class);
    given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

    final TransactionSynchronization synch = mock(TransactionSynchronization.class);

    JtaTransactionManager ptm = newJtaTransactionManager(ut);
    ptm.setGlobalRollbackOnParticipationFailure(false);
    TransactionTemplate tt = new TransactionTemplate(ptm);
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
            TransactionSynchronizationManager.registerSynchronization(synch);
            status.setRollbackOnly();
        }
    });
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

    verify(ut).setRollbackOnly();
    verify(synch).beforeCompletion();
    verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
}
项目:spring4-understanding    文件:JtaTransactionManagerTests.java   
@Test
public void jtaTransactionManagerWithPropagationSupports() throws Exception {
    UserTransaction ut = mock(UserTransaction.class);
    given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION);

    final TransactionSynchronization synch = mock(TransactionSynchronization.class);

    JtaTransactionManager ptm = newJtaTransactionManager(ut);
    TransactionTemplate tt = new TransactionTemplate(ptm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
            TransactionSynchronizationManager.registerSynchronization(synch);
            status.setRollbackOnly();
        }
    });
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

    verify(synch).beforeCompletion();
    verify(synch).afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK);
}
项目:spring4-understanding    文件:JtaTransactionManagerTests.java   
@Test
public void jtaTransactionManagerWithPropagationSupportsAndSynchronizationNever() throws Exception {
    UserTransaction ut = mock(UserTransaction.class);
    given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION);

    JtaTransactionManager ptm = newJtaTransactionManager(ut);
    TransactionTemplate tt = new TransactionTemplate(ptm);
    ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_NEVER);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
    ptm.afterPropertiesSet();

    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
            status.setRollbackOnly();
        }
    });
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
项目:spring4-understanding    文件:JtaTransactionManagerTests.java   
@Test
public void jtaTransactionManagerWithPropagationRequiresNewAndSuspensionNotSupported() throws Exception {
    UserTransaction ut = mock(UserTransaction.class);
    given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

    JtaTransactionManager ptm = newJtaTransactionManager(ut);
    TransactionTemplate tt = new TransactionTemplate(ptm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    try {
        tt.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
            }
        });
        fail("Should have thrown TransactionSuspensionNotSupportedException");
    }
    catch (TransactionSuspensionNotSupportedException ex) {
        // expected
    }
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
项目:OpenCyclos    文件:IndexOperationRunner.java   
@Override
public void afterPropertiesSet() throws Exception {
    // Our transaction template will be read-only
    readonlyTransactionTemplate = new TransactionTemplate(transactionManager);
    readonlyTransactionTemplate.setReadOnly(true);

    cachedWriters = new HashMap<Class<?>, IndexWriter>();

    statusFile = new File(indexHandler.getIndexRoot(), "status");
    status = new Properties();
    try {
        status.load(new FileReader(statusFile));
        long time = Long.parseLong(status.getProperty(LAST_OPERATION_TIME));
        lastOperationTime = new GregorianCalendar();
        lastOperationTime.setTimeInMillis(time);
        lastOperationId = Long.parseLong(status.getProperty(LAST_OPERATION_ID));
    } catch (Exception e) {
        // Ok, ignore. We'll start with empty properties
        lastOperationTime = null;
        lastOperationId = null;
    }

    // Start the thread
    thread = new Thread(this, "IndexOperationRunner");
    thread.start();
}
项目:spring4-understanding    文件:JtaTransactionManagerTests.java   
@Test
public void jtaTransactionManagerWithSystemExceptionOnIsExisting() throws Exception {
    UserTransaction ut = mock(UserTransaction.class);
    given(ut.getStatus()).willThrow(new SystemException("system exception"));

    try {
        JtaTransactionManager ptm = newJtaTransactionManager(ut);
        TransactionTemplate tt = new TransactionTemplate(ptm);
        tt.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                // something transactional
            }
        });
        fail("Should have thrown TransactionSystemException");
    }
    catch (TransactionSystemException ex) {
        // expected
    }
}
项目:spring4-understanding    文件:JtaTransactionManagerTests.java   
@Test
public void jtaTransactionManagerWithNotSupportedExceptionOnNestedBegin() throws Exception {
    UserTransaction ut = mock(UserTransaction.class);
    given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
    willThrow(new NotSupportedException("not supported")).given(ut).begin();

    try {
        JtaTransactionManager ptm = newJtaTransactionManager(ut);
        TransactionTemplate tt = new TransactionTemplate(ptm);
        tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
        tt.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                // something transactional
            }
        });
        fail("Should have thrown NestedTransactionNotSupportedException");
    }
    catch (NestedTransactionNotSupportedException ex) {
        // expected
    }
}
项目:spring4-understanding    文件:JtaTransactionManagerTests.java   
@Test
public void jtaTransactionManagerWithSystemExceptionOnBegin() throws Exception {
    UserTransaction ut = mock(UserTransaction.class);
    given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION);
    willThrow(new SystemException("system exception")).given(ut).begin();

    try {
        JtaTransactionManager ptm = newJtaTransactionManager(ut);
        TransactionTemplate tt = new TransactionTemplate(ptm);
        tt.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                // something transactional
            }
        });
        fail("Should have thrown CannotCreateTransactionException");
    }
    catch (CannotCreateTransactionException ex) {
        // expected
    }
}
项目:Camel    文件:CustomerTransformer.java   
/**
 * Finds a customer for the given username
 */
private static CustomerEntity findCustomerByName(TransactionTemplate transactionTemplate, final EntityManager entityManager, final String userName) throws Exception {
    return transactionTemplate.execute(new TransactionCallback<CustomerEntity>() {
        public CustomerEntity doInTransaction(TransactionStatus status) {
            entityManager.joinTransaction();
            List<CustomerEntity> list = entityManager.createNamedQuery("findCustomerByUsername", CustomerEntity.class).setParameter("userName", userName).getResultList();
            CustomerEntity answer;
            if (list.isEmpty()) {
                answer = new CustomerEntity();
                answer.setUserName(userName);
                LOG.info("Created a new CustomerEntity {} as no matching persisted entity found.", answer);
            } else {
                answer = list.get(0);
                LOG.info("Found a matching CustomerEntity {} having the userName {}.", answer, userName);
            }

            return answer;
        }
    });
}
项目:spring4-understanding    文件:DataSourceTransactionManagerTests.java   
/**
 * Test behavior if the first operation on a connection (getAutoCommit) throws SQLException.
 */
@Test
public void testTransactionWithExceptionOnBegin() throws Exception {
    willThrow(new SQLException("Cannot begin")).given(con).getAutoCommit();

    TransactionTemplate tt = new TransactionTemplate(tm);
    try {
        tt.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                // something transactional
            }
        });
        fail("Should have thrown CannotCreateTransactionException");
    }
    catch (CannotCreateTransactionException ex) {
        // expected
    }

    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    verify(con).close();
}
项目:spring4-understanding    文件:DataSourceTransactionManagerTests.java   
@Test
public void testTransactionWithExceptionOnCommitAndRollbackOnCommitFailure() throws Exception {
    willThrow(new SQLException("Cannot commit")).given(con).commit();

    tm.setRollbackOnCommitFailure(true);
    TransactionTemplate tt = new TransactionTemplate(tm);
    try {
        tt.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                // something transactional
            }
        });
        fail("Should have thrown TransactionSystemException");
    }
    catch (TransactionSystemException ex) {
        // expected
    }

    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    verify(con).rollback();
    verify(con).close();
}
项目:spring4-understanding    文件:DataSourceTransactionManagerTests.java   
@Test
public void testTransactionWithExceptionOnRollback() throws Exception {
    given(con.getAutoCommit()).willReturn(true);
    willThrow(new SQLException("Cannot rollback")).given(con).rollback();

    TransactionTemplate tt = new TransactionTemplate(tm);
    try {
        tt.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
                status.setRollbackOnly();
            }
        });
        fail("Should have thrown TransactionSystemException");
    }
    catch (TransactionSystemException ex) {
        // expected
    }

    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    InOrder ordered = inOrder(con);
    ordered.verify(con).setAutoCommit(false);
    ordered.verify(con).rollback();
    ordered.verify(con).setAutoCommit(true);
    verify(con).close();
}
项目:spring4-understanding    文件:DataSourceTransactionManagerTests.java   
@Test
public void testTransactionWithPropagationNestedAndRollback() throws Exception {
    final TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());

    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            assertTrue("Is new transaction", status.isNewTransaction());
            status.setRollbackOnly();
        }
    });

    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    verify(con).rollback();
    verify(con).close();
}
项目:spring4-understanding    文件:PersistenceContextTransactionTests.java   
@Before
public void setUp() throws Exception {
    factory = mock(EntityManagerFactory.class);
    manager = mock(EntityManager.class);
    tx = mock(EntityTransaction.class);

    JpaTransactionManager tm = new JpaTransactionManager(factory);
    tt = new TransactionTemplate(tm);

    given(factory.createEntityManager()).willReturn(manager);
    given(manager.getTransaction()).willReturn(tx);
    given(manager.isOpen()).willReturn(true);

    bean = new EntityManagerHoldingBean();
    @SuppressWarnings("serial")
    PersistenceAnnotationBeanPostProcessor pabpp = new PersistenceAnnotationBeanPostProcessor() {
        @Override
        protected EntityManagerFactory findEntityManagerFactory(String unitName, String requestingBeanName) {
            return factory;
        }
    };
    pabpp.postProcessPropertyValues(null, null, bean, "bean");

    assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
项目:EasyTransaction    文件:DataBaseTransactionLogWritterImpl.java   
public DataBaseTransactionLogWritterImpl(ObjectSerializer objectSerializer,DataSource dataSource) {
    super();
    this.objectSerializer = objectSerializer;

    this.dataSource = dataSource;
    transactionManager = new DataSourceTransactionManager(dataSource);
    transactionTemplate = new TransactionTemplate(transactionManager, new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW));

}
项目:wherehowsX    文件:DatasetsDAO.java   
public static Object createFolderAction(final String name, final String path, final String children,
                                        final Long datasetId, final boolean flag, final Long bindId) {
    TransactionTemplate transactionTemplate = getTransactionTemplate();
    Object object = transactionTemplate.execute(new TransactionCallback<Object>() {
        public Object doInTransaction(TransactionStatus status) {
            int res = 0;
            try {
                // insert the record and get the folder id.
                KeyHolder keyHolder = new GeneratedKeyHolder();
                getJdbcTemplate().update(new PreparedStatementCreator() {
                            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                                PreparedStatement ps = getJdbcTemplate().getDataSource().getConnection().
                                        prepareStatement(CREATE_LOGIC_DATASET_FOLDER, new String[]{ "title" ,"path"});
                                ps.setString(1, name);
                                ps.setString(2, path);
                                return ps;
                            }
                        }, keyHolder);
                res = keyHolder.getKey().intValue();
                if (res <= 0) throw new Exception();

                String childrenList = children + (children.length() == 0?children:",") + res;
                int row = getJdbcTemplate().update(UPDATE_LOGIC_DATASET_CHILDREN, childrenList, datasetId);
                if (row <= 0) throw new Exception();

                if (!flag) {
                    row = getJdbcTemplate().update(UPDATE_LOGIC_DATASET_DATASETID, bindId, 0, res);
                    if (row <= 0) throw new Exception();
                }
            } catch (Exception e) {
                status.setRollbackOnly();
                e.printStackTrace();
            }
            return res;
        }
    });
    return object;
}
项目:springboot-shiro-cas-mybatis    文件:JpaTicketRegistryTests.java   
void addTicketInTransaction(final Ticket ticket) {
    new TransactionTemplate(txManager).execute(new TransactionCallback<Object>() {
        @Override
        public Void doInTransaction(final TransactionStatus status) {
            jpaTicketRegistry.addTicket(ticket);
            return null;
        }
    });
}
项目:springboot-shiro-cas-mybatis    文件:JpaTicketRegistryTests.java   
void deleteTicketInTransaction(final String ticketId) {
    new TransactionTemplate(txManager).execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(final TransactionStatus status) {
            jpaTicketRegistry.deleteTicket(ticketId);
            return null;
        }
    });
}