org.springframework.transaction.PlatformTransactionManager

Here are the examples of the java api org.springframework.transaction.PlatformTransactionManager taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

409 Examples 7

19 Source : TransactionConfiguration.java
with Apache License 2.0
from zhuoqianmingyue

/**
 * @Author jkli
 * @Date 2020/6/14 2:57 下午
 */
@Aspect
@Configuration
public clreplaced TransactionConfiguration {

    private static final int TX_METHOD_TIMEOUT = 5;

    private static final String AOP_POINTCUT_EXPRESSION = "execution( * cn.lijunkui.service.*.*(..))";

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Bean
    public TransactionInterceptor txAdvice() {
        NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
        /* 只读事务,不做更新操作 */
        RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute();
        readOnlyTx.setReadOnly(true);
        readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
        /* 当前存在事务就使用当前事务,当前不存在事务就创建一个新的事务 */
        RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute();
        requiredTx.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.clreplaced)));
        requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        // requiredTx.setTimeout(TX_METHOD_TIMEOUT);
        Map<String, TransactionAttribute> txMap = new HashMap<String, TransactionAttribute>();
        txMap.put("add*", requiredTx);
        txMap.put("save*", requiredTx);
        txMap.put("insert*", requiredTx);
        txMap.put("update*", requiredTx);
        txMap.put("delete*", requiredTx);
        txMap.put("get*", readOnlyTx);
        txMap.put("find*", readOnlyTx);
        txMap.put("query*", readOnlyTx);
        txMap.put("*", requiredTx);
        source.setNameMap(txMap);
        TransactionInterceptor txAdvice = new TransactionInterceptor(transactionManager, source);
        return txAdvice;
    }

    @Bean
    public Advisor txAdviceAdvisor() {
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
        return new DefaultPointcutAdvisor(pointcut, txAdvice());
    }
}

19 Source : SpringTransactionManager.java
with Apache License 2.0
from zhongxunking

/**
 * Spring事务管理器
 */
@AllArgsConstructor
public clreplaced SpringTransactionManager implements TransactionManager {

    // 融合事务类型定义
    private static final TransactionDefinition REQUIRED_DEFINITION = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED);

    // 新事务类型定义
    private static final TransactionDefinition REQUIRES_NEW_DEFINITION = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

    // 无事务类型定义
    private static final TransactionDefinition NOT_SUPPORTED_DEFINITION = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);

    // 事务管理器
    private final PlatformTransactionManager transactionManager;

    @Override
    public Object getTransaction(TransactionType type) {
        TransactionDefinition definition;
        switch(type) {
            case REQUIRED:
                definition = REQUIRED_DEFINITION;
                break;
            case REQUIRES_NEW:
                definition = REQUIRES_NEW_DEFINITION;
                break;
            case NOT_SUPPORTED:
                definition = NOT_SUPPORTED_DEFINITION;
                break;
            default:
                throw new IllegalArgumentException("type不能为null");
        }
        return transactionManager.getTransaction(definition);
    }

    @Override
    public void commit(Object status) {
        transactionManager.commit((TransactionStatus) status);
    }

    @Override
    public void rollback(Object status) {
        transactionManager.rollback((TransactionStatus) status);
    }
}

19 Source : DDDAutoConfiguration.java
with Apache License 2.0
from zhihuili

@Bean
@ConditionalOnMissingBean
@ConditionalOnBean(PlatformTransactionManager.clreplaced)
public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager) {
    return new TransactionTemplate(transactionManager);
}

19 Source : TransactionAutoConfigurationTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void singleTransactionManager() {
    load(new Clreplaced<?>[] { DataSourceAutoConfiguration.clreplaced, DataSourceTransactionManagerAutoConfiguration.clreplaced }, "spring.datasource.initialization-mode:never");
    PlatformTransactionManager transactionManager = this.context.getBean(PlatformTransactionManager.clreplaced);
    TransactionTemplate transactionTemplate = this.context.getBean(TransactionTemplate.clreplaced);
    replacedertThat(transactionTemplate.getTransactionManager()).isSameAs(transactionManager);
}

19 Source : AbstractJpaAutoConfigurationTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void usesManuallyDefinedTransactionManagerBeanIfAvailable() {
    this.contextRunner.withUserConfiguration(TestConfigurationWithTransactionManager.clreplaced).run((context) -> {
        PlatformTransactionManager txManager = context.getBean(PlatformTransactionManager.clreplaced);
        replacedertThat(txManager).isInstanceOf(CustomJpaTransactionManager.clreplaced);
    });
}

19 Source : JobLauncherCommandLineRunnerTests.java
with Apache License 2.0
from yuanmabiji

@Before
public void init() {
    this.context.register(BatchConfiguration.clreplaced);
    this.context.refresh();
    JobRepository jobRepository = this.context.getBean(JobRepository.clreplaced);
    JobLauncher jobLauncher = this.context.getBean(JobLauncher.clreplaced);
    this.jobs = new JobBuilderFactory(jobRepository);
    PlatformTransactionManager transactionManager = this.context.getBean(PlatformTransactionManager.clreplaced);
    this.steps = new StepBuilderFactory(jobRepository, transactionManager);
    Tasklet tasklet = (contribution, chunkContext) -> null;
    this.step = this.steps.get("step").tasklet(tasklet).build();
    this.job = this.jobs.get("job").start(this.step).build();
    this.jobExplorer = this.context.getBean(JobExplorer.clreplaced);
    this.runner = new JobLauncherCommandLineRunner(jobLauncher, this.jobExplorer, jobRepository);
    this.context.getBean(BatchConfiguration.clreplaced).clear();
}

19 Source : SpringTransactionProvider.java
with Apache License 2.0
from yuanmabiji

/**
 * Allows Spring Transaction to be used with JOOQ.
 *
 * @author Lukas Eder
 * @author Andreas Ahlenstorf
 * @author Phillip Webb
 * @since 1.5.10
 */
public clreplaced SpringTransactionProvider implements TransactionProvider {

    // Based on the jOOQ-spring-example from https://github.com/jOOQ/jOOQ
    private final PlatformTransactionManager transactionManager;

    public SpringTransactionProvider(PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    @Override
    public void begin(TransactionContext context) {
        TransactionDefinition definition = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_NESTED);
        TransactionStatus status = this.transactionManager.getTransaction(definition);
        context.transaction(new SpringTransaction(status));
    }

    @Override
    public void commit(TransactionContext ctx) {
        this.transactionManager.commit(getTransactionStatus(ctx));
    }

    @Override
    public void rollback(TransactionContext ctx) {
        this.transactionManager.rollback(getTransactionStatus(ctx));
    }

    private TransactionStatus getTransactionStatus(TransactionContext ctx) {
        SpringTransaction transaction = (SpringTransaction) ctx.transaction();
        return transaction.getTxStatus();
    }
}

19 Source : JooqAutoConfiguration.java
with Apache License 2.0
from yuanmabiji

@Bean
@ConditionalOnBean(PlatformTransactionManager.clreplaced)
public SpringTransactionProvider transactionProvider(PlatformTransactionManager txManager) {
    return new SpringTransactionProvider(txManager);
}

19 Source : BasicBatchConfigurer.java
with Apache License 2.0
from yuanmabiji

/**
 * Basic {@link BatchConfigurer} implementation.
 *
 * @author Dave Syer
 * @author Andy Wilkinson
 * @author Kazuki Shimizu
 * @author Stephane Nicoll
 */
public clreplaced BasicBatchConfigurer implements BatchConfigurer {

    private final BatchProperties properties;

    private final DataSource dataSource;

    private PlatformTransactionManager transactionManager;

    private final TransactionManagerCustomizers transactionManagerCustomizers;

    private JobRepository jobRepository;

    private JobLauncher jobLauncher;

    private JobExplorer jobExplorer;

    /**
     * Create a new {@link BasicBatchConfigurer} instance.
     * @param properties the batch properties
     * @param dataSource the underlying data source
     * @param transactionManagerCustomizers transaction manager customizers (or
     * {@code null})
     */
    protected BasicBatchConfigurer(BatchProperties properties, DataSource dataSource, TransactionManagerCustomizers transactionManagerCustomizers) {
        this.properties = properties;
        this.dataSource = dataSource;
        this.transactionManagerCustomizers = transactionManagerCustomizers;
    }

    @Override
    public JobRepository getJobRepository() {
        return this.jobRepository;
    }

    @Override
    public PlatformTransactionManager getTransactionManager() {
        return this.transactionManager;
    }

    @Override
    public JobLauncher getJobLauncher() {
        return this.jobLauncher;
    }

    @Override
    public JobExplorer getJobExplorer() throws Exception {
        return this.jobExplorer;
    }

    @PostConstruct
    public void initialize() {
        try {
            this.transactionManager = buildTransactionManager();
            this.jobRepository = createJobRepository();
            this.jobLauncher = createJobLauncher();
            this.jobExplorer = createJobExplorer();
        } catch (Exception ex) {
            throw new IllegalStateException("Unable to initialize Spring Batch", ex);
        }
    }

    protected JobExplorer createJobExplorer() throws Exception {
        PropertyMapper map = PropertyMapper.get();
        JobExplorerFactoryBean factory = new JobExplorerFactoryBean();
        factory.setDataSource(this.dataSource);
        map.from(this.properties::getTablePrefix).whenHasText().to(factory::setTablePrefix);
        factory.afterPropertiesSet();
        return factory.getObject();
    }

    protected JobLauncher createJobLauncher() throws Exception {
        SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
        jobLauncher.setJobRepository(getJobRepository());
        jobLauncher.afterPropertiesSet();
        return jobLauncher;
    }

    protected JobRepository createJobRepository() throws Exception {
        JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
        PropertyMapper map = PropertyMapper.get();
        map.from(this.dataSource).to(factory::setDataSource);
        map.from(this::determineIsolationLevel).whenNonNull().to(factory::setIsolationLevelForCreate);
        map.from(this.properties::getTablePrefix).whenHasText().to(factory::setTablePrefix);
        map.from(this::getTransactionManager).to(factory::setTransactionManager);
        factory.afterPropertiesSet();
        return factory.getObject();
    }

    /**
     * Determine the isolation level for create* operation of the {@link JobRepository}.
     * @return the isolation level or {@code null} to use the default
     */
    protected String determineIsolationLevel() {
        return null;
    }

    protected PlatformTransactionManager createTransactionManager() {
        return new DataSourceTransactionManager(this.dataSource);
    }

    private PlatformTransactionManager buildTransactionManager() {
        PlatformTransactionManager transactionManager = createTransactionManager();
        if (this.transactionManagerCustomizers != null) {
            this.transactionManagerCustomizers.customize(transactionManager);
        }
        return transactionManager;
    }
}

19 Source : BasicBatchConfigurer.java
with Apache License 2.0
from yuanmabiji

private PlatformTransactionManager buildTransactionManager() {
    PlatformTransactionManager transactionManager = createTransactionManager();
    if (this.transactionManagerCustomizers != null) {
        this.transactionManagerCustomizers.customize(transactionManager);
    }
    return transactionManager;
}

19 Source : SpringBatchConfiguration.java
with Apache License 2.0
from ypmc

/**
 * @author clyde lou
 */
@Configuration
@Slf4j
public clreplaced SpringBatchConfiguration implements BatchConfigurer {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private PlatformTransactionManager transactionManager;

    private JobRepository jobRepository;

    private JobLauncher jobLauncher;

    private JobExplorer jobExplorer;

    protected SpringBatchConfiguration() {
    }

    @Override
    @Bean
    public JobRepository getJobRepository() {
        return jobRepository;
    }

    @Override
    public PlatformTransactionManager getTransactionManager() {
        return transactionManager;
    }

    @Override
    @Bean
    public JobLauncher getJobLauncher() {
        return jobLauncher;
    }

    @Override
    @Bean
    public JobExplorer getJobExplorer() {
        return jobExplorer;
    }

    @PostConstruct
    public void initialize() {
        try {
            if (dataSource == null) {
                log.warn("No datasource was provided...using a Map based JobRepository");
                if (this.transactionManager == null) {
                    this.transactionManager = new ResourcelessTransactionManager();
                }
                MapJobRepositoryFactoryBean jobRepositoryFactory = new MapJobRepositoryFactoryBean(this.transactionManager);
                jobRepositoryFactory.afterPropertiesSet();
                this.jobRepository = jobRepositoryFactory.getObject();
                MapJobExplorerFactoryBean jobExplorerFactory = new MapJobExplorerFactoryBean(jobRepositoryFactory);
                jobExplorerFactory.afterPropertiesSet();
                this.jobExplorer = jobExplorerFactory.getObject();
            } else {
                this.jobRepository = createJobRepository();
                JobExplorerFactoryBean jobExplorerFactoryBean = new JobExplorerFactoryBean();
                jobExplorerFactoryBean.setDataSource(this.dataSource);
                jobExplorerFactoryBean.afterPropertiesSet();
                this.jobExplorer = jobExplorerFactoryBean.getObject();
            }
            this.jobLauncher = createJobLauncher();
        } catch (Exception e) {
            throw new BatchConfigurationException(e);
        }
    }

    private JobLauncher createJobLauncher() throws Exception {
        SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
        jobLauncher.setJobRepository(jobRepository);
        jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor());
        jobLauncher.afterPropertiesSet();
        return jobLauncher;
    }

    protected JobRepository createJobRepository() throws Exception {
        JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
        factory.setIsolationLevelForCreate("ISOLATION_SERIALIZABLE");
        factory.setDataSource(dataSource);
        factory.setTransactionManager(transactionManager);
        factory.setValidateTransactionState(false);
        factory.afterPropertiesSet();
        return factory.getObject();
    }

    @Bean
    public JobBuilderFactory jobBuilderFactory(JobRepository jobRepository) {
        return new JobBuilderFactory(jobRepository);
    }

    @Bean
    public StepBuilderFactory stepBuilderFactory(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
        return new StepBuilderFactory(jobRepository, transactionManager);
    }
}

19 Source : SpringTransactionCommandService.java
with Apache License 2.0
from youseries

/**
 * @author Jacky.gao
 * @since 2013年7月30日
 */
public clreplaced SpringTransactionCommandService implements CommandService, ApplicationContextAware {

    private ContextImpl context;

    private SessionFactory sessionFactory;

    private PlatformTransactionManager platformTransactionManager;

    private int springPropagationBehaviour = TransactionDefinition.PROPAGATION_REQUIRED;

    private int newSpringPropagationBehaviour = TransactionDefinition.PROPAGATION_REQUIRES_NEW;

    public <T> T executeCommand(final Command<T> command) {
        TransactionTemplate template = new TransactionTemplate(platformTransactionManager);
        template.setPropagationBehavior(springPropagationBehaviour);
        return template.execute(new TransactionCallback<T>() {

            public T doInTransaction(TransactionStatus status) {
                return command.execute(context);
            }
        });
    }

    public <T> T executeCommandInNewTransaction(final Command<T> command) {
        TransactionTemplate template = new TransactionTemplate(platformTransactionManager);
        template.setPropagationBehavior(newSpringPropagationBehaviour);
        return template.execute(new TransactionCallback<T>() {

            public T doInTransaction(TransactionStatus status) {
                return command.execute(context);
            }
        });
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.platformTransactionManager = EnvironmentUtils.getEnvironment().getPlatformTransactionManager();
        if (this.platformTransactionManager == null) {
            throw new RuntimeException("The " + EnvironmentProvider.clreplaced.getName() + " implements clreplaced's method 'getPlatformTransactionManager' can not return null.");
        }
        this.sessionFactory = EnvironmentUtils.getEnvironment().getSessionFactory();
        if (this.sessionFactory == null) {
            throw new RuntimeException("The " + EnvironmentProvider.clreplaced.getName() + " implements clreplaced's method 'getSessionFactory' can not return null.");
        }
        context = new ContextImpl();
        context.setCommandService(this);
        context.setApplicationContext(applicationContext);
        context.setSessionFactory(sessionFactory);
        context.setProcessService((ProcessService) applicationContext.getBean(ProcessService.BEAN_ID));
        context.setExpressionContext((ExpressionContext) applicationContext.getBean(ExpressionContext.BEAN_ID));
        context.setIdenreplacedyService((IdenreplacedyService) applicationContext.getBean(IdenreplacedyService.BEAN_ID));
        context.setTaskService((TaskService) applicationContext.getBean(TaskService.BEAN_ID));
    }
}

19 Source : SequenceService.java
with Apache License 2.0
from Yaccc

/**
 * Created by xiezhaodong  on 2018/2/23
 */
@Service
@Slf4j
public clreplaced SequenceService implements ISequenceService {

    @Resource(name = "txManager")
    private PlatformTransactionManager transactionManager;

    @Autowired
    private SequenceDao sequenceDao;

    private TransactionTemplate transactionTemplate = null;

    @PostConstruct
    public void init() {
        transactionTemplate = new TransactionTemplate(transactionManager);
    }

    public Segment buildSegment(@NonNull String appName, @NonNull String key) {
        // get new segment data from database
        return transactionTemplate.execute(status -> {
            int success0 = sequenceDao.updateMaxId(appName, key);
            CoreTable oneBizInfo = null;
            try {
                oneBizInfo = sequenceDao.getOneBizInfo(appName, key);
            } catch (Exception e) {
                return null;
            }
            if (success0 < 0 || oneBizInfo == null) {
                status.setRollbackOnly();
                log.error("transaction rollback !!!!,update SQL execute status is {}. and bizInfo is {}", success0, oneBizInfo);
                return null;
            }
            log.info("alloc [{},{}] new segment,maxid-{},minid-{},step-{}", appName, key, oneBizInfo.getNowMaxId(), oneBizInfo.getNowMaxId() - oneBizInfo.getStep(), oneBizInfo.getStep());
            Segment segment = // [min,max-1]
            Segment.builder().min(oneBizInfo.getNowMaxId() - oneBizInfo.getStep()).max(oneBizInfo.getNowMaxId() - 1).step(oneBizInfo.getStep()).build();
            segment.setInitCompleted(true);
            segment.setLongFactory(new AtomicLong(segment.getMin()));
            return segment;
        });
    }

    @Override
    public void changeStep(@NonNull String appName, @NonNull String key, int step) {
    }
}

19 Source : NestedJobDemo.java
with MIT License
from wuyouzhuguli

/**
 * @author MrBird
 */
@Component
public clreplaced NestedJobDemo {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    // 父任务
    @Bean
    public Job parentJob() {
        return jobBuilderFactory.get("parentJob").start(childJobOneStep()).next(childJobTwoStep()).build();
    }

    // 将任务转换为特殊的步骤
    private Step childJobOneStep() {
        return new JobStepBuilder(new StepBuilder("childJobOneStep")).job(childJobOne()).launcher(jobLauncher).repository(jobRepository).transactionManager(platformTransactionManager).build();
    }

    // 将任务转换为特殊的步骤
    private Step childJobTwoStep() {
        return new JobStepBuilder(new StepBuilder("childJobTwoStep")).job(childJobTwo()).launcher(jobLauncher).repository(jobRepository).transactionManager(platformTransactionManager).build();
    }

    // 子任务一
    private Job childJobOne() {
        return jobBuilderFactory.get("childJobOne").start(stepBuilderFactory.get("childJobOneStep").tasklet((stepContribution, chunkContext) -> {
            System.out.println("子任务一执行步骤。。。");
            return RepeatStatus.FINISHED;
        }).build()).build();
    }

    // 子任务二
    private Job childJobTwo() {
        return jobBuilderFactory.get("childJobTwo").start(stepBuilderFactory.get("childJobTwoStep").tasklet((stepContribution, chunkContext) -> {
            System.out.println("子任务二执行步骤。。。");
            return RepeatStatus.FINISHED;
        }).build()).build();
    }
}

19 Source : ActivitiConfig.java
with MIT License
from wligang

/**
 * @author Ligang.Wang
 * Activiti 配置
 */
@Configuration
@AllArgsConstructor
public clreplaced ActivitiConfig {

    private final DataSource dataSource;

    private final PlatformTransactionManager transactionManager;

    @Bean
    public SpringProcessEngineConfiguration getProcessEngineConfiguration() {
        SpringProcessEngineConfiguration config = new SpringProcessEngineConfiguration();
        // 流程图字体设置
        config.setActivityFontName("宋体");
        config.setAnnotationFontName("宋体");
        config.setLabelFontName("宋体");
        config.setDataSource(dataSource);
        config.setTransactionManager(transactionManager);
        config.setDatabaseType("mysql");
        config.setDatabaseSchemaUpdate("true");
        return config;
    }

    @Bean
    @Primary
    public TaskExecutor primaryTaskExecutor() {
        return new ThreadPoolTaskExecutor();
    }
}

19 Source : JmsComponentProducer.java
with Apache License 2.0
from wildfly-extras

@Produces
@Named("jms")
public JmsComponent createJmsComponent(PlatformTransactionManager transactionManager) {
    return JmsComponent.jmsComponentTransacted(connectionFactory, transactionManager);
}

19 Source : SpringTransactionManager.java
with Apache License 2.0
from WeBankFinTech

/**
 * @date 2020/7/23
 */
public clreplaced SpringTransactionManager extends JavaLog implements TransactionManager {

    private final PlatformTransactionManager platformTransactionManager;

    public SpringTransactionManager() {
        platformTransactionManager = MessageUtils.getBean(PlatformTransactionManager.clreplaced);
    }

    @Override
    public Object begin() {
        if (platformTransactionManager != null) {
            return platformTransactionManager.getTransaction(new DefaultTransactionAttribute());
        }
        return null;
    }

    @Override
    public void commit(Object o) {
        if (o instanceof TransactionStatus && platformTransactionManager != null) {
            platformTransactionManager.commit((TransactionStatus) o);
        }
    }

    @Override
    public void rollback(Object o) {
        if (o instanceof TransactionStatus && platformTransactionManager != null) {
            platformTransactionManager.rollback((TransactionStatus) o);
        }
    }
}

19 Source : TransactionInterceptorTests.java
with MIT License
from Vip-Augus

private TransactionInterceptor createTransactionInterceptor(BeanFactory beanFactory, String transactionManagerName, PlatformTransactionManager transactionManager) {
    TransactionInterceptor ti = new TransactionInterceptor();
    if (beanFactory != null) {
        ti.setBeanFactory(beanFactory);
    }
    if (transactionManagerName != null) {
        ti.setTransactionManagerBeanName(transactionManagerName);
    }
    if (transactionManager != null) {
        ti.setTransactionManager(transactionManager);
    }
    ti.setTransactionAttributeSource(new NameMatchTransactionAttributeSource());
    ti.afterPropertiesSet();
    return ti;
}

19 Source : TransactionInterceptorTests.java
with MIT License
from Vip-Augus

@Test
public void determineTransactionManagerWithQualifierAndDefault() {
    BeanFactory beanFactory = mock(BeanFactory.clreplaced);
    PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.clreplaced);
    TransactionInterceptor ti = transactionInterceptorWithTransactionManager(transactionManager, beanFactory);
    PlatformTransactionManager fooTransactionManager = replacedociateTransactionManager(beanFactory, "fooTransactionManager");
    DefaultTransactionAttribute attribute = new DefaultTransactionAttribute();
    attribute.setQualifier("fooTransactionManager");
    replacedertSame(fooTransactionManager, ti.determineTransactionManager(attribute));
}

19 Source : TransactionInterceptorTests.java
with MIT License
from Vip-Augus

@Test
public void determineTransactionManagerWithEmptyQualifierAndDefaultName() {
    BeanFactory beanFactory = mock(BeanFactory.clreplaced);
    PlatformTransactionManager defaultTransactionManager = replacedociateTransactionManager(beanFactory, "defaultTransactionManager");
    TransactionInterceptor ti = transactionInterceptorWithTransactionManagerName("defaultTransactionManager", beanFactory);
    DefaultTransactionAttribute attribute = new DefaultTransactionAttribute();
    attribute.setQualifier("");
    replacedertSame(defaultTransactionManager, ti.determineTransactionManager(attribute));
}

19 Source : TransactionInterceptorTests.java
with MIT License
from Vip-Augus

private TransactionInterceptor transactionInterceptorWithTransactionManager(PlatformTransactionManager transactionManager, BeanFactory beanFactory) {
    return createTransactionInterceptor(beanFactory, null, transactionManager);
}

19 Source : TransactionInterceptorTests.java
with MIT License
from Vip-Augus

@Test
public void determineTransactionManagerWithNoBeanFactory() {
    PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.clreplaced);
    TransactionInterceptor ti = transactionInterceptorWithTransactionManager(transactionManager, null);
    replacedertSame(transactionManager, ti.determineTransactionManager(new DefaultTransactionAttribute()));
}

19 Source : TransactionInterceptorTests.java
with MIT License
from Vip-Augus

@Test
public void determineTransactionManagerWithBeanNameSeveralTimes() {
    BeanFactory beanFactory = mock(BeanFactory.clreplaced);
    TransactionInterceptor ti = transactionInterceptorWithTransactionManagerName("fooTransactionManager", beanFactory);
    PlatformTransactionManager txManager = replacedociateTransactionManager(beanFactory, "fooTransactionManager");
    DefaultTransactionAttribute attribute = new DefaultTransactionAttribute();
    PlatformTransactionManager actual = ti.determineTransactionManager(attribute);
    replacedertSame(txManager, actual);
    // Call again, should be cached
    PlatformTransactionManager actual2 = ti.determineTransactionManager(attribute);
    replacedertSame(txManager, actual2);
    verify(beanFactory, times(1)).getBean("fooTransactionManager", PlatformTransactionManager.clreplaced);
}

19 Source : TransactionInterceptorTests.java
with MIT License
from Vip-Augus

@Test
public void determineTransactionManagerWithQualifierSeveralTimes() {
    BeanFactory beanFactory = mock(BeanFactory.clreplaced);
    TransactionInterceptor ti = simpleTransactionInterceptor(beanFactory);
    PlatformTransactionManager txManager = replacedociateTransactionManager(beanFactory, "fooTransactionManager");
    DefaultTransactionAttribute attribute = new DefaultTransactionAttribute();
    attribute.setQualifier("fooTransactionManager");
    PlatformTransactionManager actual = ti.determineTransactionManager(attribute);
    replacedertSame(txManager, actual);
    // Call again, should be cached
    PlatformTransactionManager actual2 = ti.determineTransactionManager(attribute);
    replacedertSame(txManager, actual2);
    verify(beanFactory, times(1)).containsBean("fooTransactionManager");
    verify(beanFactory, times(1)).getBean("fooTransactionManager", PlatformTransactionManager.clreplaced);
}

19 Source : TransactionInterceptorTests.java
with MIT License
from Vip-Augus

@Test
public void determineTransactionManagerWithNoBeanFactoryAndNoTransactionAttribute() {
    PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.clreplaced);
    TransactionInterceptor ti = transactionInterceptorWithTransactionManager(transactionManager, null);
    replacedertSame(transactionManager, ti.determineTransactionManager(null));
}

19 Source : TransactionInterceptorTests.java
with MIT License
from Vip-Augus

@Test
public void determineTransactionManagerWithQualifierAndDefaultName() {
    BeanFactory beanFactory = mock(BeanFactory.clreplaced);
    replacedociateTransactionManager(beanFactory, "defaultTransactionManager");
    TransactionInterceptor ti = transactionInterceptorWithTransactionManagerName("defaultTransactionManager", beanFactory);
    PlatformTransactionManager fooTransactionManager = replacedociateTransactionManager(beanFactory, "fooTransactionManager");
    DefaultTransactionAttribute attribute = new DefaultTransactionAttribute();
    attribute.setQualifier("fooTransactionManager");
    replacedertSame(fooTransactionManager, ti.determineTransactionManager(attribute));
}

19 Source : PlatformTransactionManagerFacade.java
with MIT License
from Vip-Augus

/**
 * Used for testing only (for example, when we must replace the
 * behavior of a PlatformTransactionManager bean we don't have access to).
 *
 * <p>Allows behavior of an entire clreplaced to change with static delegate change.
 * Not multi-threaded.
 *
 * @author Rod Johnson
 * @since 26.04.2003
 */
public clreplaced PlatformTransactionManagerFacade implements PlatformTransactionManager {

    /**
     * This member can be changed to change behavior clreplaced-wide.
     */
    public static PlatformTransactionManager delegate;

    @Override
    public TransactionStatus getTransaction(@Nullable TransactionDefinition definition) {
        return delegate.getTransaction(definition);
    }

    @Override
    public void commit(TransactionStatus status) {
        delegate.commit(status);
    }

    @Override
    public void rollback(TransactionStatus status) {
        delegate.rollback(status);
    }
}

19 Source : AbstractTransactionAspectTests.java
with MIT License
from Vip-Augus

protected Object advised(Object target, PlatformTransactionManager ptm, TransactionAttributeSource[] tas) throws Exception {
    return advised(target, ptm, new CompositeTransactionAttributeSource(tas));
}

19 Source : TransactionTemplate.java
with MIT License
from Vip-Augus

/**
 * Template clreplaced that simplifies programmatic transaction demarcation and
 * transaction exception handling.
 *
 * <p>The central method is {@link #execute}, supporting transactional code that
 * implements the {@link TransactionCallback} interface. This template handles
 * the transaction lifecycle and possible exceptions such that neither the
 * TransactionCallback implementation nor the calling code needs to explicitly
 * handle transactions.
 *
 * <p>Typical usage: Allows for writing low-level data access objects that use
 * resources such as JDBC DataSources but are not transaction-aware themselves.
 * Instead, they can implicitly participate in transactions handled by higher-level
 * application services utilizing this clreplaced, making calls to the low-level
 * services via an inner-clreplaced callback object.
 *
 * <p>Can be used within a service implementation via direct instantiation with
 * a transaction manager reference, or get prepared in an application context
 * and preplaceded to services as bean reference. Note: The transaction manager should
 * always be configured as bean in the application context: in the first case given
 * to the service directly, in the second case given to the prepared template.
 *
 * <p>Supports setting the propagation behavior and the isolation level by name,
 * for convenient configuration in context definitions.
 *
 * @author Juergen Hoeller
 * @since 17.03.2003
 * @see #execute
 * @see #setTransactionManager
 * @see org.springframework.transaction.PlatformTransactionManager
 */
@SuppressWarnings("serial")
public clreplaced TransactionTemplate extends DefaultTransactionDefinition implements TransactionOperations, InitializingBean {

    /**
     * Logger available to subclreplacedes.
     */
    protected final Log logger = LogFactory.getLog(getClreplaced());

    @Nullable
    private PlatformTransactionManager transactionManager;

    /**
     * Construct a new TransactionTemplate for bean usage.
     * <p>Note: The PlatformTransactionManager needs to be set before
     * any {@code execute} calls.
     * @see #setTransactionManager
     */
    public TransactionTemplate() {
    }

    /**
     * Construct a new TransactionTemplate using the given transaction manager.
     * @param transactionManager the transaction management strategy to be used
     */
    public TransactionTemplate(PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    /**
     * Construct a new TransactionTemplate using the given transaction manager,
     * taking its default settings from the given transaction definition.
     * @param transactionManager the transaction management strategy to be used
     * @param transactionDefinition the transaction definition to copy the
     * default settings from. Local properties can still be set to change values.
     */
    public TransactionTemplate(PlatformTransactionManager transactionManager, TransactionDefinition transactionDefinition) {
        super(transactionDefinition);
        this.transactionManager = transactionManager;
    }

    /**
     * Set the transaction management strategy to be used.
     */
    public void setTransactionManager(@Nullable PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    /**
     * Return the transaction management strategy to be used.
     */
    @Nullable
    public PlatformTransactionManager getTransactionManager() {
        return this.transactionManager;
    }

    @Override
    public void afterPropertiesSet() {
        if (this.transactionManager == null) {
            throw new IllegalArgumentException("Property 'transactionManager' is required");
        }
    }

    @Override
    @Nullable
    public <T> T execute(TransactionCallback<T> action) throws TransactionException {
        replacedert.state(this.transactionManager != null, "No PlatformTransactionManager set");
        if (this.transactionManager instanceof CallbackPreferringPlatformTransactionManager) {
            return ((CallbackPreferringPlatformTransactionManager) this.transactionManager).execute(this, action);
        } else {
            TransactionStatus status = this.transactionManager.getTransaction(this);
            T result;
            try {
                result = action.doInTransaction(status);
            } catch (RuntimeException | Error ex) {
                // Transactional code threw application exception -> rollback
                rollbackOnException(status, ex);
                throw ex;
            } catch (Throwable ex) {
                // Transactional code threw unexpected exception -> rollback
                rollbackOnException(status, ex);
                throw new UndeclaredThrowableException(ex, "TransactionCallback threw undeclared checked exception");
            }
            this.transactionManager.commit(status);
            return result;
        }
    }

    /**
     * Perform a rollback, handling rollback exceptions properly.
     * @param status object representing the transaction
     * @param ex the thrown application exception or error
     * @throws TransactionException in case of a rollback error
     */
    private void rollbackOnException(TransactionStatus status, Throwable ex) throws TransactionException {
        replacedert.state(this.transactionManager != null, "No PlatformTransactionManager set");
        logger.debug("Initiating transaction rollback on application exception", ex);
        try {
            this.transactionManager.rollback(status);
        } catch (TransactionSystemException ex2) {
            logger.error("Application exception overridden by rollback exception", ex);
            ex2.initApplicationException(ex);
            throw ex2;
        } catch (RuntimeException | Error ex2) {
            logger.error("Application exception overridden by rollback exception", ex);
            throw ex2;
        }
    }

    @Override
    public boolean equals(Object other) {
        return (this == other || (super.equals(other) && (!(other instanceof TransactionTemplate) || getTransactionManager() == ((TransactionTemplate) other).getTransactionManager())));
    }
}

19 Source : TransactionTemplate.java
with MIT License
from Vip-Augus

/**
 * Set the transaction management strategy to be used.
 */
public void setTransactionManager(@Nullable PlatformTransactionManager transactionManager) {
    this.transactionManager = transactionManager;
}

19 Source : TransactionProxyFactoryBean.java
with MIT License
from Vip-Augus

/**
 * Set the default transaction manager. This will perform actual
 * transaction management: This clreplaced is just a way of invoking it.
 * @see TransactionInterceptor#setTransactionManager
 */
public void setTransactionManager(PlatformTransactionManager transactionManager) {
    this.transactionInterceptor.setTransactionManager(transactionManager);
}

19 Source : TransactionAspectSupport.java
with MIT License
from Vip-Augus

/**
 * Prepare a TransactionInfo for the given attribute and status object.
 * @param txAttr the TransactionAttribute (may be {@code null})
 * @param joinpointIdentification the fully qualified method name
 * (used for monitoring and logging purposes)
 * @param status the TransactionStatus for the current transaction
 * @return the prepared TransactionInfo object
 */
protected TransactionInfo prepareTransactionInfo(@Nullable PlatformTransactionManager tm, @Nullable TransactionAttribute txAttr, String joinpointIdentification, @Nullable TransactionStatus status) {
    TransactionInfo txInfo = new TransactionInfo(tm, txAttr, joinpointIdentification);
    if (txAttr != null) {
        // We need a transaction for this method...
        if (logger.isTraceEnabled()) {
            logger.trace("Getting transaction for [" + txInfo.getJoinpointIdentification() + "]");
        }
        // The transaction manager will flag an error if an incompatible tx already exists.
        txInfo.newTransactionStatus(status);
    } else {
        // The TransactionInfo.hasTransaction() method will return false. We created it only
        // to preserve the integrity of the ThreadLocal stack maintained in this clreplaced.
        if (logger.isTraceEnabled()) {
            logger.trace("No need to create transaction for [" + joinpointIdentification + "]: This method is not transactional.");
        }
    }
    // We always bind the TransactionInfo to the thread, even if we didn't create
    // a new transaction here. This guarantees that the TransactionInfo stack
    // will be managed correctly even if no transaction was created by this aspect.
    txInfo.bindToThread();
    return txInfo;
}

19 Source : TransactionAspectSupport.java
with MIT License
from Vip-Augus

private PlatformTransactionManager determineQualifiedTransactionManager(BeanFactory beanFactory, String qualifier) {
    PlatformTransactionManager txManager = asPlatformTransactionManager(this.transactionManagerCache.get(qualifier));
    if (txManager == null) {
        txManager = BeanFactoryAnnotationUtils.qualifiedBeanOfType(beanFactory, PlatformTransactionManager.clreplaced, qualifier);
        this.transactionManagerCache.putIfAbsent(qualifier, txManager);
    }
    return txManager;
}

19 Source : AbstractEntityManagerFactoryIntegrationTests.java
with MIT License
from Vip-Augus

/**
 * @author Rod Johnson
 * @author Juergen Hoeller
 */
public abstract clreplaced AbstractEnreplacedyManagerFactoryIntegrationTests {

    protected static final String[] ECLIPSELINK_CONFIG_LOCATIONS = new String[] { "/org/springframework/orm/jpa/eclipselink/eclipselink-manager.xml", "/org/springframework/orm/jpa/memdb.xml", "/org/springframework/orm/jpa/inject.xml" };

    private static ConfigurableApplicationContext applicationContext;

    protected EnreplacedyManagerFactory enreplacedyManagerFactory;

    protected EnreplacedyManager sharedEnreplacedyManager;

    protected PlatformTransactionManager transactionManager;

    protected DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();

    protected TransactionStatus transactionStatus;

    private boolean complete = false;

    protected JdbcTemplate jdbcTemplate;

    private boolean zappedTables = false;

    @Autowired
    public void setEnreplacedyManagerFactory(EnreplacedyManagerFactory enreplacedyManagerFactory) {
        this.enreplacedyManagerFactory = enreplacedyManagerFactory;
        this.sharedEnreplacedyManager = SharedEnreplacedyManagerCreator.createSharedEnreplacedyManager(this.enreplacedyManagerFactory);
    }

    @Autowired
    public void setTransactionManager(PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Before
    public void setup() {
        if (applicationContext == null) {
            applicationContext = new ClreplacedPathXmlApplicationContext(getConfigLocations());
        }
        applicationContext.getAutowireCapableBeanFactory().autowireBean(this);
        if (this.transactionManager != null && this.transactionDefinition != null) {
            startNewTransaction();
        }
    }

    protected String[] getConfigLocations() {
        return ECLIPSELINK_CONFIG_LOCATIONS;
    }

    @After
    public void cleanup() {
        if (this.transactionStatus != null && !this.transactionStatus.isCompleted()) {
            endTransaction();
        }
        replacedertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
        replacedertFalse(TransactionSynchronizationManager.isSynchronizationActive());
        replacedertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
        replacedertFalse(TransactionSynchronizationManager.isActualTransactionActive());
    }

    @AfterClreplaced
    public static void closeContext() {
        if (applicationContext != null) {
            applicationContext.close();
            applicationContext = null;
        }
    }

    protected EnreplacedyManager createContainerManagedEnreplacedyManager() {
        return ExtendedEnreplacedyManagerCreator.createContainerManagedEnreplacedyManager(this.enreplacedyManagerFactory);
    }

    protected void setComplete() {
        if (this.transactionManager == null) {
            throw new IllegalStateException("No transaction manager set");
        }
        if (this.zappedTables) {
            throw new IllegalStateException("Cannot set complete after deleting tables");
        }
        this.complete = true;
    }

    protected void endTransaction() {
        final boolean commit = this.complete;
        if (this.transactionStatus != null) {
            try {
                if (commit) {
                    this.transactionManager.commit(this.transactionStatus);
                } else {
                    this.transactionManager.rollback(this.transactionStatus);
                }
            } finally {
                this.transactionStatus = null;
            }
        }
    }

    protected void startNewTransaction() throws TransactionException {
        this.transactionStatus = this.transactionManager.getTransaction(this.transactionDefinition);
    }

    protected void deleteFromTables(String... tableNames) {
        for (String tableName : tableNames) {
            this.jdbcTemplate.update("DELETE FROM " + tableName);
        }
        this.zappedTables = true;
    }

    protected int countRowsInTable(EnreplacedyManager em, String tableName) {
        Query query = em.createNativeQuery("SELECT COUNT(0) FROM " + tableName);
        return ((Number) query.getSingleResult()).intValue();
    }

    protected int countRowsInTable(String tableName) {
        return this.jdbcTemplate.queryForObject("SELECT COUNT(0) FROM " + tableName, Integer.clreplaced);
    }

    protected void executeSqlScript(String sqlResourcePath) throws DataAccessException {
        Resource resource = applicationContext.getResource(sqlResourcePath);
        new ResourceDatabasePopulator(resource).execute(this.jdbcTemplate.getDataSource());
    }
}

19 Source : AbstractPollingMessageListenerContainer.java
with MIT License
from Vip-Augus

/**
 * Base clreplaced for listener container implementations which are based on polling.
 * Provides support for listener handling based on {@link javax.jms.MessageConsumer},
 * optionally participating in externally managed transactions.
 *
 * <p>This listener container variant is built for repeated polling attempts,
 * each invoking the {@link #receiveAndExecute} method. The MessageConsumer used
 * may be reobtained fo reach attempt or cached in between attempts; this is up
 * to the concrete implementation. The receive timeout for each attempt can be
 * configured through the {@link #setReceiveTimeout "receiveTimeout"} property.
 *
 * <p>The underlying mechanism is based on standard JMS MessageConsumer handling,
 * which is perfectly compatible with both native JMS and JMS in a Java EE environment.
 * Neither the JMS {@code MessageConsumer.setMessageListener} facility  nor the JMS
 * ServerSessionPool facility is required. A further advantage of this approach is
 * full control over the listening process, allowing for custom scaling and throttling
 * and of concurrent message processing (which is up to concrete subclreplacedes).
 *
 * <p>Message reception and listener execution can automatically be wrapped
 * in transactions through preplaceding a Spring
 * {@link org.springframework.transaction.PlatformTransactionManager} into the
 * {@link #setTransactionManager "transactionManager"} property. This will usually
 * be a {@link org.springframework.transaction.jta.JtaTransactionManager} in a
 * Java EE environment, in combination with a JTA-aware JMS ConnectionFactory
 * obtained from JNDI (check your application server's doreplacedentation).
 *
 * <p>This base clreplaced does not replacedume any specific mechanism for asynchronous
 * execution of polling invokers. Check out {@link DefaultMessageListenerContainer}
 * for a concrete implementation which is based on Spring's
 * {@link org.springframework.core.task.TaskExecutor} abstraction,
 * including dynamic scaling of concurrent consumers and automatic self recovery.
 *
 * @author Juergen Hoeller
 * @since 2.0.3
 * @see #createListenerConsumer
 * @see #receiveAndExecute
 * @see #setTransactionManager
 */
public abstract clreplaced AbstractPollingMessageListenerContainer extends AbstractMessageListenerContainer {

    /**
     * The default receive timeout: 1000 ms = 1 second.
     */
    public static final long DEFAULT_RECEIVE_TIMEOUT = 1000;

    private final MessageListenerContainerResourceFactory transactionalResourceFactory = new MessageListenerContainerResourceFactory();

    private boolean sessionTransactedCalled = false;

    @Nullable
    private PlatformTransactionManager transactionManager;

    private DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();

    private long receiveTimeout = DEFAULT_RECEIVE_TIMEOUT;

    @Override
    public void setSessionTransacted(boolean sessionTransacted) {
        super.setSessionTransacted(sessionTransacted);
        this.sessionTransactedCalled = true;
    }

    /**
     * Specify the Spring {@link org.springframework.transaction.PlatformTransactionManager}
     * to use for transactional wrapping of message reception plus listener execution.
     * <p>Default is none, not performing any transactional wrapping.
     * If specified, this will usually be a Spring
     * {@link org.springframework.transaction.jta.JtaTransactionManager} or one
     * of its subclreplacedes, in combination with a JTA-aware ConnectionFactory that
     * this message listener container obtains its Connections from.
     * <p><b>Note: Consider the use of local JMS transactions instead.</b>
     * Simply switch the {@link #setSessionTransacted "sessionTransacted"} flag
     * to "true" in order to use a locally transacted JMS Session for the entire
     * receive processing, including any Session operations performed by a
     * {@link SessionAwareMessageListener} (e.g. sending a response message). This
     * allows for fully synchronized Spring transactions based on local JMS
     * transactions, similar to what
     * {@link org.springframework.jms.connection.JmsTransactionManager} provides. Check
     * {@link AbstractMessageListenerContainer}'s javadoc for
     * a discussion of transaction choices and message redelivery scenarios.
     * @see #setSessionTransacted(boolean)
     * @see org.springframework.transaction.jta.JtaTransactionManager
     * @see org.springframework.jms.connection.JmsTransactionManager
     */
    public void setTransactionManager(@Nullable PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    /**
     * Return the Spring PlatformTransactionManager to use for transactional
     * wrapping of message reception plus listener execution.
     */
    @Nullable
    protected final PlatformTransactionManager getTransactionManager() {
        return this.transactionManager;
    }

    /**
     * Specify the transaction name to use for transactional wrapping.
     * Default is the bean name of this listener container, if any.
     * @see org.springframework.transaction.TransactionDefinition#getName()
     */
    public void setTransactionName(String transactionName) {
        this.transactionDefinition.setName(transactionName);
    }

    /**
     * Specify the transaction timeout to use for transactional wrapping, in <b>seconds</b>.
     * Default is none, using the transaction manager's default timeout.
     * @see org.springframework.transaction.TransactionDefinition#getTimeout()
     * @see #setReceiveTimeout
     */
    public void setTransactionTimeout(int transactionTimeout) {
        this.transactionDefinition.setTimeout(transactionTimeout);
    }

    /**
     * Set the timeout to use for receive calls, in <b>milliseconds</b>.
     * The default is 1000 ms, that is, 1 second.
     * <p><b>NOTE:</b> This value needs to be smaller than the transaction
     * timeout used by the transaction manager (in the appropriate unit,
     * of course). 0 indicates no timeout at all; however, this is only
     * feasible if not running within a transaction manager and generally
     * discouraged since such a listener container cannot cleanly shut down.
     * A negative value such as -1 indicates a no-wait receive operation.
     * @see #receiveFromConsumer(MessageConsumer, long)
     * @see javax.jms.MessageConsumer#receive(long)
     * @see javax.jms.MessageConsumer#receiveNoWait()
     * @see javax.jms.MessageConsumer#receive()
     * @see #setTransactionTimeout
     */
    public void setReceiveTimeout(long receiveTimeout) {
        this.receiveTimeout = receiveTimeout;
    }

    /**
     * Return the receive timeout (ms) configured for this listener container.
     * @since 4.2
     */
    protected long getReceiveTimeout() {
        return this.receiveTimeout;
    }

    @Override
    public void initialize() {
        // Set sessionTransacted=true in case of a non-JTA transaction manager.
        if (!this.sessionTransactedCalled && this.transactionManager instanceof ResourceTransactionManager && !TransactionSynchronizationUtils.sameResourceFactory((ResourceTransactionManager) this.transactionManager, obtainConnectionFactory())) {
            super.setSessionTransacted(true);
        }
        // Use bean name as default transaction name.
        if (this.transactionDefinition.getName() == null) {
            String beanName = getBeanName();
            if (beanName != null) {
                this.transactionDefinition.setName(beanName);
            }
        }
        // Proceed with superclreplaced initialization.
        super.initialize();
    }

    /**
     * Create a MessageConsumer for the given JMS Session,
     * registering a MessageListener for the specified listener.
     * @param session the JMS Session to work on
     * @return the MessageConsumer
     * @throws javax.jms.JMSException if thrown by JMS methods
     * @see #receiveAndExecute
     */
    protected MessageConsumer createListenerConsumer(Session session) throws JMSException {
        Destination destination = getDestination();
        if (destination == null) {
            String destinationName = getDestinationName();
            replacedert.state(destinationName != null, "No destination set");
            destination = resolveDestinationName(session, destinationName);
        }
        return createConsumer(session, destination);
    }

    /**
     * Execute the listener for a message received from the given consumer,
     * wrapping the entire operation in an external transaction if demanded.
     * @param session the JMS Session to work on
     * @param consumer the MessageConsumer to work on
     * @return whether a message has been received
     * @throws JMSException if thrown by JMS methods
     * @see #doReceiveAndExecute
     */
    protected boolean receiveAndExecute(Object invoker, @Nullable Session session, @Nullable MessageConsumer consumer) throws JMSException {
        if (this.transactionManager != null) {
            // Execute receive within transaction.
            TransactionStatus status = this.transactionManager.getTransaction(this.transactionDefinition);
            boolean messageReceived;
            try {
                messageReceived = doReceiveAndExecute(invoker, session, consumer, status);
            } catch (JMSException | RuntimeException | Error ex) {
                rollbackOnException(this.transactionManager, status, ex);
                throw ex;
            }
            this.transactionManager.commit(status);
            return messageReceived;
        } else {
            // Execute receive outside of transaction.
            return doReceiveAndExecute(invoker, session, consumer, null);
        }
    }

    /**
     * Actually execute the listener for a message received from the given consumer,
     * fetching all requires resources and invoking the listener.
     * @param session the JMS Session to work on
     * @param consumer the MessageConsumer to work on
     * @param status the TransactionStatus (may be {@code null})
     * @return whether a message has been received
     * @throws JMSException if thrown by JMS methods
     * @see #doExecuteListener(javax.jms.Session, javax.jms.Message)
     */
    protected boolean doReceiveAndExecute(Object invoker, @Nullable Session session, @Nullable MessageConsumer consumer, @Nullable TransactionStatus status) throws JMSException {
        Connection conToClose = null;
        Session sessionToClose = null;
        MessageConsumer consumerToClose = null;
        try {
            Session sessionToUse = session;
            boolean transactional = false;
            if (sessionToUse == null) {
                sessionToUse = ConnectionFactoryUtils.doGetTransactionalSession(obtainConnectionFactory(), this.transactionalResourceFactory, true);
                transactional = (sessionToUse != null);
            }
            if (sessionToUse == null) {
                Connection conToUse;
                if (sharedConnectionEnabled()) {
                    conToUse = getSharedConnection();
                } else {
                    conToUse = createConnection();
                    conToClose = conToUse;
                    conToUse.start();
                }
                sessionToUse = createSession(conToUse);
                sessionToClose = sessionToUse;
            }
            MessageConsumer consumerToUse = consumer;
            if (consumerToUse == null) {
                consumerToUse = createListenerConsumer(sessionToUse);
                consumerToClose = consumerToUse;
            }
            Message message = receiveMessage(consumerToUse);
            if (message != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Received message of type [" + message.getClreplaced() + "] from consumer [" + consumerToUse + "] of " + (transactional ? "transactional " : "") + "session [" + sessionToUse + "]");
                }
                messageReceived(invoker, sessionToUse);
                boolean exposeResource = (!transactional && isExposeListenerSession() && !TransactionSynchronizationManager.hasResource(obtainConnectionFactory()));
                if (exposeResource) {
                    TransactionSynchronizationManager.bindResource(obtainConnectionFactory(), new LocallyExposedJmsResourceHolder(sessionToUse));
                }
                try {
                    doExecuteListener(sessionToUse, message);
                } catch (Throwable ex) {
                    if (status != null) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Rolling back transaction because of listener exception thrown: " + ex);
                        }
                        status.setRollbackOnly();
                    }
                    handleListenerException(ex);
                    // Rethrow JMSException to indicate an infrastructure problem
                    // that may have to trigger recovery...
                    if (ex instanceof JMSException) {
                        throw (JMSException) ex;
                    }
                } finally {
                    if (exposeResource) {
                        TransactionSynchronizationManager.unbindResource(obtainConnectionFactory());
                    }
                }
                // Indicate that a message has been received.
                return true;
            } else {
                if (logger.isTraceEnabled()) {
                    logger.trace("Consumer [" + consumerToUse + "] of " + (transactional ? "transactional " : "") + "session [" + sessionToUse + "] did not receive a message");
                }
                noMessageReceived(invoker, sessionToUse);
                // Nevertheless call commit, in order to reset the transaction timeout (if any).
                if (shouldCommitAfterNoMessageReceived(sessionToUse)) {
                    commitIfNecessary(sessionToUse, null);
                }
                // Indicate that no message has been received.
                return false;
            }
        } finally {
            JmsUtils.closeMessageConsumer(consumerToClose);
            JmsUtils.closeSession(sessionToClose);
            ConnectionFactoryUtils.releaseConnection(conToClose, getConnectionFactory(), true);
        }
    }

    /**
     * This implementation checks whether the Session is externally synchronized.
     * In this case, the Session is not locally transacted, despite the listener
     * container's "sessionTransacted" flag being set to "true".
     * @see org.springframework.jms.connection.JmsResourceHolder
     */
    @Override
    protected boolean isSessionLocallyTransacted(Session session) {
        if (!super.isSessionLocallyTransacted(session)) {
            return false;
        }
        JmsResourceHolder resourceHolder = (JmsResourceHolder) TransactionSynchronizationManager.getResource(obtainConnectionFactory());
        return (resourceHolder == null || resourceHolder instanceof LocallyExposedJmsResourceHolder || !resourceHolder.containsSession(session));
    }

    /**
     * Determine whether to trigger a commit after no message has been received.
     * This is a good idea on any modern-day JMS provider.
     * @param session the current JMS Session which received no message
     * @return whether to call {@link #commitIfNecessary} on the given Session
     */
    protected boolean shouldCommitAfterNoMessageReceived(Session session) {
        return true;
    }

    /**
     * Perform a rollback, handling rollback exceptions properly.
     * @param status object representing the transaction
     * @param ex the thrown listener exception or error
     */
    private void rollbackOnException(PlatformTransactionManager manager, TransactionStatus status, Throwable ex) {
        logger.debug("Initiating transaction rollback on listener exception", ex);
        try {
            manager.rollback(status);
        } catch (RuntimeException ex2) {
            logger.error("Listener exception overridden by rollback exception", ex);
            throw ex2;
        } catch (Error err) {
            logger.error("Listener exception overridden by rollback error", ex);
            throw err;
        }
    }

    /**
     * Receive a message from the given consumer.
     * @param consumer the MessageConsumer to use
     * @return the Message, or {@code null} if none
     * @throws JMSException if thrown by JMS methods
     */
    @Nullable
    protected Message receiveMessage(MessageConsumer consumer) throws JMSException {
        return receiveFromConsumer(consumer, getReceiveTimeout());
    }

    /**
     * Template method that gets called right when a new message has been received,
     * before attempting to process it. Allows subclreplacedes to react to the event
     * of an actual incoming message, for example adapting their consumer count.
     * @param invoker the invoker object (preplaceded through)
     * @param session the receiving JMS Session
     */
    protected void messageReceived(Object invoker, Session session) {
    }

    /**
     * Template method that gets called when <i>no</i> message has been received,
     * before returning to the receive loop again. Allows subclreplacedes to react to
     * the event of no incoming message, for example marking the invoker as idle.
     * @param invoker the invoker object (preplaceded through)
     * @param session the receiving JMS Session
     */
    protected void noMessageReceived(Object invoker, Session session) {
    }

    /**
     * Fetch an appropriate Connection from the given JmsResourceHolder.
     * <p>This implementation accepts any JMS 1.1 Connection.
     * @param holder the JmsResourceHolder
     * @return an appropriate Connection fetched from the holder,
     * or {@code null} if none found
     */
    @Nullable
    protected Connection getConnection(JmsResourceHolder holder) {
        return holder.getConnection();
    }

    /**
     * Fetch an appropriate Session from the given JmsResourceHolder.
     * <p>This implementation accepts any JMS 1.1 Session.
     * @param holder the JmsResourceHolder
     * @return an appropriate Session fetched from the holder,
     * or {@code null} if none found
     */
    @Nullable
    protected Session getSession(JmsResourceHolder holder) {
        return holder.getSession();
    }

    /**
     * ResourceFactory implementation that delegates to this listener container's protected callback methods.
     */
    private clreplaced MessageListenerContainerResourceFactory implements ConnectionFactoryUtils.ResourceFactory {

        @Override
        @Nullable
        public Connection getConnection(JmsResourceHolder holder) {
            return AbstractPollingMessageListenerContainer.this.getConnection(holder);
        }

        @Override
        @Nullable
        public Session getSession(JmsResourceHolder holder) {
            return AbstractPollingMessageListenerContainer.this.getSession(holder);
        }

        @Override
        public Connection createConnection() throws JMSException {
            if (AbstractPollingMessageListenerContainer.this.sharedConnectionEnabled()) {
                Connection sharedCon = AbstractPollingMessageListenerContainer.this.getSharedConnection();
                return new SingleConnectionFactory(sharedCon).createConnection();
            } else {
                return AbstractPollingMessageListenerContainer.this.createConnection();
            }
        }

        @Override
        public Session createSession(Connection con) throws JMSException {
            return AbstractPollingMessageListenerContainer.this.createSession(con);
        }

        @Override
        public boolean isSynchedLocalTransactionAllowed() {
            return AbstractPollingMessageListenerContainer.this.isSessionTransacted();
        }
    }
}

19 Source : AbstractPollingMessageListenerContainer.java
with MIT License
from Vip-Augus

/**
 * Specify the Spring {@link org.springframework.transaction.PlatformTransactionManager}
 * to use for transactional wrapping of message reception plus listener execution.
 * <p>Default is none, not performing any transactional wrapping.
 * If specified, this will usually be a Spring
 * {@link org.springframework.transaction.jta.JtaTransactionManager} or one
 * of its subclreplacedes, in combination with a JTA-aware ConnectionFactory that
 * this message listener container obtains its Connections from.
 * <p><b>Note: Consider the use of local JMS transactions instead.</b>
 * Simply switch the {@link #setSessionTransacted "sessionTransacted"} flag
 * to "true" in order to use a locally transacted JMS Session for the entire
 * receive processing, including any Session operations performed by a
 * {@link SessionAwareMessageListener} (e.g. sending a response message). This
 * allows for fully synchronized Spring transactions based on local JMS
 * transactions, similar to what
 * {@link org.springframework.jms.connection.JmsTransactionManager} provides. Check
 * {@link AbstractMessageListenerContainer}'s javadoc for
 * a discussion of transaction choices and message redelivery scenarios.
 * @see #setSessionTransacted(boolean)
 * @see org.springframework.transaction.jta.JtaTransactionManager
 * @see org.springframework.jms.connection.JmsTransactionManager
 */
public void setTransactionManager(@Nullable PlatformTransactionManager transactionManager) {
    this.transactionManager = transactionManager;
}

19 Source : DefaultJmsListenerContainerFactory.java
with MIT License
from Vip-Augus

/**
 * @see DefaultMessageListenerContainer#setTransactionManager
 */
public void setTransactionManager(PlatformTransactionManager transactionManager) {
    this.transactionManager = transactionManager;
}

19 Source : TransactionAwareCacheDecoratorTests.java
with MIT License
from Vip-Augus

/**
 * @author Stephane Nicoll
 */
public clreplaced TransactionAwareCacheDecoratorTests {

    private final PlatformTransactionManager txManager = new CallCountingTransactionManager();

    @Test
    public void createWithNullTarget() {
        replacedertThatIllegalArgumentException().isThrownBy(() -> new TransactionAwareCacheDecorator(null));
    }

    @Test
    public void getTargetCache() {
        Cache target = new ConcurrentMapCache("testCache");
        TransactionAwareCacheDecorator cache = new TransactionAwareCacheDecorator(target);
        replacedertSame(target, cache.getTargetCache());
    }

    @Test
    public void regularOperationsOnTarget() {
        Cache target = new ConcurrentMapCache("testCache");
        Cache cache = new TransactionAwareCacheDecorator(target);
        replacedertEquals(target.getName(), cache.getName());
        replacedertEquals(target.getNativeCache(), cache.getNativeCache());
        Object key = new Object();
        target.put(key, "123");
        replacedertEquals("123", cache.get(key).get());
        replacedertEquals("123", cache.get(key, String.clreplaced));
        cache.clear();
        replacedertNull(target.get(key));
    }

    @Test
    public void putNonTransactional() {
        Cache target = new ConcurrentMapCache("testCache");
        Cache cache = new TransactionAwareCacheDecorator(target);
        Object key = new Object();
        cache.put(key, "123");
        replacedertEquals("123", target.get(key, String.clreplaced));
    }

    @Test
    public void putTransactional() {
        Cache target = new ConcurrentMapCache("testCache");
        Cache cache = new TransactionAwareCacheDecorator(target);
        TransactionStatus status = this.txManager.getTransaction(new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED));
        Object key = new Object();
        cache.put(key, "123");
        replacedertNull(target.get(key));
        this.txManager.commit(status);
        replacedertEquals("123", target.get(key, String.clreplaced));
    }

    @Test
    public void putIfAbsent() {
        // no transactional support for putIfAbsent
        Cache target = new ConcurrentMapCache("testCache");
        Cache cache = new TransactionAwareCacheDecorator(target);
        Object key = new Object();
        replacedertNull(cache.putIfAbsent(key, "123"));
        replacedertEquals("123", target.get(key, String.clreplaced));
        replacedertEquals("123", cache.putIfAbsent(key, "456").get());
        // unchanged
        replacedertEquals("123", target.get(key, String.clreplaced));
    }

    @Test
    public void evictNonTransactional() {
        Cache target = new ConcurrentMapCache("testCache");
        Cache cache = new TransactionAwareCacheDecorator(target);
        Object key = new Object();
        cache.put(key, "123");
        cache.evict(key);
        replacedertNull(target.get(key));
    }

    @Test
    public void evictTransactional() {
        Cache target = new ConcurrentMapCache("testCache");
        Cache cache = new TransactionAwareCacheDecorator(target);
        Object key = new Object();
        cache.put(key, "123");
        TransactionStatus status = this.txManager.getTransaction(new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED));
        cache.evict(key);
        replacedertEquals("123", target.get(key, String.clreplaced));
        this.txManager.commit(status);
        replacedertNull(target.get(key));
    }

    @Test
    public void clearNonTransactional() {
        Cache target = new ConcurrentMapCache("testCache");
        Cache cache = new TransactionAwareCacheDecorator(target);
        Object key = new Object();
        cache.put(key, "123");
        cache.clear();
        replacedertNull(target.get(key));
    }

    @Test
    public void clearTransactional() {
        Cache target = new ConcurrentMapCache("testCache");
        Cache cache = new TransactionAwareCacheDecorator(target);
        Object key = new Object();
        cache.put(key, "123");
        TransactionStatus status = this.txManager.getTransaction(new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED));
        cache.clear();
        replacedertEquals("123", target.get(key, String.clreplaced));
        this.txManager.commit(status);
        replacedertNull(target.get(key));
    }
}

19 Source : SchedulerAccessor.java
with MIT License
from Vip-Augus

/**
 * Set the transaction manager to be used for registering jobs and triggers
 * that are defined by this SchedulerFactoryBean. Default is none; setting
 * this only makes sense when specifying a DataSource for the Scheduler.
 */
public void setTransactionManager(PlatformTransactionManager transactionManager) {
    this.transactionManager = transactionManager;
}

19 Source : PlatformTransactionManagerAdapter.java
with Apache License 2.0
from teiid

public void setPlatformTransactionManager(PlatformTransactionManager platformTransactionManager) {
    this.platformTransactionManager = platformTransactionManager;
    if (this.platformTransactionManager instanceof DelegatingPlatformTransactionManager) {
        ((DelegatingPlatformTransactionManager) this.platformTransactionManager).setTransactionManagers(this.txnManagersForEachDataSource);
    }
}

19 Source : SpringJdbcConfig.java
with Apache License 2.0
from spring-avengers

@Bean
public TransactionTemplate transactionTemplate(@Autowired PlatformTransactionManager transactionManager) {
    return new TransactionTemplate(transactionManager);
}

19 Source : TransactionTemplate.java
with Apache License 2.0
from SourceHot

/**
 * Template clreplaced that simplifies programmatic transaction demarcation and transaction exception
 * handling.
 *
 * <p>The central method is {@link #execute}, supporting transactional code that
 * implements the {@link TransactionCallback} interface. This template handles the transaction
 * lifecycle and possible exceptions such that neither the TransactionCallback implementation nor
 * the calling code needs to explicitly handle transactions.
 *
 * <p>Typical usage: Allows for writing low-level data access objects that use
 * resources such as JDBC DataSources but are not transaction-aware themselves. Instead, they can
 * implicitly participate in transactions handled by higher-level application services utilizing
 * this clreplaced, making calls to the low-level services via an inner-clreplaced callback object.
 *
 * <p>Can be used within a service implementation via direct instantiation with
 * a transaction manager reference, or get prepared in an application context and preplaceded to services
 * as bean reference. Note: The transaction manager should always be configured as bean in the
 * application context: in the first case given to the service directly, in the second case given to
 * the prepared template.
 *
 * <p>Supports setting the propagation behavior and the isolation level by name,
 * for convenient configuration in context definitions.
 *
 * @author Juergen Hoeller
 * @see #execute
 * @see #setTransactionManager
 * @see org.springframework.transaction.PlatformTransactionManager
 * @since 17.03.2003
 */
@SuppressWarnings("serial")
public clreplaced TransactionTemplate extends DefaultTransactionDefinition implements TransactionOperations, InitializingBean {

    /**
     * Logger available to subclreplacedes.
     */
    protected final Log logger = LogFactory.getLog(getClreplaced());

    @Nullable
    private PlatformTransactionManager transactionManager;

    /**
     * Construct a new TransactionTemplate for bean usage.
     * <p>Note: The PlatformTransactionManager needs to be set before
     * any {@code execute} calls.
     *
     * @see #setTransactionManager
     */
    public TransactionTemplate() {
    }

    /**
     * Construct a new TransactionTemplate using the given transaction manager.
     *
     * @param transactionManager the transaction management strategy to be used
     */
    public TransactionTemplate(PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    /**
     * Construct a new TransactionTemplate using the given transaction manager, taking its default
     * settings from the given transaction definition.
     *
     * @param transactionManager    the transaction management strategy to be used
     * @param transactionDefinition the transaction definition to copy the default settings from.
     *                              Local properties can still be set to change values.
     */
    public TransactionTemplate(PlatformTransactionManager transactionManager, TransactionDefinition transactionDefinition) {
        super(transactionDefinition);
        this.transactionManager = transactionManager;
    }

    /**
     * Return the transaction management strategy to be used.
     */
    @Nullable
    public PlatformTransactionManager getTransactionManager() {
        return this.transactionManager;
    }

    /**
     * Set the transaction management strategy to be used.
     */
    public void setTransactionManager(@Nullable PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    @Override
    public void afterPropertiesSet() {
        if (this.transactionManager == null) {
            throw new IllegalArgumentException("Property 'transactionManager' is required");
        }
    }

    /**
     * 执行,做一个事务
     *
     * @param action the callback object that specifies the transactional action
     * @param <T>
     * @return
     * @throws TransactionException
     */
    @Override
    @Nullable
    public <T> T execute(TransactionCallback<T> action) throws TransactionException {
        replacedert.state(this.transactionManager != null, "No PlatformTransactionManager set");
        // 事务管理是否是 xxx接口
        if (this.transactionManager instanceof CallbackPreferringPlatformTransactionManager) {
            // 强转执行
            return ((CallbackPreferringPlatformTransactionManager) this.transactionManager).execute(this, action);
        } else {
            // 获取事务状态
            TransactionStatus status = this.transactionManager.getTransaction(this);
            // 返回结果
            T result;
            try {
                // 事务回调执行
                result = action.doInTransaction(status);
            } catch (RuntimeException | Error ex) {
                // Transactional code threw application exception -> rollback
                // 回滚异常
                rollbackOnException(status, ex);
                throw ex;
            } catch (Throwable ex) {
                // Transactional code threw unexpected exception -> rollback
                // 回滚异常
                rollbackOnException(status, ex);
                throw new UndeclaredThrowableException(ex, "TransactionCallback threw undeclared checked exception");
            }
            // 提交
            this.transactionManager.commit(status);
            return result;
        }
    }

    /**
     * Perform a rollback, handling rollback exceptions properly.
     *
     * @param status object representing the transaction
     * @param ex     the thrown application exception or error
     * @throws TransactionException in case of a rollback error
     */
    private void rollbackOnException(TransactionStatus status, Throwable ex) throws TransactionException {
        replacedert.state(this.transactionManager != null, "No PlatformTransactionManager set");
        logger.debug("Initiating transaction rollback on application exception", ex);
        try {
            this.transactionManager.rollback(status);
        } catch (TransactionSystemException ex2) {
            logger.error("Application exception overridden by rollback exception", ex);
            ex2.initApplicationException(ex);
            throw ex2;
        } catch (RuntimeException | Error ex2) {
            logger.error("Application exception overridden by rollback exception", ex);
            throw ex2;
        }
    }

    @Override
    public boolean equals(@Nullable Object other) {
        return (this == other || (super.equals(other) && (!(other instanceof TransactionTemplate) || getTransactionManager() == ((TransactionTemplate) other).getTransactionManager())));
    }
}

19 Source : TransactionAspectSupport.java
with Apache License 2.0
from SourceHot

/**
 * Prepare a TransactionInfo for the given attribute and status object.
 *
 * @param txAttr                  the TransactionAttribute (may be {@code null})
 * @param joinpointIdentification the fully qualified method name (used for monitoring and
 *                                logging purposes)
 * @param status                  the TransactionStatus for the current transaction
 * @return the prepared TransactionInfo object
 */
protected TransactionInfo prepareTransactionInfo(@Nullable PlatformTransactionManager tm, @Nullable TransactionAttribute txAttr, String joinpointIdentification, @Nullable TransactionStatus status) {
    // 初始化
    TransactionInfo txInfo = new TransactionInfo(tm, txAttr, joinpointIdentification);
    if (txAttr != null) {
        // We need a transaction for this method...
        if (logger.isTraceEnabled()) {
            logger.trace("Getting transaction for [" + txInfo.getJoinpointIdentification() + "]");
        }
        // The transaction manager will flag an error if an incompatible tx already exists.
        txInfo.newTransactionStatus(status);
    } else {
        // The TransactionInfo.hasTransaction() method will return false. We created it only
        // to preserve the integrity of the ThreadLocal stack maintained in this clreplaced.
        if (logger.isTraceEnabled()) {
            logger.trace("No need to create transaction for [" + joinpointIdentification + "]: This method is not transactional.");
        }
    }
    // We always bind the TransactionInfo to the thread, even if we didn't create
    // a new transaction here. This guarantees that the TransactionInfo stack
    // will be managed correctly even if no transaction was created by this aspect.
    // 和线程绑定
    txInfo.bindToThread();
    return txInfo;
}

19 Source : AbstractEntityManagerFactoryIntegrationTests.java
with Apache License 2.0
from SourceHot

/**
 * @author Rod Johnson
 * @author Juergen Hoeller
 */
public abstract clreplaced AbstractEnreplacedyManagerFactoryIntegrationTests {

    protected static final String[] ECLIPSELINK_CONFIG_LOCATIONS = new String[] { "/org/springframework/orm/jpa/eclipselink/eclipselink-manager.xml", "/org/springframework/orm/jpa/memdb.xml", "/org/springframework/orm/jpa/inject.xml" };

    private static ConfigurableApplicationContext applicationContext;

    protected EnreplacedyManagerFactory enreplacedyManagerFactory;

    protected EnreplacedyManager sharedEnreplacedyManager;

    protected PlatformTransactionManager transactionManager;

    protected DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();

    protected TransactionStatus transactionStatus;

    private boolean complete = false;

    protected JdbcTemplate jdbcTemplate;

    private boolean zappedTables = false;

    @Autowired
    public void setEnreplacedyManagerFactory(EnreplacedyManagerFactory enreplacedyManagerFactory) {
        this.enreplacedyManagerFactory = enreplacedyManagerFactory;
        this.sharedEnreplacedyManager = SharedEnreplacedyManagerCreator.createSharedEnreplacedyManager(this.enreplacedyManagerFactory);
    }

    @Autowired
    public void setTransactionManager(PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @BeforeEach
    public void setup() {
        if (applicationContext == null) {
            applicationContext = new ClreplacedPathXmlApplicationContext(getConfigLocations());
        }
        applicationContext.getAutowireCapableBeanFactory().autowireBean(this);
        if (this.transactionManager != null && this.transactionDefinition != null) {
            startNewTransaction();
        }
    }

    protected String[] getConfigLocations() {
        return ECLIPSELINK_CONFIG_LOCATIONS;
    }

    @AfterEach
    public void cleanup() {
        if (this.transactionStatus != null && !this.transactionStatus.isCompleted()) {
            endTransaction();
        }
        replacedertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue();
        replacedertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse();
        replacedertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse();
        replacedertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
    }

    @AfterAll
    public static void closeContext() {
        if (applicationContext != null) {
            applicationContext.close();
            applicationContext = null;
        }
    }

    protected EnreplacedyManager createContainerManagedEnreplacedyManager() {
        return ExtendedEnreplacedyManagerCreator.createContainerManagedEnreplacedyManager(this.enreplacedyManagerFactory);
    }

    protected void setComplete() {
        if (this.transactionManager == null) {
            throw new IllegalStateException("No transaction manager set");
        }
        if (this.zappedTables) {
            throw new IllegalStateException("Cannot set complete after deleting tables");
        }
        this.complete = true;
    }

    protected void endTransaction() {
        final boolean commit = this.complete;
        if (this.transactionStatus != null) {
            try {
                if (commit) {
                    this.transactionManager.commit(this.transactionStatus);
                } else {
                    this.transactionManager.rollback(this.transactionStatus);
                }
            } finally {
                this.transactionStatus = null;
            }
        }
    }

    protected void startNewTransaction() throws TransactionException {
        this.transactionStatus = this.transactionManager.getTransaction(this.transactionDefinition);
    }

    protected void deleteFromTables(String... tableNames) {
        for (String tableName : tableNames) {
            this.jdbcTemplate.update("DELETE FROM " + tableName);
        }
        this.zappedTables = true;
    }

    protected int countRowsInTable(EnreplacedyManager em, String tableName) {
        Query query = em.createNativeQuery("SELECT COUNT(0) FROM " + tableName);
        return ((Number) query.getSingleResult()).intValue();
    }

    protected int countRowsInTable(String tableName) {
        return this.jdbcTemplate.queryForObject("SELECT COUNT(0) FROM " + tableName, Integer.clreplaced);
    }

    protected void executeSqlScript(String sqlResourcePath) throws DataAccessException {
        Resource resource = applicationContext.getResource(sqlResourcePath);
        new ResourceDatabasePopulator(resource).execute(this.jdbcTemplate.getDataSource());
    }
}

19 Source : JBPMPersistence.java
with Apache License 2.0
from redhat-cop

/**
 * Overrides existing jBPM Datasource simply for @Primary on the datasource..
 * This shall be fixed soon..
 */
@Configuration
public clreplaced JBPMPersistence extends JBPMAutoConfiguration {

    private ApplicationContext applicationContext;

    private PlatformTransactionManager transactionManager;

    public JBPMPersistence(PlatformTransactionManager transactionManager, JBPMProperties properties, ApplicationContext applicationContext) {
        super(transactionManager, properties, applicationContext);
        this.applicationContext = applicationContext;
    }

    private static final String CLreplaced_RESOURCE_PATTERN = "/**/*.clreplaced";

    private static final String PACKAGE_INFO_SUFFIX = ".package-info";

    protected static final String PERSISTENCE_UNIT_NAME = "org.jbpm.domain";

    protected static final String PERSISTENCE_XML_LOCATION = "clreplacedpath:/META-INF/jbpm-persistence.xml";

    // @Autowired
    // @Qualifier("auditEnreplacedyManager")
    // EnreplacedyManagerFactory auditEMF;
    /**
     * Define jBPM EMF as Primary
     * Overriding Clreplaced: https://github.com/kiegroup/droolsjbpm-integration/blob/master/kie-spring-boot/kie-spring-boot-autoconfiguration/jbpm-spring-boot-autoconfiguration/src/main/java/org/jbpm/springboot/autoconfigure/JBPMAutoConfiguration.java#L194
     * @param dataSource
     * @param jpaProperties
     * @return
     */
    @Override
    @Bean
    // Allows to specify additional DS's
    @Primary
    @ConditionalOnMissingBean(name = "enreplacedyManagerFactory")
    public LocalContainerEnreplacedyManagerFactoryBean enreplacedyManagerFactory(DataSource dataSource, JpaProperties jpaProperties) {
        LocalContainerEnreplacedyManagerFactoryBean factoryBean = new LocalContainerEnreplacedyManagerFactoryBean();
        factoryBean.setPersistenceUnitName(PERSISTENCE_UNIT_NAME);
        factoryBean.setPersistenceXmlLocation(PERSISTENCE_XML_LOCATION);
        factoryBean.setJtaDataSource(dataSource);
        factoryBean.setJpaPropertyMap(jpaProperties.getProperties());
        HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        adapter.setPrepareConnection(false);
        factoryBean.setJpaVendorAdapter(adapter);
        String packagesToScan = jpaProperties.getProperties().get("enreplacedy-scan-packages");
        if (packagesToScan != null) {
            factoryBean.setPersistenceUnitPostProcessors(new PersistenceUnitPostProcessor() {

                @Override
                public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui) {
                    Set<TypeFilter> enreplacedyTypeFilters = new LinkedHashSet<TypeFilter>(3);
                    enreplacedyTypeFilters.add(new AnnotationTypeFilter(Enreplacedy.clreplaced, false));
                    enreplacedyTypeFilters.add(new AnnotationTypeFilter(Embeddable.clreplaced, false));
                    enreplacedyTypeFilters.add(new AnnotationTypeFilter(MappedSuperclreplaced.clreplaced, false));
                    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
                    if (packagesToScan != null) {
                        for (String pkg : packagesToScan.split(",")) {
                            try {
                                String pattern = ResourcePatternResolver.CLreplacedPATH_ALL_URL_PREFIX + ClreplacedUtils.convertClreplacedNameToResourcePath(pkg) + CLreplaced_RESOURCE_PATTERN;
                                Resource[] resources = resourcePatternResolver.getResources(pattern);
                                MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
                                for (Resource resource : resources) {
                                    if (resource.isReadable()) {
                                        MetadataReader reader = readerFactory.getMetadataReader(resource);
                                        String clreplacedName = reader.getClreplacedMetadata().getClreplacedName();
                                        if (matchesFilter(reader, readerFactory, enreplacedyTypeFilters)) {
                                            pui.addManagedClreplacedName(clreplacedName);
                                        } else if (clreplacedName.endsWith(PACKAGE_INFO_SUFFIX)) {
                                            pui.addManagedPackage(clreplacedName.substring(0, clreplacedName.length() - PACKAGE_INFO_SUFFIX.length()));
                                        }
                                    }
                                }
                            } catch (IOException ex) {
                                throw new PersistenceException("Failed to scan clreplacedpath for unlisted enreplacedy clreplacedes", ex);
                            }
                        }
                    }
                }

                private boolean matchesFilter(MetadataReader reader, MetadataReaderFactory readerFactory, Set<TypeFilter> enreplacedyTypeFilters) throws IOException {
                    for (TypeFilter filter : enreplacedyTypeFilters) {
                        if (filter.match(reader, readerFactory)) {
                            return true;
                        }
                    }
                    return false;
                }
            });
        }
        return factoryBean;
    }
}

19 Source : DefaultGetExtensionSuiteDatasource.java
with Apache License 2.0
from QNJR-GROUP

public clreplaced DefaultGetExtensionSuiteDatasource implements GetExtentionSuiteDatabase {

    public DefaultGetExtensionSuiteDatasource(DataSource dataSource, PlatformTransactionManager transManager) {
        super();
        this.dataSource = dataSource;
        this.transManager = transManager;
    }

    private DataSource dataSource;

    private PlatformTransactionManager transManager;

    @Override
    public DataSource getDataSource() {
        return dataSource;
    }

    @Override
    public PlatformTransactionManager getPlatformTransactionManager() {
        return transManager;
    }
}

19 Source : SingleDataSourceSelector.java
with Apache License 2.0
from QNJR-GROUP

public clreplaced SingleDataSourceSelector implements DataSourceSelector {

    private DataSource dataSource;

    private PlatformTransactionManager transactionManager;

    public SingleDataSourceSelector(DataSource dataSource, PlatformTransactionManager transactionManager) {
        super();
        this.dataSource = dataSource;
        this.transactionManager = transactionManager;
    }

    @Override
    public DataSource selectDataSource(String appId, String busCode, long trxId) {
        return dataSource;
    }

    @Override
    public PlatformTransactionManager selectTransactionManager(String appId, String busCode, long trxId) {
        return transactionManager;
    }

    @Override
    public DataSource selectDataSource(String appId, String busCode, EasyTransRequest<?, ?> request) {
        return dataSource;
    }

    @Override
    public PlatformTransactionManager selectTransactionManager(String appId, String busCode, EasyTransRequest<?, ?> request) {
        return transactionManager;
    }
}

19 Source : TransactionTemplate.java
with Apache License 2.0
from q920447939

/**
 * Template clreplaced that simplifies programmatic transaction demarcation and
 * transaction exception handling.
 *
 * <p>The central method is {@link #execute}, supporting transactional code that
 * implements the {@link TransactionCallback} interface. This template handles
 * the transaction lifecycle and possible exceptions such that neither the
 * TransactionCallback implementation nor the calling code needs to explicitly
 * handle transactions.
 *
 * <p>Typical usage: Allows for writing low-level data access objects that use
 * resources such as JDBC DataSources but are not transaction-aware themselves.
 * Instead, they can implicitly participate in transactions handled by higher-level
 * application services utilizing this clreplaced, making calls to the low-level
 * services via an inner-clreplaced callback object.
 *
 * <p>Can be used within a service implementation via direct instantiation with
 * a transaction manager reference, or get prepared in an application context
 * and preplaceded to services as bean reference. Note: The transaction manager should
 * always be configured as bean in the application context: in the first case given
 * to the service directly, in the second case given to the prepared template.
 *
 * <p>Supports setting the propagation behavior and the isolation level by name,
 * for convenient configuration in context definitions.
 *
 * @author Juergen Hoeller
 * @since 17.03.2003
 * @see #execute
 * @see #setTransactionManager
 * @see org.springframework.transaction.PlatformTransactionManager
 */
@SuppressWarnings("serial")
public clreplaced TransactionTemplate extends DefaultTransactionDefinition implements TransactionOperations, InitializingBean {

    /**
     * Logger available to subclreplacedes.
     */
    protected final Log logger = LogFactory.getLog(getClreplaced());

    @Nullable
    private PlatformTransactionManager transactionManager;

    /**
     * Construct a new TransactionTemplate for bean usage.
     * <p>Note: The PlatformTransactionManager needs to be set before
     * any {@code execute} calls.
     * @see #setTransactionManager
     */
    public TransactionTemplate() {
    }

    /**
     * Construct a new TransactionTemplate using the given transaction manager.
     * @param transactionManager the transaction management strategy to be used
     */
    public TransactionTemplate(PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    /**
     * Construct a new TransactionTemplate using the given transaction manager,
     * taking its default settings from the given transaction definition.
     * @param transactionManager the transaction management strategy to be used
     * @param transactionDefinition the transaction definition to copy the
     * default settings from. Local properties can still be set to change values.
     */
    public TransactionTemplate(PlatformTransactionManager transactionManager, TransactionDefinition transactionDefinition) {
        super(transactionDefinition);
        this.transactionManager = transactionManager;
    }

    /**
     * Set the transaction management strategy to be used.
     */
    public void setTransactionManager(@Nullable PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    /**
     * Return the transaction management strategy to be used.
     */
    @Nullable
    public PlatformTransactionManager getTransactionManager() {
        return this.transactionManager;
    }

    @Override
    public void afterPropertiesSet() {
        if (this.transactionManager == null) {
            throw new IllegalArgumentException("Property 'transactionManager' is required");
        }
    }

    @Override
    @Nullable
    public <T> T execute(TransactionCallback<T> action) throws TransactionException {
        replacedert.state(this.transactionManager != null, "No PlatformTransactionManager set");
        if (this.transactionManager instanceof CallbackPreferringPlatformTransactionManager) {
            return ((CallbackPreferringPlatformTransactionManager) this.transactionManager).execute(this, action);
        } else {
            TransactionStatus status = this.transactionManager.getTransaction(this);
            T result;
            try {
                result = action.doInTransaction(status);
            } catch (RuntimeException | Error ex) {
                // Transactional code threw application exception -> rollback
                rollbackOnException(status, ex);
                throw ex;
            } catch (Throwable ex) {
                // Transactional code threw unexpected exception -> rollback
                rollbackOnException(status, ex);
                throw new UndeclaredThrowableException(ex, "TransactionCallback threw undeclared checked exception");
            }
            this.transactionManager.commit(status);
            return result;
        }
    }

    /**
     * Perform a rollback, handling rollback exceptions properly.
     * @param status object representing the transaction
     * @param ex the thrown application exception or error
     * @throws TransactionException in case of a rollback error
     */
    private void rollbackOnException(TransactionStatus status, Throwable ex) throws TransactionException {
        replacedert.state(this.transactionManager != null, "No PlatformTransactionManager set");
        logger.debug("Initiating transaction rollback on application exception", ex);
        try {
            this.transactionManager.rollback(status);
        } catch (TransactionSystemException ex2) {
            logger.error("Application exception overridden by rollback exception", ex);
            ex2.initApplicationException(ex);
            throw ex2;
        } catch (RuntimeException | Error ex2) {
            logger.error("Application exception overridden by rollback exception", ex);
            throw ex2;
        }
    }

    @Override
    public boolean equals(@Nullable Object other) {
        return (this == other || (super.equals(other) && (!(other instanceof TransactionTemplate) || getTransactionManager() == ((TransactionTemplate) other).getTransactionManager())));
    }
}

19 Source : TransactionService.java
with GNU Affero General Public License v3.0
from progilone

/**
 * Service permettant de gérer des transactions à la main. Deux types de transactions sont possibles :
 * <ul>
 * <li>Stateless : ce type est destiné aux imports de mreplacede. Les enreplacedées hibernate ne sont pas attachées à la session
 * (attention aux LazyInitialisationException !) ce qui permet de gagner un temps phénoménal dans les imports.</li>
 * <li>Normal : ce type est destiné à tous les autres cas...</li>
 * </ul>
 * Il est possible de mixer les transactions (par exemple démarrer une stateless, puis faire une normale pour un
 * traitement particulier et continuer la stateless ensuite)
 *
 * @author David
 */
@Service
public clreplaced TransactionService {

    private final PlatformTransactionManager txManager;

    private final LocalContainerEnreplacedyManagerFactoryBean enreplacedyManagerFactory;

    private final EnreplacedyManager enreplacedyManager;

    public TransactionService(final PlatformTransactionManager txManager, final LocalContainerEnreplacedyManagerFactoryBean enreplacedyManagerFactory, final EnreplacedyManager enreplacedyManager) {
        this.txManager = txManager;
        this.enreplacedyManagerFactory = enreplacedyManagerFactory;
        this.enreplacedyManager = enreplacedyManager;
    }

    public TransactionStatus startTransaction(final boolean readonly) {
        final DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        def.setReadOnly(readonly);
        return txManager.getTransaction(def);
    }

    public void commitTransaction(final TransactionStatus status) {
        txManager.commit(status);
        enreplacedyManager.clear();
    }

    public void rollbackTransaction(final TransactionStatus status) {
        if (!status.isCompleted()) {
            txManager.rollback(status);
        }
    }

    public void flushSession(final TransactionStatus status) {
        status.flush();
        enreplacedyManager.clear();
    }

    /**
     * Crée une nouvelle session stateless et démarre une nouvelle transaction. Attention à bien fermer la session après
     * l'avoir utilisée !
     *
     * @return StatelessSession
     */
    public StatelessSession startStatelessTransaction() {
        return startStatelessTransaction(null);
    }

    /**
     * Utilise la session preplacedée en paramètre et démarre une nouvelle transaction. Si la session est <code>null</code>,
     * une nouvelle est créee. Attention à bien fermer la session après l'avoir utilisée !
     *
     * @param session
     * @return StatelessSession
     */
    public StatelessSession startStatelessTransaction(StatelessSession session) {
        if (session == null || !session.isOpen()) {
            session = ((SessionFactory) enreplacedyManagerFactory.getNativeEnreplacedyManagerFactory()).openStatelessSession();
        }
        session.beginTransaction();
        return session;
    }

    /**
     * Commite la transaction contenue dans la session.
     *
     * @param session
     */
    public void commitStatelessTransaction(final StatelessSession session) {
        session.getTransaction().commit();
    }

    /**
     * Rollback la transaction contenue dans la session.
     *
     * @param session
     */
    public void rollbackStatelessTransaction(final StatelessSession session) {
        if (session.getTransaction().getStatus() == org.hibernate.resource.transaction.spi.TransactionStatus.ACTIVE) {
            session.getTransaction().rollback();
        }
    }

    /**
     * Ferme la session
     *
     * @param session
     */
    public void closeStatelessSession(final StatelessSession session) {
        session.close();
    }

    /**
     * Exécute une méthode dans une nouvelle transaction
     */
    @Transactional(value = Transactional.TxType.REQUIRES_NEW, rollbackOn = Exception.clreplaced)
    public void executeInNewTransaction(final Runnable runnable) {
        runnable.run();
    }

    /**
     * Exécute une méthode dans une nouvelle transaction non readonly
     */
    @Transactional(value = Transactional.TxType.REQUIRES_NEW, rollbackOn = Exception.clreplaced)
    public <T> T executeInNewTransactionWithReturn(final RunnableWithReturn<T> runnable) {
        return runnable.run();
    }

    /**
     * Exécute une méthode dans une nouvelle transaction non readonly
     */
    @Transactional(value = Transactional.TxType.REQUIRES_NEW, rollbackOn = Exception.clreplaced)
    public <T> T executeInNewTransactionWithReturnAndException(final RunnableWithReturnAndException<T> runnable) throws Exception {
        return runnable.run();
    }

    /**
     * Exécute une méthode dans une nouvelle transaction asynchrone
     */
    @Async
    @Transactional(value = Transactional.TxType.REQUIRES_NEW, rollbackOn = Exception.clreplaced)
    public void executeInNewTransactionAsync(final Runnable runnable) {
        executeInNewTransaction(runnable);
    }

    @FunctionalInterface
    public interface RunnableWithReturn<T> {

        public abstract T run();
    }

    @FunctionalInterface
    public interface RunnableWithReturnAndException<T> {

        public abstract T run() throws Exception;
    }
}

19 Source : TransactionTemplateFactory.java
with Apache License 2.0
from penggle

/**
 * @author pengpeng
 * @version 1.0
 * @date 2020/9/22 8:39
 */
public clreplaced TransactionTemplateFactory {

    private final PlatformTransactionManager platformTransactionManager;

    public TransactionTemplateFactory(PlatformTransactionManager platformTransactionManager) {
        this.platformTransactionManager = platformTransactionManager;
    }

    public TransactionTemplate createTransactionTemplate(int propagation) {
        return createTransactionTemplate(propagation, false);
    }

    public TransactionTemplate createTransactionTemplate(int propagation, boolean readOnly) {
        TransactionTemplate transactionTemplate = new TransactionTemplate(platformTransactionManager);
        transactionTemplate.setPropagationBehavior(propagation);
        transactionTemplate.setReadOnly(readOnly);
        return transactionTemplate;
    }
}

See More Examples