Quarkus

Migrating applications from a well-grounded framework to a completely new framework just a few days after its public release sounds crazy, right? Before doing so, I asked myself several questions, such as: Why should I do that? Is this new framework stable? What would be the gain? To me, the most important of these is: Why?

To help answer that question, I started thinking about my application's performance—in this case, the bootstrap time—and asked myself whether I was happy with the actual time my application took to start up. The answer was no. And, nowadays, this is one of the most important metrics to be considered when working with microservices, mainly on a serverless architecture.

The goal of this article is to provide a point of reference for a basic migration of an existing Java EE application to Quarkus. For this reason, I'll save a few lines of the article by not introducing Quarkus and focus mostly on the migration part. If you don't know what Quarkus is, then I recommend reading this article and visiting the Quarkus homepage.

In this article, I'll try to illustrate all the changes, or at least the most important changes, that I had to do on my existing application to make it run well with Quarkus.

A little background

The app used is a Telegram API + Bot with several plugins that I've been using as a playground where I can try new things, frameworks, etc. When this app was created, we decided to create a Telegram Java EE API so we could run it in any application server or framework that implements all the EE 7 Standards. The main reason was the ability to use cool stuff like CDI, JPA, and Rest. It was designed for WildFly Swarm, which is now called Thorntail. Since then there have been no framework changes. Once Quarkus was released, I decided to take a further look at it, and the first impressions were amazing. It supports all the dependencies that I had initially, and most importantly, the ability to create native container images with GraalVM. So, I thought, why not give it a try?

Of course, a migration like this is not easy.

First steps

When I started to migrate the application, I divided the work into smaller sections, such as:

  • Dependencies
  • Divide and conquer (migrate modules, one by one)
  • Code changes
  • Dependencies review

Dependencies

As you can imagine, the first thing I did was completely remove Thorntail dependencies—in my case, the BOM from parent pom and the related dependencies from every module. I changed this:

<dependency>
    <groupId>io.thorntail</groupId>
    <artifactId>bom</artifactId>
    <version>${version.io.thorntail}</version>
    <scope>import</scope>
    <type>pom</type>
</dependency>

to:

<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-bom</artifactId>
    <version>${io.quarkus.version}</version>
    <type>pom</type>
    <scope>import</scope>
</dependency>

Next, I also had to remove the javaee-api dependency, which is mostly used for CDI purposes, and replace it with the quarkus-arc, one of the core libraries which provides dependency injection. So, I removed it from the parent pom and did a big replace on every pom.xml:

<dependency>
- <groupId>javax</groupId>
- <artifactId>javaee-api</artifactId>
+ <groupId>io.quarkus</groupId>
+ <artifactId>quarkus-arc</artifactId>
+ <scope>provided</scope>
</dependency>

Below you can find a few more dependencies that I had to change:

  • io.thorntail:jaxrs -> io.quarkus:quarkus-resteasy
  • io.thorntail:jpa -> io.quarkus:quarkus-hibernate-orm
  • data validation -> io.quarkus:quarkus-hibernate-validator.
  • com.h2database -> io.quarkus:quarkus-jdbc-h2 (Quarkus already has some jdbc extensions, H2, MariaDB, and PostgreSQL; for Oracle, there is a good starting point here).

On the project hierarchy, this is the module that produces the runnable jar, and it is here that we need to take out the Thorntail maven plugin and put in the Quarkus maven plugin. This is a very important step; without it, you will not be able to use Quarkus.

Note that when working with a multi-module project, you need to pay attention to the Quarkus dependencies. For example, if some of your modules expose a Rest endpoint, you'll need to use the quarkus-resteasy extension. But, note that, in order to enable this extension, this dependency also needs to be declared on the runnable module.

Example:

<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-resteasy</artifactId>
    <scope>provided</scope>
</dependency>

To make sure the extensions were installed as expected, you can always verify the logs. Quarkus lets you know which extensions were installed, and a similar line is printed when the app is ready:

INFO [io.quarkus] Installed features: [agroal, cdi, hibernate-orm, jdbc-h2, narayana-jta, resteasy, scheduler]

Now is the time when the fun really begins, with a lot of issues, missing dependencies, etc. The first time that the mvn compile quarkus:dev or mvn clean package is executed, don't panic; a lot of issues will happen, and remember, divide and conquer!

Code changes

At first, I confess I got a little bit scared, so that was the right time to take a breath, get a cup of coffee, and get things done!

The approach I used to make things easier was to make the build work first on the smaller modules and then move forward to accomplish the first goal: a successful build! At this point, I removed every dependency from the main pom.xml in order to build only the CoreAPI and the runnable jar.

After going through the dependencies, my IDE started to complain about unsatisfied dependencies. In this case, there was an issue related to EJB annotations. As you can see here, I used the EJB annotations to execute tasks during the app startup using @Startup, @PostConstruct, and @PreDestroy annotations. A simple way to fix it would be just to remove the EJB annotations and keep using the PostConstruct and add a CDI annotation (i.e., ApplicationScoped on class level). But Quarkus provides a fancy way to control the application's lifecycle, with the Startup and Shutdown events that can be observed in this example. For more details about this specific functionality, please refer to the Quarkus documentation.

One of the easiest parts was the Core API, along with some basic changes to configure CDI. On the previous version, I was using the Service Provider Implementation and discovering new providers through Service Provider mechanism. With Quarkus, I could completely remove the Service Provider files and replace it with the beans.xml file. In my case, all modules that use CDI had to have the beans.xml file added as well so Quarkus could properly discovery CDI beans. Once that was done, I could move forward and try to build the CoreAPI. If you face an issue, like the example below, the first place you might want to look is whether the dependencies listed in the issue have the beans.xml.

An interesting issue I had to fix was a CDI Circular dependency where I was injecting ClassA and ClassB, but ClassB already was Injecting ClassA. I am not sure why Thorntail was accepting it, but Quarkus is very strict.

At this point, I successfully built the CoreAPI; it requires some System Properties in order to correctly configure the application. If the required properties are not set, the app will fail to start. Previously, the API was expecting only System Properties; with Quarkus this configuration was improved by also reading the microprofile-config.properties. Once the configuration of the app properties was done, I moved on to the plugins.

The first plugins I moved to Quarkus were the simplest ones that do not require Persistence or the Cache layer, for example, this simple ping plugin.

Another point of attention is the use of private members; if you got a message similar to the one below, you will have to change the access modifiers. Or, if you really think that the access modifier needs to be private, you might want to use package-private instead:

Found unrecommended usage of private members (use package-private instead) in application beans

Wow, at this point I already have my app running with the first plugin on Quarkus:

INFO [it.reb.reb.Startup] (main) The application is starting...
INFO [io.quarkus] (main) Quarkus 0.11.0 started in 0.359s.
INFO [io.quarkus] (main) Installed features: [cdi]

Because most of the logging stuff for my app is under the FINE log level, I would like to configure the logging to print only debug messages that belongs to my app. To achieve this, I had to add some logging configurations on the microprofile-config.properties, just like the example below:

# DEBUG console logging
quarkus.log.console.enable=true
quarkus.log.console.format=%d{HH:mm:ss} %-5p [%c] %s%e%n
quarkus.log.console.level=TRACE

# TRACE file logging
quarkus.log.file.enable=true
quarkus.log.file.path=/tmp/quarkus.log
quarkus.log.file.level=TRACE
quarkus.log.file.format=%d{HH:mm:ss} %-5p [%c{2.}]] (%t) %s%e%n

# custom loggers
quarkus.log.category."it.rebase".level=TRACE

Scheduler

One of the plugins I was using was the EJB timer. In order to take advantage of everything that Quarkus provides, however, I replaced the EJB timer with the quarkus-scheduler extension (Quartz under the hood), which also works with Annotations. And, to be honest, its usage is very simple, that is:

@Scheduled(every = "1800s", delay = 30)

And its dependency:

<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-scheduler</artifactId>
    <scope>provided</scope>
</dependency>

Infinispan cache

My app was using the Infinispan embedded cache where I was using specific Qualifiers and Producers to configure a different cache for different purposes and where I could just inject a specific cache according to my plugin needs. When I built the cache module, I got the following issue:

[error]: Build step io.quarkus.arc.deployment.ArcAnnotationProcessor#build threw an exception: javax.enterprise.inject.spi.DefinitionException: Interceptor has no bindings: org.infinispan.jcache.annotation.CachePutInterceptor

This was fixed by updating the Infinispan dependencies:

  • Bump version from 9.1.1.Final to 9.4.9.Final
  • Update dependency from org.infinispan:infinispan-embedded to org.infinispan:infinispan-cdi-embedded

From this point, I got some CDI issues, like:

  • Unsatisfied dependency for type org.infinispan.manager.EmbeddedCacheManager#defaultCacheContainer
  • Unsatisfied dependency for type org.infinispan.cdi.embedded.InfinispanExtensionEmbedded#infinispanExtension
  • Unsatisfied dependency for type org.infinispan.Cache<java.lang.String, java.lang.String> and qualifiers [@Default]

Basically, the issue is telling us that there are no Producers for the methods above. To fix that, I had to manually create producers to satisfy the missing dependencies; to start I modified the default cache by removing the old cache configuration that looks like:

@Produces
@ConfigureCache("default-cache")
@DefaultCache
public Configuration specialCacheCfg(InjectionPoint injectionPoint) {

...

}

And added the new cache configuration:

private DefaultCacheManager defaultCacheManager;

@Produces
@DefaultCache
public Cache<String, String> returnDefaultCacheStringObject() {
    return defaultCacheContainer().getCache();
}

@Produces
public Configuration defaultCacheProducer() {
    log.info("Configuring default-cache...");
    return new ConfigurationBuilder()
            .indexing()
            .autoConfig(true)
            .memory()
            .size(1000)
            .build();
}

@Produces
public EmbeddedCacheManager defaultCacheContainer() {
    if (null == defaultCacheManager) {
        GlobalConfiguration g = new GlobalConfigurationBuilder()
                .nonClusteredDefault()
                .defaultCacheName("default-cache")
                .globalJmxStatistics()
                .allowDuplicateDomains(false)
                .build();
        defaultCacheManager = new DefaultCacheManager(g, defaultCacheProducer());
    }
    return defaultCacheManager;
}

@Produces
public InfinispanExtensionEmbedded defaultInfinispanExtensionEmbedded() {
    return new InfinispanExtensionEmbedded();
}

Another point I had to update was the Event Listeners. Here is an example before the changes:

@Listener
public class KarmaEventListener {
...
    @CacheEntryCreated
    public void entryCreated(@Observes CacheEntryCreatedEvent event) {
    ...
    }
}

Persistence Module

Besides the dependency changes described previously on Thorntail, to use the database, you would have to create a file called project-defaults.yaml under resources/ path and declare the database information there in addition to the persistence.xml file. With Quarkus, this can be done by providing a file called application.properties on the same path, as described here. Or, you can provide all the database settings using System Properties through the command line when running the binary. So, the two old files were replaced by the application.properties; here is an example:

quarkus.datasource.url=jdbc:h2:file:/opt/h2/database.db;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
quarkus.datasource.driver=org.h2.Driver
quarkus.datasource.username=rebot
quarkus.datasource.password=rebot
quarkus.datasource.max-size=8
quarkus.datasource.min-size=2
quarkus.hibernate-orm.database.generation=update
quarkus.hibernate-orm.log.sql=false

Another little change was a tweak on the EntityManager Injection that had to be changed from:

@PersistenceContext(unitName = "rebotPU")
private EntityManager em;

to

@Inject
EntityManager em;

Dependencies review

I completely removed resteasy dependencies and used quarkus-resteasy instead. After removing the resteasy, a new issue started to happen:

Caused by: java.lang.ClassNotFoundException: org.glassfish.jersey.client.JerseyClientBuilder

To solve this, three new dependencies had to be added on the modules that were using the javax.ws.rs.client.ClientBuilder. The new dependencies are:

  • org.glassfish.jersey.core:jersey-client
  • org.glassfish.jersey.inject:jersey-hk2
  • org.glassfish.jersey.media:jersey-media-json-jackson

It would definitely be worthwhile to investigate this further or drop the ClientBuilder usage.

WARN: RESTEASY002145: NoClassDefFoundError: Unable to load builtin provider org.jboss.resteasy.plugins.providers.DataSourceProvider from jar:file:/home/spolti/.m2/repository/org/jboss/resteasy/resteasy-core/4.0.0.Beta8/resteasy-core-4.0.0.Beta8.jar!/META-INF/services/javax.ws.rs.ext.Providers
java.lang.NoClassDefFoundError: javax/activation/DataSource

This situation was fixed by adding the quarkus-hibernate-orm on the module that failed with this issue.

I think I've covered the most important points that came up during my experience while migrating my app to Quarkus. This was the first step; unfortunately, I was not able to build the native binary because the Infinispan embedded cache dependency is not ready for it yet. Definitely, one of the next steps would be to look for an alternative for it, which will be a topic for a new article.

Last updated: February 11, 2024