sebastiandaschner blog


Calculations in Quarkus Qute using AtomicInteger

#quarkus tuesday, february 01, 2022

Quarkus' Qute Templating Engine is very handy for creating server-side rendered pages. Besides the regular loops and control structures, there’s also a possibility to set and update variables, at least with a small trick. In the following, we’ll see how to do some arithmetic calculations using Java’s AtomicInteger.

Usually, you can invoke methods of objects that are passed to Qute, but you can’t easily update the variables itself. There’s the {#let} directive to define variables but in order to update values we need to use types that provide methods to do so, unlike Java primitives.

Imagine we’d like to have multiple nested loops and would like some global counter:

{#let counter=math:atomicInt(1)}
{#for entry in entries}
    <li>{counter.getAndIncrement()}. {entry_count}.
        {entry.title} {#if entry_hasNext}OR{/}</li>
{/for}

{#for i in 5}
    <li>{counter.getAndIncrement()}. {i_count}.
        Entry number {i}{#if i_hasNext},{/}</li>
{/for}
{/let}

What happens is that the counter variable is of type AtomicInteger and the getAndIncrement method returns and changes the internal numeric value. We provide the instance via a template extension method:

@TemplateExtension(namespace = "math")
static AtomicInteger atomicInt(int initial) {
    return new AtomicInteger(initial);
}

The result looks like follows:

  • 1. 1. This is an entry OR

  • 2. 2. This is another entry OR

  • 3. 3. This is yet another entry

  • 4. 1. Entry number 1,

  • 5. 2. Entry number 2,

  • 6. 3. Entry number 3,

  • 7. 4. Entry number 4,

  • 8. 5. Entry number 5

 

As an alternative, you can also initialize and provide the AtomicInteger in your Java code:

// ... in your Qute REST controller
return template.data("entries", entries, "counter", new AtomicInteger(1));

Then you can get rid of the {#let} directive:

<ul>
{#for entry in entries}
    <li>{counter.getAndIncrement()}. {entry_count}.
        {entry.title} {#if entry_hasNext}OR{/}</li>
{/for}

{#for i in 5}
    <li>{counter.getAndIncrement()}. {i_count}.
        Entry number {i}{#if i_hasNext},{/}</li>
{/for}
</ul>

These examples are using Quarkus version 2.7.0.Final.

 

Found the post useful? Subscribe to my newsletter for more free content, tips and tricks on IT & Java: