<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JEE &#8211; Pauls Blog</title>
	<atom:link href="https://sterl.org/tag/jee/feed/" rel="self" type="application/rss+xml" />
	<link>https://sterl.org</link>
	<description></description>
	<lastBuildDate>Mon, 04 Jul 2022 08:57:04 +0000</lastBuildDate>
	<language>de</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>
	<item>
		<title>Quartz integration in JEE</title>
		<link>https://sterl.org/2019/09/quartz-scheduler-integration-in-java-jee/</link>
					<comments>https://sterl.org/2019/09/quartz-scheduler-integration-in-java-jee/#comments</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Sat, 21 Sep 2019 12:24:10 +0000</pubDate>
				<category><![CDATA[Quartz]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[container]]></category>
		<category><![CDATA[cron]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[Job]]></category>
		<category><![CDATA[payara]]></category>
		<category><![CDATA[quartz-scheduler]]></category>
		<category><![CDATA[scheduler]]></category>
		<category><![CDATA[timer]]></category>
		<category><![CDATA[Wildfly]]></category>
		<guid isPermaLink="false">http://sterl.org/?p=378</guid>

					<description><![CDATA[Nowadays everybody talks about cloud and Microservices. The JEE container isn't that sexy anymore. With microprofile.io the JEE world started to move into the direction of a more lightweight structure. We should also mention docker and friends which changed the way we deploy and run applications now. ]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Why Quartz? <span class="badge badge-pill badge-primary">motivation</span></h2>



<p>Nowadays everybody talks about cloud and Microservices. The JEE container isn&#8217;t that sexy anymore. With <a rel="noreferrer noopener" aria-label="microprofile.io (öffnet in neuem Tab)" href="https://microprofile.io" target="_blank">microprofile.io</a> the JEE world started to move into the direction of a more lightweight structure. We should also mention docker and friends which changed the way we deploy and run applications now. </p>



<p>Long story short we have to keep in mind that the JEE timer depends on the admin server. Clustered timer just won&#8217;t really work anymore. Not to mention that the normal timers in JEE are pretty limited in their feature set. Even simple <em>job triggers</em> aren&#8217;t possible out of the box.</p>



<p><a href="https://github.com/sterlp/jee-quartz-integration">Bring me to the code.</a></p>



<h2 class="wp-block-heading">Steps for the integration</h2>



<ol class="wp-block-list"><li>Configure <a rel="noreferrer noopener" aria-label="Quartz Scheduler (öffnet in neuem Tab)" href="http://www.quartz-scheduler.org" target="_blank">Quartz Scheduler</a></li><li>Configure CDI Job Factory</li><li>Register our timers</li></ol>



<div class="bs-callout bs-callout-info">
<strong>Note:</strong> If you are already using Deltaspike you might want to use directly the <a href="https://deltaspike.apache.org/documentation/scheduler.html">scheduler integration</a> provided by it.
</div>



<h2 class="wp-block-heading">Configure Quartz Scheduler</h2>



<h3 class="wp-block-heading">Select the right job store</h3>



<p>In general, we have several ways of integration, going through the documentation we will see, that we have to choose between:</p>



<ul class="wp-block-list"><li><a rel="noreferrer noopener" aria-label="JobStoreCMT (öffnet in neuem Tab)" href="http://www.quartz-scheduler.org/documentation/2.4.0-SNAPSHOT/configuration.html#configuration-of-jdbc-jobstorecmt-jdbc-with-jta-container-managed-transactions" target="_blank">JobStoreCMT</a></li><li><a href="http://www.quartz-scheduler.org/documentation/2.4.0-SNAPSHOT/configuration.html#configuration-of-terracottajobstore-clustering-without-a-database" target="_blank" rel="noreferrer noopener" aria-label="TerracottaJobStore (öffnet in neuem Tab)">TerracottaJobStore</a></li></ul>



<p>We will focus for now on a job store using a normal database. We cannot really choose the <a rel="noreferrer noopener" aria-label="JobStoreTX  (öffnet in neuem Tab)" href="http://www.quartz-scheduler.org/documentation/2.4.0-SNAPSHOT/configuration.html#configuration-of-jdbc-jobstoretx-store-jobs-and-triggers-in-a-database-via-jdbc" target="_blank">JobStoreTX </a>as it wouldn&#8217;t join our transaction creating new triggers etc. Means if we accept during a REST call a command on our server, for which we also want to create a quartz trigger which does later on the heavy lifting, we would lose the ability to rollback the trigger and the modification of our data in one logical step. We might end up reverting all changes on the data, but still creating the trigger which e.g. won&#8217;t find the entities we created or modified for it.</p>



<p>For unit testing the <a rel="noreferrer noopener" aria-label="RamJobStore  (öffnet in neuem Tab)" href="http://www.quartz-scheduler.org/documentation/2.4.0-SNAPSHOT/configuration.html#configuration-of-ramjobstore-store-jobs-and-triggers-in-memory" target="_blank">RamJobStore </a>is sufficient. Luckily the default, if we don&#8217;t specify anything we will get it anyway.</p>



<h3 class="wp-block-heading">Configure JobStoreCMT</h3>



<p>The  CMT job store requires two DB connection pools. One will join our application transaction, means we can just simply provide the application data source.</p>



<p>The second connection pool has to be standalone, which means it shouldn&#8217;t join the transaction of the first pool. We can now either create a pool and disable the connection:</p>



<figure class="wp-block-image"><img fetchpriority="high" decoding="async" width="760" height="159" src="http://sterl.org/wp-content/uploads/2019/09/non-transactional-connection-payara.png" alt="" class="wp-image-484" srcset="https://sterl.org/wp-content/uploads/2019/09/non-transactional-connection-payara.png 760w, https://sterl.org/wp-content/uploads/2019/09/non-transactional-connection-payara-300x63.png 300w" sizes="(max-width: 760px) 100vw, 760px" /><figcaption>JDBC Connection Pool non-transactional</figcaption></figure>



<p>or create a non-container managed pool. Which wouldn&#8217;t be that nice but possible.</p>



<h4 class="wp-block-heading">ConnectionProvider</h4>



<p>Nevertheless, we have to bridge the JEE world to the Quartz world using a small class implementing the <code>ConnectionProvider</code>:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
@AllArgsConstructor
public class SimpleConnectionProvider implements ConnectionProvider {
    @NonNull
    private final DataSource dataSource;
    @Override
    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
    @Override
    public void shutdown() {
    }
    @Override
    public void initialize() {
    }
}
</pre></div>


<h4 class="wp-block-heading">ThreadPool</h4>



<p>Quartz comes with its own code to manage threads. Like with the database connection we have also to tell quartz to use the managed executor service here. Furthermore, quartz allows to limit the threads.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">public class SimpleQuartzJeeThreadPool implements ThreadPool {
    private static final Logger LOG = LoggerFactory.getLogger(SimpleQuartzJeeThreadPool.class);

    private final ManagedExecutorService executorService;
    private final List&lt;WeakReference&lt;Future&lt;?&gt;&gt;&gt; tasks = Collections.synchronizedList(new ArrayList&lt;&gt;());
    /** the max pool size, could also be the max size of the custom executor services created */
    private final int poolSize;
    private boolean shutdown = false;

    public SimpleQuartzJeeThreadPool(ManagedExecutorService executorService, int poolSize) {
        this.executorService = executorService;
        this.poolSize = poolSize;
        Objects.requireNonNull(this.executorService, &quot;ManagedExecutorService cannot be null.&quot;);
    }
 
    @Override
    public boolean runInThread(Runnable runnable) {
        if (shutdown) return false;
        try {
            tasks.add(new WeakReference&lt;&gt;(executorService.submit(runnable)));
            return true;
        } catch (RejectedExecutionException e) {
            LOG.info(&quot;runInThread was rejected, the pool capacitiy is exceeded! {}&quot;, e.getMessage());
            return false;
        }
    }

    @Override
    public int blockForAvailableThreads() {
        if (shutdown) return -1;
        try {
            // check if we have a thread available again and block for quartz // and purge
            this.executorService.submit(this::purge).get();

            return poolSize - tasks.size();
        } catch (Exception e) {
            LOG.warn(&quot;blockForAvailableThreads failed to pruge queue!&quot;, e);
            return poolSize - tasks.size();
        }
    }
  
    /**
     * Removes all monitored jobs and returns the removed count.
     * @return the removed jobn count
     */
    public int purge() {
        int removed = 0;
        if (!tasks.isEmpty()) {   
            List&lt;WeakReference&lt;Future&lt;?&gt;&gt;&gt; doneJobs = tasks.stream().filter(e -&gt; e.isEnqueued() || e.get() == null || e.get().isDone())
                    .collect(Collectors.toList());

            removed = doneJobs.size();
            this.tasks.removeAll(doneJobs);
            doneJobs.clear();
        }
        return removed;
    }

    @Override
    public void initialize() {
    }
    @Override
    public void shutdown(boolean waitForJobsToComplete) {
        this.shutdown = true;
    }
    @Override
    public int getPoolSize() {
        return poolSize;
    }
    @Override
    public void setInstanceId(String schedInstId) {
    }
    @Override
    public void setInstanceName(String schedName) {
    }
}</pre></div>



<div class="bs-callout bs-callout-info"><strong>Note:</strong>
The executor created for quartz shouldn&#8217;t have any queue capacity, as quartz manages the queue.
</div>



<h4 class="wp-block-heading">Put it together</h4>



<p>Which leads us to the following configuration</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">@Startup
@Singleton
public class TimerConfiguration {
    // this data source should be non transactional in the container
    private static final String QUARTZ_DS = &quot;jdbc/quartz-datasource&quot;;
    @Resource(lookup = QUARTZ_DS)
    private DataSource quartzDataSource;
    // the default application datasource
    private static final String APP_DS = &quot;jdbc/app-datasource&quot;;
    @Resource(lookup = APP_DS)
    private DataSource appDataSource;
    
    @Inject InjectionJobFactory jobFactory;
	// executor service for our jobs to quartz
    @Resource(name = &quot;concurrent/quartz-executor&quot;)
    private ManagedExecutorService executorService;

    private Scheduler scheduler;
    
    @PostConstruct
    public void start() {
        try {
            // Get scheduler and start it
            final DirectSchedulerFactory schedulerFactory = DirectSchedulerFactory.getInstance();
			// provide the datasources            
            DBConnectionManager.getInstance()
                    .addConnectionProvider(APP_DS, new SimpleConnectionProvider(appDataSource));
            DBConnectionManager.getInstance()
                    .addConnectionProvider(QUARTZ_DS, new SimpleConnectionProvider(quartzDataSource));
            
            JobStoreCMT jobStore = new JobStoreCMT();
            jobStore.setInstanceName(&quot;quartz-job-example-store&quot;);
            jobStore.setDataSource(APP_DS);
            jobStore.setNonManagedTXDataSource(QUARTZ_DS);
            // use the JEE executor service
            jobStore.setThreadExecutor(new ThreadExecutor() {
                @Override
                public void execute(Thread thread) {
                    executorService.execute(thread);
                }
                @Override
                public void initialize() {
                }
            });
            jobStore.setIsClustered(true);
            jobStore.setDriverDelegateClass(&quot;org.quartz.impl.jdbcjobstore.PostgreSQLDelegate&quot;);
            // note: the id matters as it defines if the times is seens as an own node ...
            schedulerFactory.createScheduler(&quot;JEE-QUARTZ&quot;, &quot;JEE-QUARTZ-ID&quot;, new SimpleQuartzJeeThreadPool(executorService, 20), jobStore);
            
            scheduler = schedulerFactory.getScheduler(&quot;JEE-QUARTZ&quot;);

            // Use the CDI managed job factory
            scheduler.setJobFactory(jobFactory);

            // Start scheduler
            scheduler.start();

        } catch (Exception e) {
            throw new RuntimeException(&quot;Failed to configure and start quartz.&quot;, e);
        }
    }</pre></div>



<div class="bs-callout bs-callout-info"><strong>Note:</strong>
The scheduler provides a way to set the ID of a quartz timer. If the ID is the same between two nodes they will not balance the load between each other. Make sure each node has an own ID.
</div>



<h2 class="wp-block-heading">Configure CDI Job Factory</h2>



<p>The default behavior of  Quartz would be to create a new instance of the class we register as a job. In most cases, this is not what we want. Usually, we want to use our CDI beans or JEE EJBs, for the spring guys the spring beans. As so we have to tell Quartz somehow how to find our beans.</p>



<h3 class="wp-block-heading">Injection JobFactory</h3>



<p>The easiest and most clean way is to provide an adapter to our CDI world. We just inject all classes which implement the Job interface, using it to find the right one based on the job detail we define during the job registration.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">@ApplicationScoped
public class InjectionJobFactory implements JobFactory {    
    @Inject @Any
    private Instance&lt;Job&gt; jobs;
    
    @Override
    public Job newJob(TriggerFiredBundle bundle, Scheduler scheduler) throws SchedulerException {
        final Class&lt;? extends Job&gt; clazz = bundle.getJobDetail().getJobClass();
        final Instance&lt;? extends Job&gt; bean = jobs.select(clazz);
        if (bean.isUnsatisfied()) throw new SchedulerException(&quot;No job bean of type &quot; + clazz + &quot; found.&quot;);
        return bean.get();
    }
}</pre></div>



<div class="bs-callout bs-callout-info"><strong>Note:</strong>
Of course we could use additional vaules to do fruther filtering e.g. based on annotations.
</div>



<h2 class="wp-block-heading">Register our timers</h2>



<p>Quartz provides us the Job interface our timer have to implement. As soon this is done we can register a timer:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">// Create a QuarzJob to run
JobDetail jeeJob = JobBuilder.newJob(CdiTimer.class)
        .withIdentity(CdiTimer.class.getSimpleName())
        .build();

// Create a Trigger to trigger the job every five minutes 
Trigger trigger = TriggerBuilder.newTrigger()
                 // run every 10 seconds
                 .withSchedule(CronScheduleBuilder.cronSchedule(&quot;0/10 * * * * ?&quot;))
                 .forJob(jeeJob)			
                 .build();

// Register Job and Trigger with the scheduler
scheduler.scheduleJob(jeeJob, trigger);</pre></div>



<h3 class="wp-block-heading">CDI Timer</h3>



<p>Using CDI beans as timers is just straight forward, add the interface, ensure they are annotated as application scoped, done.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">import org.quartz.Job;
import javax.enterprise.context.ApplicationScoped;
// our simple CDI timer bean
@ApplicationScoped // timer don't have a scope or web request ...
public class CdiTimer implements Job {

    @Override
    public void execute(JobExecutionContext context) {
        // the CDI timer code
    }   
}</pre></div>



<h3 class="wp-block-heading">EJBs as timer beans</h3>



<p>EJBs are a bit different. As soon as we add the interface you might encounter the problem that <code>@Inject</code> doesn&#8217;t work. Well long story short just tell JEE that it just a <a rel="noreferrer noopener" aria-label="local bean (öffnet in neuem Tab)" href="https://docs.oracle.com/javaee/7/api/javax/ejb/LocalBean.html" target="_blank">local bean</a> with <code>@LocalBean</code> and all will be good:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import org.quartz.Job;
// tells JEE to not mess around because we use an interface, this is not a remote EJB!
@LocalBean 
@Stateless
public class EjbTimer implements Job {

    @Override
    public void execute(JobExecutionContext context) {
        // the EJB timer code
    }
}</pre></div>



<h2 class="wp-block-heading">Links</h2>



<ul class="wp-block-list"><li><a href="http://www.quartz-scheduler.org/">Quartz</a></li><li><a href="https://deltaspike.apache.org/documentation/scheduler.html">Deltaspike Quartz</a></li><li><a rel="noreferrer noopener" aria-label="Spring Quartz datasource integratrion (öffnet in neuem Tab)" href="https://github.com/spring-projects/spring-framework/blob/master/spring-context-support/src/main/java/org/springframework/scheduling/quartz/LocalDataSourceJobStore.java" target="_blank">Spring Quartz datasource integration</a></li><li><a href="https://spring.io/projects/spring-cloud-task">Spring Cloud Task</a></li></ul>



<h2 class="wp-block-heading">Sidenotes</h2>



<p>Not enough? Well here some other side notes.</p>



<h3 class="wp-block-heading">Manage dependant Scope Beans</h3>



<p>Just for completeness but not as a recommendation, it is possible to use also not annotated CDI beans as Timer beans. Of course, we have to handle than its lifecycle and destroy them after they have beans used. In the <a rel="noreferrer noopener" aria-label="JBoss Documentation (öffnet in neuem Tab)" href="https://docs.jboss.org/weld/reference/latest/en-US/html/injection.html#_enhanced_version_of_javax_enterprise_inject_instance" target="_blank">JBoss Documentation</a>, we are pointed to a <code>WeldInstance</code> class, which allows us to check the scope and later also to destroy the bean.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">// important is the usage of the WeldInstance instead of Instance
@Inject @Any
WeldInstance Job jobs;

// which would allow us to add the destroy code after the timer was used
// problem of course is to find the correct point in Quartz to postion this part
if (Dependent.class.equals(handler.getBean().getScope()) {
    // Destroy only dependent CDI beans
    handler.destroy();
}</pre></div>



<h3 class="wp-block-heading">Creating the Quartz tables</h3>



<p>Quartz provides two ways to set up the tables out of the box:</p>



<ol class="wp-block-list"><li>SQL to be used e.g. with <a rel="noreferrer noopener" aria-label="flyway (öffnet in neuem Tab)" href="https://flywaydb.org/" target="_blank">flyway</a></li><li>XML to be used with <a href="https://www.liquibase.org/" target="_blank" rel="noreferrer noopener" aria-label="liquibase (öffnet in neuem Tab)">liquibase</a></li></ol>



<p>The second one has the charm that it works also in tests out of the box, as liquibase supports multiple DBs.</p>



<p>As so we can copy the <a rel="noreferrer noopener" aria-label="liquibase.quartz.init.xml (öffnet in neuem Tab)" href="https://github.com/quartz-scheduler/quartz/blob/master/quartz-core/src/main/resources/org/quartz/impl/jdbcjobstore/liquibase.quartz.init.xml" target="_blank">liquibase.quartz.init.xml</a> into our <code>src/main/resources</code> and execute the following code before the initialization of quartz.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">try (Connection c = dataSource.getConnection()) {
    Liquibase l = new Liquibase(
            &quot;/liquibase.quartz.init.xml&quot;, 
            new ClassLoaderResourceAccessor(getClass().getClassLoader()),
            DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(c)));
    l.update(&quot;QUARTZ-SCHEMA&quot;);
} catch (Exception e) {
    throw new RuntimeException(&quot;Failed to init quartz schema.&quot;, e);
}</pre></div>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2019/09/quartz-scheduler-integration-in-java-jee/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>JEE 7 Activiti integration</title>
		<link>https://sterl.org/2017/09/jee-7-activiti-integration/</link>
					<comments>https://sterl.org/2017/09/jee-7-activiti-integration/#respond</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Sat, 02 Sep 2017 14:12:46 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Activiti]]></category>
		<category><![CDATA[alfresco]]></category>
		<category><![CDATA[BPM]]></category>
		<category><![CDATA[JEE7]]></category>
		<guid isPermaLink="false">http://sterl.org/?p=239</guid>

					<description><![CDATA[Overview To enable Activiti in our JEE project the following steps are needed: Add the maven dependencies &#8212; include spring-context Add log4j configuration Add the activiti configuration for CDI integration&#160;activiti.cfg.xml Add your first activiti workflow Add an activiti compatible data source to your container Deploy and run it Git Project. Eclipse Plugin To install the&#8230;]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading"> Overview</h2>



<p> To enable Activiti in our JEE project the following steps are needed: </p>



<ol class="wp-block-list"><li>Add the maven dependencies &#8212; include spring-context</li><li>Add log4j configuration</li><li>Add the activiti configuration for CDI integration&nbsp;activiti.cfg.xml</li><li>Add your first activiti workflow</li><li>Add an activiti compatible data source to your container</li><li>Deploy and run it </li></ol>



<p><a href="https://github.com/sterlp/jee7-activiti">Git Project</a>.

</p>



<h2 class="wp-block-heading"> Eclipse Plugin</h2>



<p> To install the activiti designer just add the following update site to eclipse:&nbsp;http://docs.alfresco.com/5.2/tasks/wf-install-activiti-designer.html for more details just check the <a rel="noreferrer noopener" href="https://www.activiti.org/userguide/#eclipseDesignerInstallation" target="_blank">documentation</a>. </p>



<h2 class="wp-block-heading"> Add activity maven dependencies </h2>



<p> For JEE we want not only to add the normal dependencies for the core lib but also the CDI integration which allows us later on to access our CDI or EJB beans. In addition, we need one more dependency to have the JNDI bean. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;xml&quot;,&quot;mime&quot;:&quot;application/xml&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;XML&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;xml&quot;}">&lt;!-- activiti --&gt; 
&lt;dependency&gt; 
  &lt;groupId&gt;org.activiti&lt;/groupId&gt; 
  &lt;artifactId&gt;activiti-engine&lt;/artifactId&gt; 
  &lt;version&gt;6.0.0&lt;/version&gt; 
&lt;/dependency&gt; 
&lt;dependency&gt; 
  &lt;groupId&gt;org.activiti&lt;/groupId&gt; 
  &lt;artifactId&gt;activiti-cdi&lt;/artifactId&gt; 
  &lt;version&gt;6.0.0&lt;/version&gt; 
&lt;/dependency&gt; 
&lt;!-- to get org.springframework.jndi.JndiObjectFactoryBean, same version as used by activiti --&gt; 
&lt;dependency&gt; 
  &lt;groupId&gt;org.springframework&lt;/groupId&gt; 
  &lt;artifactId&gt;spring-context&lt;/artifactId&gt; 
  &lt;version&gt;4.2.5.RELEASE&lt;/version&gt; 
&lt;/dependency&gt; 
&lt;!-- Needed to see the log --&gt; 
&lt;dependency&gt; 
  &lt;groupId&gt;org.slf4j&lt;/groupId&gt; 
  &lt;artifactId&gt;slf4j-log4j12&lt;/artifactId&gt; 
  &lt;version&gt;${slf4j.version}&lt;/version&gt; 
&lt;/dependency&gt;</pre></div>



<h2 class="wp-block-heading"> Add log4j configuration </h2>



<p>Before we start with activiti we should add the log4j.xml configuration into src/main/resources which would allow us to see any error in activiti, otherwise, we are blind. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;xml&quot;,&quot;mime&quot;:&quot;application/xml&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;XML&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;xml&quot;}">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt; 
&lt;!DOCTYPE log4j:configuration SYSTEM &quot;log4j.dtd&quot;&gt; 
&lt;log4j:configuration debug=&quot;true&quot; xmlns:log4j='http://jakarta.apache.org/log4j/'&gt; 
  &lt;appender name=&quot;console&quot; class=&quot;org.apache.log4j.ConsoleAppender&quot;&gt; 
    &lt;layout class=&quot;org.apache.log4j.PatternLayout&quot;&gt; 
      &lt;param name=&quot;ConversionPattern&quot; value=&quot;%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n&quot; /&gt; 
    &lt;/layout&gt; 
  &lt;/appender&gt; 
  &lt;root&gt; 
    &lt;level value=&quot;INFO&quot; /&gt; &lt;appender-ref ref=&quot;console&quot; /&gt; 
  &lt;/root&gt; 
&lt;/log4j:configuration&gt;</pre></div>



<h2 class="wp-block-heading"> Add activiti configuration</h2>



<p>Add to the <code>src/main/resources</code> folder the default&nbsp;<code>activiti.cfg.xml</code> configuration which is picked up automatically by the activiti CDI integration to create the process engine.</p>



<div class="bs-callout bs-callout-info"><strong>Note:</strong>&nbsp;We set here the <code>TransactionManager</code> and the <code>ThreadFactory</code> to ensure threads and the transaction is managed by the JEE container. You may also provide the executor which is configured in the JEE container by you. As the <code>ManagedAsyncJobExecutor</code> is just creating a <code>ThreadPoolExecutor</code> under the hood.
</div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;htmlmixed&quot;,&quot;mime&quot;:&quot;text/html&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;HTML&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;html&quot;}">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; 
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd&quot;&gt; 
  &lt;!-- lookup the JTA-Transaction manager --&gt; 
  &lt;bean id=&quot;transactionManager&quot; class=&quot;org.springframework.jndi.JndiObjectFactoryBean&quot;&gt; 
    &lt;property name=&quot;jndiName&quot; value=&quot;java:appserver/TransactionManager&quot; /&gt; 
    &lt;property name=&quot;resourceRef&quot; value=&quot;true&quot; /&gt; 
  &lt;/bean&gt; 
  &lt;!-- using the JEE container thread factory for the managed executor service --&gt; 
  &lt;bean id=&quot;asyncExecutor&quot; class=&quot;org.activiti.engine.impl.asyncexecutor.ManagedAsyncJobExecutor&quot;&gt; 
    &lt;property name=&quot;threadFactory&quot;&gt; 
      &lt;bean class=&quot;org.springframework.jndi.JndiObjectFactoryBean&quot;&gt; 
        &lt;property name=&quot;jndiName&quot; value=&quot;java:comp/DefaultManagedThreadFactory&quot; /&gt; 
        &lt;property name=&quot;resourceRef&quot; value=&quot;true&quot; /&gt; 
      &lt;/bean&gt; 
    &lt;/property&gt; 
  &lt;/bean&gt; 
  &lt;!-- process engine configuration --&gt; 
  &lt;bean id=&quot;processEngineConfiguration&quot; class=&quot;org.activiti.cdi.CdiJtaProcessEngineConfiguration&quot;&gt; 
    &lt;property name=&quot;dataSourceJndiName&quot; value=&quot;jdbc/postgresql&quot; /&gt; 
    &lt;property name=&quot;transactionManager&quot; ref=&quot;transactionManager&quot; /&gt; 
    &lt;property name=&quot;asyncExecutor&quot; ref=&quot;asyncExecutor&quot; /&gt; 
    &lt;!-- using externally managed transactions --&gt; 
    &lt;property name=&quot;transactionsExternallyManaged&quot; value=&quot;true&quot; /&gt; 
    &lt;!-- will create the activiti DB schema automatically as needed --&gt; 
    &lt;property name=&quot;databaseSchemaUpdate&quot; value=&quot;true&quot; /&gt; 
  &lt;/bean&gt; 
&lt;/beans&gt;</pre></div>



<h2 class="wp-block-heading"> Deploy a workflow </h2>



<p> Overall where to ways to deploy your workflows. Either using XML or programmatically. Here I will use the last to demonstrate the injection and usage in a very simple&nbsp;(not production-ready) way: </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">@Singleton
@Startup
public class SampleProcessDeployerBA {

    @Inject RepositoryService repositoryService;

    @PostConstruct
    void start() {
        // this will deploy the same process over and over again ...
        Deployment deploy = repositoryService.createDeployment()
                .name(&quot;SampleProcess&quot;)
                .key(&quot;SampleProcess&quot;) // note this has no effect, the ID of the bpmn file is used &quot;myProcess&quot;
                .addClasspathResource(&quot;org/sterl/jee/activiti/impl/sample/control/SampleProcess.bpmn&quot;)
                .deploy();
        System.out.println(&quot;Deployed process ID: &quot; + deploy.getId() + &quot; KEY &quot; + deploy.getKey());
    }
}</pre></div>



<h2 class="wp-block-heading"> Start a workflow</h2>



<div class="bs-callout bs-callout-info">
<strong>Note:</strong> The process ID is defined in the process <code>bpmn</code> file.
</div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">@Named // that activiti finds this EJB
@Singleton // show that this is a singleton
public class HelloWorldBF {
    @Inject RuntimeService runtimeService;

    public void startProcess() {
        // use here the id you defined in the process designer
        ProcessInstance process = runtimeService.startProcessInstanceByKey(&quot;myProcess&quot;);
        System.out.println(&quot;Process &quot; + process.getName() + &quot; started with ID: &quot; + process.getId());
    }
}</pre></div>



<h2 class="wp-block-heading">Activiti support currently following DB </h2>



<p>Add to your JEE container one JNDI data source of one of the following supported database types. In this sample we name it <code>jdbc/activiti</code>.</p>



<div class="bs-callout bs-callout-info"><strong>Note:</strong> The default Sample DB of Payara is a Apache Derby DB and is not supported by Activiti. </div>



<p>This list is taken from <a href="https://www.activiti.org/userguide/#supporteddatabases" target="_blank" rel="noreferrer noopener">version 6.0</a>.</p>



<ul class="wp-block-list"><li>H2</li><li>HSQL</li><li>MYSQL</li><li>ORACLE</li><li>POSTGRES</li><li>MSSQL</li><li>DB2</li></ul>



<pre style="white-space: pre;">Information:   2017-08-31 20:49:49 ERROR ProcessEngines:169 - Exception while initializing process engine: couldn't deduct database type from database product name 'Apache Derby'
org.activiti.engine.ActivitiException: couldn't deduct database type from database product name 'Apache Derby'
	at org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl.initDatabaseType(ProcessEngineConfigurationImpl.java:963)
	at org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl.initDataSource(ProcessEngineConfigurationImpl.java:907)
	at org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl.init(ProcessEngineConfigurationImpl.java:689)
	at org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl.buildProcessEngine(ProcessEngineConfigurationImpl.java:664)
	at org.activiti.engine.ProcessEngines.buildProcessEngine(ProcessEngines.java:189)
	at org.activiti.engine.ProcessEngines.initProcessEngineFromResource(ProcessEngines.java:162)
	at org.activiti.engine.ProcessEngines.init(ProcessEngines.java:94)
	at org.activiti.engine.ProcessEngines.getProcessEngine(ProcessEngines.java:223)
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2017/09/jee-7-activiti-integration/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
