<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Marcelo Paixão Resende's Blog]]></title><description><![CDATA[Marcelo Paixão Resende's Blog]]></description><link>https://marceloresende.dev</link><generator>RSS for Node</generator><lastBuildDate>Thu, 12 Nov 2026 06:36:44 GMT</lastBuildDate><atom:link href="https://marceloresende.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Detecting Absent Properties in Java REST APIs with Jackson, Spring, and Custom Deserializers]]></title><description><![CDATA[Ensuring Compatibility and Flexibility in Java REST APIs with Custom Deserializers for Optional Properties]]></description><link>https://marceloresende.dev/detecting-absent-properties-in-java-rest-apis-with-jackson-spring-and-custom-deserializers</link><guid isPermaLink="true">https://marceloresende.dev/detecting-absent-properties-in-java-rest-apis-with-jackson-spring-and-custom-deserializers</guid><category><![CDATA[Java]]></category><category><![CDATA[Spring]]></category><category><![CDATA[REST API]]></category><category><![CDATA[jackson]]></category><category><![CDATA[json]]></category><dc:creator><![CDATA[Marcelo Paixão Resende]]></dc:creator><pubDate>Mon, 01 Jul 2024 15:00:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1719587930751/801f200f-7455-4708-b71e-9d94e0c1d5f6.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In modern software development, ensuring backward compatibility with older clients while introducing new features can be challenging. One such challenge is detecting whether a specific property was sent through a REST API request. By default, Jackson deserializes absent properties to <code>null</code>, which complicates the process of identifying whether a property was intentionally set to <code>null</code> or was absent in the request altogether. This article will walk you through a solution using a custom Jackson deserializer to handle this scenario.</p>
<h2 id="heading-the-problem">The Problem</h2>
<p>Using Java, Spring, and Jackson, I needed to identify whether a specific property was sent through my REST API to maintain compatibility with older clients. If the property was not sent, I must detect that the property was absent in the request and ignore it. However, Jackson's default behavior deserializes absent properties to <code>null</code>, making it difficult to distinguish between an absent property and one explicitly set to <code>null</code>.</p>
<h2 id="heading-the-solution-custom-jackson-deserializer">The Solution: Custom Jackson Deserializer</h2>
<p>To solve this problem, we can use a custom Jackson deserializer that can handle three states for a property: present, absent, and explicitly set to <code>null</code>. This is achieved by creating an <code>OptionalProperty</code> wrapper and a custom deserializer for this wrapper.</p>
<h3 id="heading-implementing-the-optionalproperty-wrapper">Implementing the <code>OptionalProperty</code> Wrapper</h3>
<p>The <code>OptionalProperty</code> class represents a property that can be present with a value, absent, or present with a <code>null</code> value. This class provides methods to check the presence of a value and handle each state appropriately.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.io.Serializable;
<span class="hljs-keyword">import</span> java.util.function.Consumer;

<span class="hljs-comment">/**
 * This class represents an optional property.
 * &lt;p&gt;
 * The difference between this and {<span class="hljs-doctag">@code</span> java.util.Optional} is that this class represents three states:
 *
 * &lt;ul&gt;
 * &lt;li&gt;The value is present.&lt;/li&gt;
 * &lt;li&gt;The value is absent.&lt;/li&gt;
 * &lt;li&gt;The value is present but it is null.&lt;/li&gt;
 * &lt;/ul&gt;
 * &lt;p&gt;
 * It is a container object which may or may not contain a non-null value.
 * &lt;p&gt;
 * If a value is present, {<span class="hljs-doctag">@code</span> isPresent()} will return {<span class="hljs-doctag">@code</span> true} and {<span class="hljs-doctag">@code</span> get()} will return the value.
 * &lt;p&gt;
 * Additional methods that depend on the presence or absence of a contained value are provided, such as {<span class="hljs-doctag">@code</span> ifPresent()}.&lt;br&gt;
 *
 * <span class="hljs-doctag">@param</span> &lt;T&gt; the type of the value
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OptionalProperty</span>&lt;<span class="hljs-title">T</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Serializable</span>&gt; <span class="hljs-keyword">implements</span> <span class="hljs-title">Serializable</span> </span>{

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">boolean</span> isPresent;
    <span class="hljs-keyword">private</span> T value;

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">OptionalProperty</span><span class="hljs-params">(<span class="hljs-keyword">boolean</span> isPresent, T value)</span> </span>{
        <span class="hljs-keyword">this</span>.isPresent = isPresent;
        <span class="hljs-keyword">this</span>.value = value;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> &lt;T extends Serializable&gt; <span class="hljs-function">OptionalProperty&lt;T&gt; <span class="hljs-title">of</span><span class="hljs-params">(T value)</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> OptionalProperty&lt;&gt;(<span class="hljs-keyword">true</span>, value);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> &lt;T extends Serializable&gt; <span class="hljs-function">OptionalProperty&lt;T&gt; <span class="hljs-title">absent</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> OptionalProperty&lt;&gt;(<span class="hljs-keyword">false</span>, <span class="hljs-keyword">null</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> T <span class="hljs-title">get</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">if</span> (!isPresent) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalStateException(<span class="hljs-string">"No value present"</span>);
        }
        <span class="hljs-keyword">return</span> value;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">isAbsent</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> !isPresent;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">isPresent</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> isPresent;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> OptionalProperty&lt;T&gt; <span class="hljs-title">ifPresent</span><span class="hljs-params">(Consumer&lt;? <span class="hljs-keyword">super</span> T&gt; consumer)</span> </span>{
        <span class="hljs-keyword">if</span> (isPresent) {
            consumer.accept(value);
        }
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> OptionalProperty&lt;T&gt; <span class="hljs-title">ifPresentAndNotNull</span><span class="hljs-params">(Consumer&lt;? <span class="hljs-keyword">super</span> T&gt; consumer)</span> </span>{
        <span class="hljs-keyword">if</span> (isPresent &amp;&amp; value != <span class="hljs-keyword">null</span>) {
            consumer.accept(value);
        }
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> OptionalProperty&lt;T&gt; <span class="hljs-title">ifAbsent</span><span class="hljs-params">(Runnable runnable)</span> </span>{
        <span class="hljs-keyword">if</span> (!isPresent) {
            runnable.run();
        }
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> T <span class="hljs-title">orElse</span><span class="hljs-params">(T other)</span> </span>{
        <span class="hljs-keyword">return</span> isPresent ? value : other;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> T <span class="hljs-title">orElseNull</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> orElse(<span class="hljs-keyword">null</span>);
    }
}
</code></pre>
<h3 id="heading-creating-the-custom-deserializer">Creating the Custom Deserializer</h3>
<p>Next, we create a custom deserializer for the <code>OptionalProperty</code> class. This deserializer will handle the three states: present with value, absent, and present with a <code>null</code> value.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> com.fasterxml.jackson.core.JacksonException;
<span class="hljs-keyword">import</span> com.fasterxml.jackson.core.JsonParser;
<span class="hljs-keyword">import</span> com.fasterxml.jackson.databind.BeanProperty;
<span class="hljs-keyword">import</span> com.fasterxml.jackson.databind.DeserializationContext;
<span class="hljs-keyword">import</span> com.fasterxml.jackson.databind.JsonDeserializer;
<span class="hljs-keyword">import</span> com.fasterxml.jackson.databind.JsonMappingException;
<span class="hljs-keyword">import</span> com.fasterxml.jackson.databind.deser.ContextualDeserializer;

<span class="hljs-keyword">import</span> java.io.IOException;
<span class="hljs-keyword">import</span> java.io.Serializable;

<span class="hljs-comment">/**
 * This class is a custom deserializer for {<span class="hljs-doctag">@link</span> OptionalProperty} objects.
 *
 * <span class="hljs-doctag">@param</span> &lt;T&gt; the type of the value contained in the {<span class="hljs-doctag">@link</span> OptionalProperty}
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">JsonOptionalPropertyDeserializer</span>&lt;<span class="hljs-title">T</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Serializable</span>&gt; <span class="hljs-keyword">extends</span> <span class="hljs-title">JsonDeserializer</span>&lt;<span class="hljs-title">OptionalProperty</span>&lt;<span class="hljs-title">T</span>&gt;&gt; <span class="hljs-keyword">implements</span> <span class="hljs-title">ContextualDeserializer</span> </span>{

    <span class="hljs-keyword">private</span> Class&lt;T&gt; valueClass;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> OptionalProperty&lt;T&gt; <span class="hljs-title">getNullValue</span><span class="hljs-params">(DeserializationContext ctxt)</span> </span>{
        <span class="hljs-keyword">return</span> OptionalProperty.of(<span class="hljs-keyword">null</span>);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Object <span class="hljs-title">getAbsentValue</span><span class="hljs-params">(DeserializationContext ctxt)</span> </span>{
        <span class="hljs-keyword">return</span> OptionalProperty.absent();
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> OptionalProperty&lt;T&gt; <span class="hljs-title">deserialize</span><span class="hljs-params">(JsonParser jsonParser, DeserializationContext deserializationContext)</span> <span class="hljs-keyword">throws</span> IOException </span>{
        T value = jsonParser.readValueAs(valueClass);
        <span class="hljs-keyword">return</span> OptionalProperty.of(value);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-keyword">public</span> JsonDeserializer&lt;?&gt; createContextual(DeserializationContext ctxt, BeanProperty property) <span class="hljs-keyword">throws</span> JsonMappingException {
        valueClass = (Class&lt;T&gt;) property.getType().getBindings().getBoundType(<span class="hljs-number">0</span>).getRawClass();
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>;
    }
}
</code></pre>
<h3 id="heading-explanation-of-the-custom-deserializer-code">Explanation of the Custom Deserializer Code</h3>
<p>The custom deserializer <code>JsonOptionalPropertyDeserializer</code> is designed to handle the deserialization of the <code>OptionalProperty</code> class, which can represent three states: present with a value, absent, and present with a <code>null</code> value. Here's a breakdown of how the deserializer works:</p>
<p><strong>Class Declaration and Generics</strong>:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">JsonOptionalPropertyDeserializer</span>&lt;<span class="hljs-title">T</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Serializable</span>&gt; <span class="hljs-keyword">extends</span> <span class="hljs-title">JsonDeserializer</span>&lt;<span class="hljs-title">OptionalProperty</span>&lt;<span class="hljs-title">T</span>&gt;&gt; <span class="hljs-keyword">implements</span> <span class="hljs-title">ContextualDeserializer</span> </span>{
</code></pre>
<p><strong>Handling Null Values</strong>:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> OptionalProperty&lt;T&gt; <span class="hljs-title">getNullValue</span><span class="hljs-params">(DeserializationContext ctxt)</span> </span>{
    <span class="hljs-keyword">return</span> OptionalProperty.of(<span class="hljs-keyword">null</span>);
}
</code></pre>
<p>This method is called when the JSON value is explicitly <code>null</code>. It returns an <code>OptionalProperty</code> instance with a <code>null</code> value.</p>
<p><strong>Handling Absent Values</strong>:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> Object <span class="hljs-title">getAbsentValue</span><span class="hljs-params">(DeserializationContext ctxt)</span> </span>{
    <span class="hljs-keyword">return</span> OptionalProperty.absent();
}
</code></pre>
<p>This method is called when the JSON value is absent. It returns an absent <code>OptionalProperty</code> instance.</p>
<p><strong>Deserializing JSON Values</strong>:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> OptionalProperty&lt;T&gt; <span class="hljs-title">deserialize</span><span class="hljs-params">(JsonParser jsonParser, DeserializationContext deserializationContext)</span> <span class="hljs-keyword">throws</span> IOException </span>{
    T value = jsonParser.readValueAs(valueClass);
    <span class="hljs-keyword">return</span> OptionalProperty.of(value);
}
</code></pre>
<p>This method is called to deserialize a JSON value into an <code>OptionalProperty</code> instance. It reads the JSON value as an object of type <code>T</code> and returns an <code>OptionalProperty</code> containing the deserialized object.</p>
<p><strong>Creating Contextual Deserializer</strong>:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Override</span>
<span class="hljs-keyword">public</span> JsonDeserializer&lt;?&gt; createContextual(DeserializationContext ctxt, BeanProperty property) <span class="hljs-keyword">throws</span> JsonMappingException {
    valueClass = (Class&lt;T&gt;) property.getType().getBindings().getBoundType(<span class="hljs-number">0</span>).getRawClass();
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>;
}
</code></pre>
<p>This method is called to create a contextual deserializer. It retrieves the class of the generic type <code>T</code> from the property's type and stores it in the <code>valueClass</code> field for later use in deserialization.</p>
<p>By implementing these methods, the <code>JsonOptionalPropertyDeserializer</code> ensures that the <code>OptionalProperty</code> class can correctly handle the three states of a property during deserialization: present with a value, absent, and present with a <code>null</code> value. This allows for more precise control over the handling of optional properties in your Java REST API.</p>
<h3 id="heading-using-the-custom-deserializer">Using the Custom Deserializer</h3>
<p>Finally, we use the custom deserializer in a DTO class to handle the <code>OptionalProperty</code>.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> com.fasterxml.jackson.databind.annotation.JsonDeserialize;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyDTO</span> </span>{

    <span class="hljs-meta">@JsonDeserialize(using = JsonOptionalPropertyDeserializer.class)</span>
    <span class="hljs-keyword">private</span> OptionalProperty&lt;Long&gt; identifier;

    <span class="hljs-function"><span class="hljs-keyword">public</span> OptionalProperty&lt;Long&gt; <span class="hljs-title">getIdentifier</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> identifier;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setIdentifier</span><span class="hljs-params">(OptionalProperty&lt;Long&gt; identifier)</span> </span>{
        <span class="hljs-keyword">this</span>.identifier = identifier;
    }
}
</code></pre>
<h3 id="heading-complete-controller-class-with-business-logic">Complete Controller Class with Business Logic</h3>
<p>Here is a comprehensive controller class that includes the business logic for processing <code>MyDTO</code> using the custom deserializer. This controller will handle incoming POST requests, process the <code>identifier</code> property, and output the results based on its state.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> org.springframework.web.bind.annotation.PostMapping;
<span class="hljs-keyword">import</span> org.springframework.web.bind.annotation.RequestBody;
<span class="hljs-keyword">import</span> org.springframework.web.bind.annotation.RequestMapping;
<span class="hljs-keyword">import</span> org.springframework.web.bind.annotation.RestController;
<span class="hljs-keyword">import</span> com.fasterxml.jackson.databind.annotation.JsonDeserialize;

<span class="hljs-meta">@RestController</span>
<span class="hljs-meta">@RequestMapping("/api")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyController</span> </span>{

    <span class="hljs-meta">@PostMapping("/process")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">processMyDTO</span><span class="hljs-params">(<span class="hljs-meta">@RequestBody</span> MyDTO myDTO)</span> </span>{
        <span class="hljs-comment">// Check if identifier is present</span>
        <span class="hljs-keyword">if</span> (myDTO.getIdentifier().isPresent()) {
            <span class="hljs-comment">// Check if the identifier is not null</span>
            myDTO.getIdentifier().ifPresentAndNotNull(value -&gt; {
                <span class="hljs-comment">// Business logic for when the identifier is present and not null</span>
                System.out.println(<span class="hljs-string">"Identifier is present and not null: "</span> + value);
                <span class="hljs-comment">// Additional processing logic here</span>
            });

            <span class="hljs-comment">// If the identifier is present but null</span>
            <span class="hljs-keyword">if</span> (myDTO.getIdentifier().orElseNull() == <span class="hljs-keyword">null</span>) {
                System.out.println(<span class="hljs-string">"Identifier is present but null"</span>);
                <span class="hljs-comment">// Business logic for when the identifier is explicitly set to null</span>
                <span class="hljs-comment">// Additional processing logic here</span>
            }
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-comment">// If the identifier is absent</span>
            System.out.println(<span class="hljs-string">"Identifier is absent"</span>);
            <span class="hljs-comment">// Business logic for when the identifier is absent</span>
            <span class="hljs-comment">// Additional processing logic here</span>
        }
    }
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>By using a custom Jackson deserializer, we can effectively distinguish between absent properties, properties explicitly set to <code>null</code>, and properties with a non-null value in our REST API requests. This approach ensures backward compatibility with older clients while providing the flexibility to handle new requirements. The <code>OptionalProperty</code> wrapper and custom deserializer provide a robust solution for managing optional properties in Java applications using Spring and Jackson.</p>
<p>Feel free to incorporate this solution into your projects and adapt it to fit your specific needs. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Transferring data from one Kafka Broker to Another Using kcat]]></title><description><![CDATA[Learn efficient Kafka data migration using kcat! Transfer data between brokers effortlessly. Perfect for small datasets and development environments.]]></description><link>https://marceloresende.dev/transferring-data-from-one-kafka-broker-to-another-using-kcat</link><guid isPermaLink="true">https://marceloresende.dev/transferring-data-from-one-kafka-broker-to-another-using-kcat</guid><category><![CDATA[kafka]]></category><category><![CDATA[terminal]]></category><category><![CDATA[shell script]]></category><dc:creator><![CDATA[Marcelo Paixão Resende]]></dc:creator><pubDate>Fri, 27 Oct 2023 16:00:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1698381877292/91cdf8ed-c6ce-464c-9ef0-5e4836c98988.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You've decided to migrate your Kafka data to another broker and need an efficient, straightforward solution.</p>
<p>In this guide, we will explore how to use kcat, a powerful and flexible Kafka data manipulation tool, to transfer data from one broker to another.</p>
<p>This method is particularly useful when you need a simple way to move <strong>small amounts of data</strong> from one broker to another.</p>
<p>In my case, I used this approach to transfer data between my development server and my local Kafka server.</p>
<h2 id="heading-when-to-use-the-kcat-approach"><strong>When to use the kcat Approach</strong></h2>
<ul>
<li><p><strong>Simple and Fast Transfer:</strong> For moving <strong>small datasets</strong> between brokers.</p>
</li>
<li><p><strong>Development Environments:</strong> Ideal for development environments where simplicity and time-saving solutions are valuable.</p>
</li>
</ul>
<h2 id="heading-installing-kcat"><strong>Installing kcat</strong></h2>
<p>Before you begin, make sure you have kcat installed on your system. You can install it using a package manager, such as Homebrew for macOS or apt-get for Debian/Ubuntu-based systems.</p>
<pre><code class="lang-sh">brew install kafkacat   <span class="hljs-comment"># For macOS using Homebrew</span>
<span class="hljs-comment"># OR</span>
sudo apt-get install kafkacat   <span class="hljs-comment"># For Debian/Ubuntu-based systems</span>
</code></pre>
<h2 id="heading-transferring-an-entire-topic"><strong>Transferring an Entire Topic</strong></h2>
<p>We can use kcat in producer mode, where it is used to send messages to a specific topic in Kafka. In consumer mode, we can consume messages and print them in the terminal. Our simple trick is redirecting the output of the <code>kcat</code> command in consumer mode to the <code>kcat</code> command in producer mode. In other words, the messages received by the first command will be sent to the second command.</p>
<p>See the script below with the necessary commands and details:</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/usr/bin/env bash</span>
<span class="hljs-comment"># Defining the source and target brokers, as well as the corresponding topics.</span>
SOURCE_BROKER=source_host_or_ip:9092
SOURCE_TOPIC=topic
TARGET_BROKER=target_host_or_ip:9092
TARGET_TOPIC=topic

<span class="hljs-comment"># Using kcat to consume messages from the source broker and produce them to the target broker.</span>
<span class="hljs-comment"># -C: Consumer mode</span>
<span class="hljs-comment"># -P: Producer mode</span>
<span class="hljs-comment"># -b: Specifies the broker to be used</span>
<span class="hljs-comment"># -t: Specifies the topic to be consumed or produced</span>
<span class="hljs-comment"># -o beginning: Reads messages from the beginning of the topic</span>
<span class="hljs-comment"># -K: Sets the delimiter between the key and value of messages</span>
<span class="hljs-comment"># -e: Exits the command after receiving the last available message</span>
<span class="hljs-comment"># | : Pipe, redirects the output from the first command to the second.</span>

<span class="hljs-comment"># Consuming messages from the source broker and producing them to the target broker using kcat.</span>
kcat -C -b <span class="hljs-variable">$SOURCE_BROKER</span> -t <span class="hljs-variable">$SOURCE_TOPIC</span> -o beginning -K: -e | \
    kcat -b <span class="hljs-variable">$TARGET_BROKER</span> -P -t <span class="hljs-variable">$TARGET_TOPIC</span> -K:
</code></pre>
<h2 id="heading-transferring-messages-created-within-a-specific-date-and-time-range"><strong>Transferring Messages Created within a Specific Date and Time Range</strong></h2>
<p>We can also transfer only part of a topic with different options. In the code below, we will transfer only messages created between 10 AM and 8 PM on a specific day.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/usr/bin/env bash</span>
<span class="hljs-comment"># Defining the source and target brokers, as well as the corresponding topics.</span>
SOURCE_BROKER=source_host_or_ip:9092
SOURCE_TOPIC=topic
TARGET_BROKER=target_host_or_ip:9092
TARGET_TOPIC=topic
START_TIMESTAMP=$(date -d <span class="hljs-string">'2023-10-25 10:00:00 -03'</span> +%s000)
END_TIMESTAMP=$(date -d <span class="hljs-string">'2023-10-25 20:00:00 -03'</span> +%s000)

<span class="hljs-comment"># We replace -o beginning with -o s@$START_TIMESTAMP -o e@$END_TIMESTAMP, where each one is a timestamp like -o s@1568276612443 -o e@1568276617901</span>
kcat -C -b <span class="hljs-variable">$SOURCE_BROKER</span> -t <span class="hljs-variable">$SOURCE_TOPIC</span> -o s@<span class="hljs-variable">$START_TIMESTAMP</span> -o e@<span class="hljs-variable">$END_TIMESTAMP</span> -K: -e | \
    kcat -b <span class="hljs-variable">$TARGET_BROKER</span> -P -t <span class="hljs-variable">$TARGET_TOPIC</span> -K:
</code></pre>
<h2 id="heading-filtering-data"><strong>Filtering Data</strong></h2>
<p>If your messages are <strong>not in binary format</strong>, you can filter them by any string before sending them to the target broker.</p>
<p><strong>Please note:</strong> You will still be fetching all messages, and the filtering will occur on your machine.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/usr/bin/env bash</span>
<span class="hljs-comment"># Defining the source and target brokers, as well as the corresponding topics.</span>
SOURCE_BROKER=source_host_or_ip:9092
SOURCE_TOPIC=topic
TARGET_BROKER=target_host_or_ip:9092
TARGET_TOPIC=topic
FILTER_STRING=some_string

kcat -C -b <span class="hljs-variable">$SOURCE_BROKER</span> -t <span class="hljs-variable">$SOURCE_TOPIC</span> -o beginning -K: -e | \
    grep <span class="hljs-variable">$FILTER_STRING</span> | \
    kcat -b <span class="hljs-variable">$TARGET_BROKER</span> -P -t <span class="hljs-variable">$TARGET_TOPIC</span> -K:
</code></pre>
<p>Please note that we added the <code>grep</code> utility, which will receive the messages from the first command, filter only those containing the desired string, and send them to the third command.</p>
<h2 id="heading-bonus-searching-for-a-message-in-kafka"><strong>Bonus: Searching for a Message in Kafka</strong></h2>
<p>We can use the above command to search for a message by removing the producer command:</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/usr/bin/env bash</span>
<span class="hljs-comment"># Defining the source broker and topic, as well as the filter string.</span>
SOURCE_BROKER=source_host_or_ip:909

2
SOURCE_TOPIC=topic
FILTER_STRING=some_string

kcat -C -b <span class="hljs-variable">$SOURCE_BROKER</span> -t <span class="hljs-variable">$SOURCE_TOPIC</span> -o beginning -K: -e | \
    grep <span class="hljs-variable">$FILTER_STRING</span>
</code></pre>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>In this guide, we explored an efficient and straightforward way to transfer <strong>small amounts of data</strong> from one Kafka broker to another using the powerful tool kcat. By following the provided examples, you've learned how to migrate data simply between Kafka brokers, whether by transferring an entire topic, filtering messages by time intervals, or specific keywords.</p>
<p>It's crucial to highlight that this approach is more suitable for transferring smaller datasets or when you need a quick solution in a development environment. If you're dealing with large volumes of data or in a production environment, it's advisable to consider other transfer strategies, such as using replication tools or more robust data pipelines, to ensure efficiency and security during migration.</p>
<p>We hope this guide has been helpful for your Kafka broker data transfer needs.</p>
]]></content:encoded></item><item><title><![CDATA[ElasticSearch: Pagination by document creation date]]></title><description><![CDATA[It's been a while. Kept you waiting, huh? Pagination is not an easy task. There are a lot of implementations that are simply wrong, returning pages missing…]]></description><link>https://marceloresende.dev/elasticsearch-pagination-by-document-creation-date</link><guid isPermaLink="true">https://marceloresende.dev/elasticsearch-pagination-by-document-creation-date</guid><category><![CDATA[elasticsearch]]></category><category><![CDATA[Pagination]]></category><dc:creator><![CDATA[Marcelo Paixão Resende]]></dc:creator><pubDate>Sun, 21 Jan 2018 02:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1698381756161/6c6128bc-180e-4a16-b9ca-dee57b290ecb.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>It's been a while. Kept you waiting, huh?</p>
<p>Pagination is not an easy task. There are a lot of implementations that are simply wrong, returning pages missing entries when there's insertion/updates between queries or sufferring from serious performance issues.</p>
<p>With ElasticSearch, we have multiple ways of implementing pagination. The <a target="_blank" href="https://www.elastic.co/guide/en/elasticsearch/reference/5.5/search-request-scroll.html">Scroll API</a> is a good feature when you need to fetch multiple documents inside a task, but it won't save you when you need to work with pages in a stateless manner (maybe there's a front-end client consuming your api).</p>
<p>Real case: I needed to search for documents using a task that would run every N minutes. At the end of every search, I would save a "checkpoint", something indicating where I last stopped so that the next iteration could resume from it.</p>
<h2 id="heading-pagination-with-a-creation-date-field">Pagination with a "creation date" field</h2>
<p>Supposing we have the following documents stored in an index:</p>
<pre><code class="lang-json">[
  {
    <span class="hljs-attr">"creationDate"</span>: <span class="hljs-string">"2018-01-21T19:51:42.840Z"</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Marcelo"</span>
  },
  {
    <span class="hljs-attr">"creationDate"</span>: <span class="hljs-string">"2018-01-21T19:51:42.840Z"</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Sarah"</span>
  },
  {
    <span class="hljs-attr">"creationDate"</span>: <span class="hljs-string">"2018-01-21T19:51:42.840Z"</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Yasmin"</span>
  },
  {
    <span class="hljs-attr">"creationDate"</span>: <span class="hljs-string">"2018-01-21T20:51:42.840Z"</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Julia"</span>
  },
  {
    <span class="hljs-attr">"creationDate"</span>: <span class="hljs-string">"2018-01-21T20:51:42.840Z"</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Nicolly"</span>
  }
]
</code></pre>
<p>In our example, we will search through these documents with a page size of <strong>2</strong>. We want to find all those <strong>5</strong> documents, ordered by their creation date, meaning that when new documents are inserted we can fetch only the new ones.</p>
<h3 id="heading-episode-1-the-naive-approach">Episode 1: The naïve approach</h3>
<p>We can structure our query in a way that documents are ordered by their <code>creationDate</code> and for every iteration we would store the <strong>last</strong> document <code>creationDate</code>. This is what our query will look like (with the GET /my_index/_search ommitted):</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"size"</span>: <span class="hljs-number">2</span>,
  <span class="hljs-attr">"query"</span>: {
    <span class="hljs-attr">"range"</span>: {
      <span class="hljs-attr">"_name"</span>: <span class="hljs-string">"This block won't be present in the first page request (since we don't have the last creationDate reference!)"</span>,
      <span class="hljs-attr">"creationDate"</span>: {
        <span class="hljs-attr">"gt"</span>: <span class="hljs-string">"2018-01-21T19:51:42.840Z"</span>
      }
    }
  },
  <span class="hljs-attr">"sort"</span>: [
    {
      <span class="hljs-attr">"creationDate"</span>: {
        <span class="hljs-attr">"order"</span>: <span class="hljs-string">"asc"</span>
      }
    }
  ]
}
</code></pre>
<p>And this is the result after 3 iterations/pages (only _source included, the other metadata is not needed for now):</p>
<pre><code class="lang-json">[{
  <span class="hljs-attr">"_source"</span>: {
    <span class="hljs-attr">"creationDate"</span>: <span class="hljs-string">"2018-01-21T19:51:42.840Z"</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Sarah"</span>
  }
}, {
  <span class="hljs-attr">"_source"</span>: {
    <span class="hljs-attr">"creationDate"</span>: <span class="hljs-string">"2018-01-21T19:51:42.840Z"</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Marcelo"</span>
  }
}, {
  <span class="hljs-attr">"_source"</span>: {
    <span class="hljs-attr">"creationDate"</span>: <span class="hljs-string">"2018-01-21T20:51:42.840Z"</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Julia"</span>
  }
}, {
  <span class="hljs-attr">"_source"</span>: {
    <span class="hljs-attr">"creationDate"</span>: <span class="hljs-string">"2018-01-21T20:51:42.840Z"</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Nicolly"</span>
  }
}]
</code></pre>
<p>We only got 4 results!</p>
<p>Where is <strong>Yasmin</strong>?</p>
<p>Turns out that after we got <strong>Sarah</strong> and <strong>Marcelo</strong>, our next query asked for a page with 2 results returning documents created after the first query's last document (<strong>Marcelo</strong>) with a <code>creationDate</code> greater than "2018-01-21T19:51:42.840Z".</p>
<p>The problem: Yasmin was also created in that same instant.</p>
<p><strong>Documents created in the same instant makes this approach unpredictable and not always accurate.</strong></p>
<p><strong>Worse yet:</strong> The problem can persist for a long time before someone notice it, if they ever do.</p>
<h3 id="heading-episode-2-the-right-approach">Episode 2: The right approach</h3>
<p>Starting with version 5.0, ElasticSearch provides us a nice and realiable way to address this issue: the <a target="_blank" href="https://www.elastic.co/guide/en/elasticsearch/reference/5.0/search-request-search-after.html">Search After</a> parameter. Quoting the docs:</p>
<blockquote>
<p>The search_after parameter circumvents this problem by providing a live cursor. The idea is to use the results from the previous page to help the retrieval of the next page.</p>
</blockquote>
<p>and</p>
<blockquote>
<p>search_after is not a solution to jump freely to a random page but rather to scroll many queries in parallel. It is very similar to the scroll API but unlike it, the search_after parameter is stateless, it is always resolved against the latest version of the searcher.</p>
</blockquote>
<p>We can change the sort in out last query to include the <a target="_blank" href="https://www.elastic.co/guide/en/elasticsearch/reference/5.0/mapping-uid-field.html">_uid</a> field, unique to every document in that specific index.</p>
<p>Then, starting from the first query, we must include a search_after parameter that will include the <strong>creationDate</strong> and <strong>_uid</strong> from the last document in the previous query. Those values are returned with every match in the <code>sort</code> block:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"_source"</span>: {
    <span class="hljs-attr">"creationDate"</span>: <span class="hljs-string">"2018-01-21T20:51:42.840Z"</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Julia"</span>
  },
  <span class="hljs-attr">"sort"</span>: [
    <span class="hljs-number">1516564302840</span>,
    <span class="hljs-string">"type#AWEagzSzwHnysW-7Ulq9"</span>
  ]
}
</code></pre>
<p>So, when finding all documents created after <strong>Julia</strong>, we would use the following query:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"size"</span>: <span class="hljs-number">2</span>,
  <span class="hljs-attr">"search_after"</span>: [
    <span class="hljs-number">1516564302840</span>,
    <span class="hljs-string">"type#AWEagzSzwHnysW-7Ulq9"</span>
  ],
  <span class="hljs-attr">"sort"</span>: [
    {
      <span class="hljs-attr">"creationDate"</span>: {
        <span class="hljs-attr">"order"</span>: <span class="hljs-string">"asc"</span>
      }
    },
    {
      <span class="hljs-attr">"_uid"</span>: {
        <span class="hljs-attr">"order"</span>: <span class="hljs-string">"asc"</span>
      }
    }
  ]
}
</code></pre>
<p><strong>That way we can assure that we can find all the current 5 documents and all future documents that will be inserted.</strong></p>
<p>There's just one caveat: Our application <strong>must not</strong> insert documents with a <code>creationDate</code> lower than the last one.</p>
<h2 id="heading-other-dbms">Other DBMS</h2>
<p>This solution can also be "ported" to other DBMS easily.</p>
<p>For example, I found that solution when looking for a similar way that we used to do with <a target="_blank" href="https://couchdb.apache.org/">CouchDB</a> keys and views.</p>
<p>In this case, it is almost identical.</p>
<p>It would look like this with SQL databases when you are not using an auto-incremented primary key:</p>
<p>First page query:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">select</span>
    <span class="hljs-keyword">uuid</span>,
    creation_date
<span class="hljs-keyword">from</span>
    your_table
<span class="hljs-keyword">order</span> <span class="hljs-keyword">by</span>
    creation_date <span class="hljs-keyword">asc</span>,
    <span class="hljs-keyword">uuid</span> <span class="hljs-keyword">asc</span>
<span class="hljs-keyword">limit</span> <span class="hljs-number">10</span>
</code></pre>
<p>Second page query:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">select</span>
    <span class="hljs-keyword">uuid</span>,
    creation_date
<span class="hljs-keyword">from</span>
    your_table
<span class="hljs-keyword">where</span>
  <span class="hljs-comment">-- the document is indeed created later than the last one</span>
    creation_date &gt; :last_page_row_creation_date
  <span class="hljs-comment">-- OR it was created at the same time, but wasn't included in the last page because of it's limit clause</span>
        <span class="hljs-keyword">or</span> creation_date = :last_page_row_creation_date <span class="hljs-keyword">and</span> <span class="hljs-keyword">uuid</span> &gt; :last_page_row_uuid
<span class="hljs-keyword">order</span> <span class="hljs-keyword">by</span>
    creation_date <span class="hljs-keyword">asc</span>,
    <span class="hljs-keyword">uuid</span> <span class="hljs-keyword">asc</span>
<span class="hljs-keyword">limit</span> <span class="hljs-number">10</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This is a safe way of implementing pagination using ElasticSearch when we plan to iterate through the results in a stateless manner. It is much valuable when using ElasticSearch with endlessy running tasks or when it is used as your primary database.</p>
<p>Good luck!</p>
]]></content:encoded></item><item><title><![CDATA[JPA Criteria: Invalid SQL with IN predicate]]></title><description><![CDATA[JPA Criteria is awesome when you need to compose complex queries from multiple blocks, but it can cause a lot of troubles when the underlying SQL code…]]></description><link>https://marceloresende.dev/jpa-criteria-invalid-sql-with-in-predicate</link><guid isPermaLink="true">https://marceloresende.dev/jpa-criteria-invalid-sql-with-in-predicate</guid><category><![CDATA[Java]]></category><category><![CDATA[jpa]]></category><category><![CDATA[hibernate]]></category><category><![CDATA[criteria]]></category><dc:creator><![CDATA[Marcelo Paixão Resende]]></dc:creator><pubDate>Mon, 11 Sep 2017 03:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1698509214610/b4069c21-1b56-4ffc-a2c3-b522e43e79f9.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>JPA Criteria is awesome when you need to compose complex queries from multiple blocks, but it can cause a lot of troubles when the underlying SQL code fails to check some obvious scenarios.</p>
<h2 id="heading-the-concept">The concept</h2>
<p>When dealing with Java <code>List</code>s, we can almost always assume (if written correctly) that code will work as expected with empty lists if we respect the contract (don't pass <code>null</code> as a parameter!).</p>
<p>Imagine the following code:</p>
<pre><code class="lang-java"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> List&lt;Person&gt; persons = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();

<span class="hljs-keyword">static</span> {
    persons.add(<span class="hljs-keyword">new</span> Person(<span class="hljs-number">1L</span>));
    persons.add(<span class="hljs-keyword">new</span> Person(<span class="hljs-number">2L</span>));
    persons.add(<span class="hljs-keyword">new</span> Person(<span class="hljs-number">3L</span>));
}

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
    List&lt;Person&gt; personsQueryOne = findPersonsByIds(Arrays.asList(<span class="hljs-number">1L</span>, <span class="hljs-number">2L</span>));
    System.out.println(personsQueryOne);
    List&lt;Person&gt; personsQueryTwo = findPersonsByIds(Arrays.asList());
    System.out.println(personsQueryTwo);
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> List&lt;Person&gt; <span class="hljs-title">findPersonsByIds</span><span class="hljs-params">(List&lt;Long&gt; idsList)</span> </span>{
    <span class="hljs-keyword">return</span> persons.stream().filter(person -&gt; idsList.contains(person.getId())).collect(Collectors.toList());
}
</code></pre>
<p>We have:</p>
<ul>
<li><p>A static list of persons;</p>
</li>
<li><p>A method that searches the list of persons when provided with a list of ids.</p>
</li>
</ul>
<p>This is the console output:</p>
<pre><code class="lang-plaintext">[Person [id=1], Person [id=2]]
[]
</code></pre>
<p>Nothing special, right? If we pass an empty list of ids, the method won't have anything to search for!</p>
<h2 id="heading-the-problem">The problem</h2>
<p>Now, lets imagine the same kind of situation, but working with:</p>
<ul>
<li><p>JPA 2.1 with Criteria;</p>
</li>
<li><p>Hibernate as JPA provider;</p>
</li>
<li><p>Postgres as database.</p>
</li>
</ul>
<p>The following query should search for the <code>Person</code> entity that matches a list of ids (but we are bad boys and provided an empty <code>List</code>):</p>
<pre><code class="lang-java">CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery&lt;MyEntity&gt; criteriaQuery = criteriaBuilder.createQuery(MyEntity.class);
Root&lt;MyEntity&gt; myEntity = criteriaQuery.from(MyEntity.class);
Predicate inPredicate = myEntity.in(<span class="hljs-keyword">new</span> ArrayList&lt;&gt;()); <span class="hljs-comment">// an empty arraylist!</span>
criteriaQuery.where(inPredicate);
TypedQuery&lt;MyEntity&gt; typedQuery = entityManager.createQuery(criteriaQuery);
typedQuery.getResultList();
</code></pre>
<p>The call to <code>typedQuery.getResultList()</code> should return an empty resultset. The generated SQL is (attention to the where clause):</p>
<pre><code class="lang-sql"><span class="hljs-keyword">select</span>
    person0_.id <span class="hljs-keyword">as</span> id1_0_,
    person0_.name <span class="hljs-keyword">as</span> name2_0_,
    person0_.type <span class="hljs-keyword">as</span> type3_0_
<span class="hljs-keyword">from</span>
    person person0_
<span class="hljs-keyword">where</span>
    person0_.id <span class="hljs-keyword">in</span>()
</code></pre>
<p>And the execution causes:</p>
<pre><code class="lang-plaintext">javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
...
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near ")"
  Posição: 127
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2477)
    ...
</code></pre>
<p>Indeed, the generated SQL is invalid. One of the approaches (and the most performatic one) would be to check for empty <code>List</code>s all the time, but we may end up with a lot of boilerplate code.</p>
<h2 id="heading-solutions">Solution(s)</h2>
<p>We can solve this problem with creative ways, and I came up with two, depending on the situation.</p>
<h3 id="heading-1-create-your-own-in-method-or-utility">#1 - Create your own IN method or utility</h3>
<p>This one is easy: instead of using <code>Expression#in(Collection)</code>, we can create a method that will handle the empty collection case for us, returning a <code>Predicate</code>:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">private</span> Predicate <span class="hljs-title">in</span><span class="hljs-params">(Expression&lt;?&gt; entityValue, Collection&lt;?&gt; valuesToMatch)</span> </span>{
    <span class="hljs-keyword">if</span> (valuesToMatch == <span class="hljs-keyword">null</span> || valuesToMatch.isEmpty()) {
        <span class="hljs-keyword">return</span> falsyCondition();
    }
    <span class="hljs-keyword">return</span> entityValue.in(valuesToMatch);
}

<span class="hljs-function"><span class="hljs-keyword">private</span> Predicate <span class="hljs-title">falsyCondition</span><span class="hljs-params">()</span> </span>{
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    <span class="hljs-keyword">return</span> criteriaBuilder.isTrue(criteriaBuilder.literal(<span class="hljs-keyword">false</span>));
}
</code></pre>
<p>What's happenning here: If <code>List.isEmpty() == true</code>, we return an condition that is <strong>always</strong> false. In this case: <code>true=false</code>.</p>
<p>Here's the relevant part using this code:</p>
<pre><code class="lang-java">Predicate inPredicate = in(personEntity, <span class="hljs-keyword">new</span> ArrayList&lt;&gt;());
criteriaQuery.where(inPredicate);
List&lt;Person&gt; result = entityManager.createQuery(criteriaQuery).getResultList();
</code></pre>
<p>And here is the generated SQL (? is a placeholder for <code>false</code>):</p>
<pre><code class="lang-sql"><span class="hljs-keyword">select</span>
    person0_.id <span class="hljs-keyword">as</span> id1_0_,
    person0_.name <span class="hljs-keyword">as</span> name2_0_,
    person0_.type <span class="hljs-keyword">as</span> type3_0_
<span class="hljs-keyword">from</span>
    person person0_
<span class="hljs-keyword">where</span>
    ?= <span class="hljs-literal">true</span>
</code></pre>
<p>No more exceptions!</p>
<h3 id="heading-2-decorator-pattern">#2 - Decorator pattern</h3>
<p>The solution #1 is great when you have something like a <code>AbstractRepository</code> or <code>AbstractDAO</code> that you can put the created reusable method. But when that's not an option, we can come up with a <code>Decorator</code> that will only be applied to the <code>Path</code> or <code>Expression</code> that we are checking for matches in the list.</p>
<p>First, a new class must be created:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SafeInDecorator</span>&lt;<span class="hljs-title">T</span>&gt; <span class="hljs-keyword">implements</span> <span class="hljs-title">Expression</span>&lt;<span class="hljs-title">T</span>&gt; </span>{
    <span class="hljs-keyword">private</span> CriteriaBuilder criteriaBuilder;
    <span class="hljs-keyword">private</span> Expression&lt;T&gt; decorated;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">SafeInDecorator</span><span class="hljs-params">(CriteriaBuilder criteriaBuilder, Expression&lt;T&gt; decorated)</span> </span>{
        <span class="hljs-keyword">this</span>.criteriaBuilder = criteriaBuilder;
        <span class="hljs-keyword">this</span>.decorated = decorated;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Predicate <span class="hljs-title">in</span><span class="hljs-params">(Collection&lt;?&gt; values)</span> </span>{
        <span class="hljs-keyword">if</span> (values.isEmpty()) {
            <span class="hljs-keyword">return</span> falsyCondition();
        }
        <span class="hljs-keyword">return</span> decorated.in(values);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Predicate <span class="hljs-title">in</span><span class="hljs-params">(Object... values)</span> </span>{
        <span class="hljs-keyword">return</span> in(Arrays.asList(values));
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> Predicate <span class="hljs-title">falsyCondition</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> criteriaBuilder.isTrue(criteriaBuilder.literal(<span class="hljs-keyword">false</span>));
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Predicate <span class="hljs-title">isNull</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> decorated.isNull();
    }

  <span class="hljs-comment">/** all other methods must be implemented delegating to the decorated object **/</span>
}
</code></pre>
<p>Then we can decorate the entity <code>Path</code> object and use the <code>#in(Collection)</code> method that adheres to our contract:</p>
<pre><code class="lang-java">Root&lt;Person&gt; personEntity = criteriaQuery.from(Person.class);
Expression&lt;Person&gt; personDecorated = <span class="hljs-keyword">new</span> SafeInDecorator&lt;&gt;(criteriaBuilder, personEntity);
Predicate inPredicate = personDecorated.in(<span class="hljs-keyword">new</span> ArrayList&lt;&gt;());
</code></pre>
<p>No more exceptions!²</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In the end, you should pick the option that suits better your project's situation.</p>
<p>It would be nice to have the <strong>#1</strong> solution in an <code>AbstractRepository</code> where it can be reused in subclasses. But if this problem was discovered when that's not an option, the <strong>#2</strong> solution also solves the problem and is less intrusive to the class hierarchy.</p>
<p>Which one to choose is up to you!</p>
]]></content:encoded></item><item><title><![CDATA[Yet another technology blog]]></title><description><![CDATA[My name is Marcelo and I'm a software developer currently living in Uberlândia, Brazil. I've been developing software for fun since i was fifteen. A few…]]></description><link>https://marceloresende.dev/yet-another-technology-blog</link><guid isPermaLink="true">https://marceloresende.dev/yet-another-technology-blog</guid><dc:creator><![CDATA[Marcelo Paixão Resende]]></dc:creator><pubDate>Sun, 10 Sep 2017 14:09:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1698510466590/d8bd128d-12a7-43e1-9f3c-e183d6b7afeb.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>My name is Marcelo and I'm a software developer currently living in <a target="_blank" href="https://en.wikipedia.org/wiki/Uberl%C3%A2ndia">Uberlândia, Brazil</a>.</p>
<p>I've been developing software for fun since i was fifteen. A few years later, I realized that programming was something that I already had been doing with a quality that could be used professionally, and then I started working in the industry.</p>
<p>Throughout the years I had contact with <strong>Perl</strong>, <strong>C#</strong>, <strong>C++</strong>, <strong>Java</strong> and <strong>Javascript</strong> (Client &amp; Server-side). Today I work heavily with <strong>Java</strong> and <strong>Javascript</strong> enterprisely. Currently I'm anxious to have some fun with Typescript (Angular) and Kotlin.</p>
<p>I've been flirting with the idea of creating a blog for too long, but time had been crushing my dreams. I hope this introduction to be just the front page to a lot of useful and interesting posts.</p>
]]></content:encoded></item></channel></rss>