<?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[Utopian Nerd]]></title><description><![CDATA[Concepts and Stories from the field of Software Development and Engineering]]></description><link>https://tech.anshulgautam.in</link><generator>RSS for Node</generator><lastBuildDate>Sun, 15 Nov 2026 21:44:46 GMT</lastBuildDate><atom:link href="https://tech.anshulgautam.in/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Distributed Tracing with Spring Boot Jaeger - Part 3]]></title><description><![CDATA[This is going to be the final part in the Distributed Tracing series using Jaeger in a Spring Boot application. So far, we covered overview on Distributed…]]></description><link>https://tech.anshulgautam.in/distributed-tracing-with-spring-boot-jaeger-part-3</link><guid isPermaLink="true">https://tech.anshulgautam.in/distributed-tracing-with-spring-boot-jaeger-part-3</guid><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[distributed system]]></category><dc:creator><![CDATA[Anshul Gautam]]></dc:creator><pubDate>Mon, 23 May 2022 08:09:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1653293294606/ctfO5ewQH.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This is going to be the final part in the Distributed Tracing series using Jaeger in a Spring Boot application.
So far, we covered overview on Distributed Tracing and how we can integrate tracing using Jaeger in our Spring Boot applications.
If you are coming to this post directly, I will urge you to go through the previous parts on this topic on this blog:</p>
<ul>
<li><a target="_blank" href="https://tech.anshulgautam.in/distributed-tracing-with-spring-boot-jaeger-part-1">Part 1</a></li>
<li><a target="_blank" href="https://tech.anshulgautam.in/distributed-tracing-with-spring-boot-jaeger-part-2">Part 2</a></li>
</ul>
<p>In this final part I will be wrapping up with the basic concepts that I had targeted to cover in the whole Distributed Tracing series.</p>
<h2 id="heading-what-happens-under-the-hood">🎯 What happens under the hood?</h2>
<p>In the sample applications that we had developed, we included a jaeger dependency. This instrumented our code for distributed tracing. The Jaeger UI is the tool, which we ran via the easiest way using Docker, collected the metrics and other data from our application code and gave that a meaning through visual representations in the UI.</p>
<p>So clearly as far distributed tracing is concerned, we have two key components involved here:</p>
<ul>
<li>The first component is the one which instrumented our code. Gathered information from our code and pushed to a destination.</li>
<li>The second component is the tracer UI which obtained data sent by the instrumentor piece and used that to represent transaction life span in its UI. We had used Jaeger UI for this.</li>
</ul>
<p>The first component here, the instrumentor piece, is an implementation of OpenTracing specification.</p>
<p>OpenTracing is a vendor neutral open standard for distributed tracing. It provides model and interfaces that will be used for instrumenting the code. We used Jaeger implementation for OpenTracing in our applications.</p>
<p>With this approach, we are not tied to a particular backend implementation. We can easily switch to another implementations.</p>
<p>But did we write any code specifically in our applications to instrument the code ourselves, like creating traces and span, and then push the context propagation further? The answer is no, we did  not do that.</p>
<p>We could have controlled everything, from creating traces to individual spans and tie the parent child relationships, but all these were not required explicitly as we had used <code>opentracing-spring-jaeger-web-starter</code>.</p>
<p>This implementation does more than providing the mere implementation. It automatically creates traces and spans as the request executes in the pipeline. And like I mentioned in <a target="_blank" href="https://tech.anshulgautam.in/distributed-tracing-with-spring-boot-jaeger-part-2">part 2</a> as well, the Jaeger implementation here is:</p>
<ul>
<li>Instrumenting the code</li>
<li>Intercepting the service calls that happen from their host application and insert proper header information. </li>
<li>Passing the updated header to the next service call in the pipeline as part of context propagation.</li>
<li>During service calls, it extracts the information from header and process it, and then after updating the header passes on to the next service call in the pipeline.</li>
</ul>
<p>Well yes, <code>opentracing-spring-jaeger-web-starter</code> does this all on its own by default.</p>
<p>But what if we need to manually trigger the creating of trace, and add spans to it?</p>
<h2 id="heading-creating-tracing-information-manually">🎯 Creating tracing information manually</h2>
<p>So in case of service calls we understood that Jaeger implementation used here is smart enough to do the instrumentation on its own. But if the application needs to do something on its own, without invocation from any service calls, then how do we manage that?</p>
<p>For example, consider an application which offers set of web services to be used by different clients. And this application also needs to send heartbeat to a destination saying that its alive, every 1 minute. So this thing needs to be invoked without any service call. We will see and learn how can we add traces manually.</p>
<p>I am implementing this is <code>initiator-service</code>.</p>
<pre><code>package nerd.utopian.initiator.service;

<span class="hljs-keyword">import</span> io.opentracing.Span;
<span class="hljs-keyword">import</span> io.opentracing.Tracer;
<span class="hljs-keyword">import</span> org.slf4j.Logger;
<span class="hljs-keyword">import</span> org.slf4j.LoggerFactory;

<span class="hljs-keyword">import</span> java.util.TimerTask;

public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">IAmAliveTimerTask</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">TimerTask</span> </span>{

    private <span class="hljs-keyword">static</span> final Logger LOGGER = LoggerFactory.getLogger(IAmAliveTimerTask.class);

    private Tracer tracer;

    public IAmAliveTimerTask(Tracer tracer) {
        <span class="hljs-built_in">this</span>.tracer = tracer;
    }

    @Override
    public <span class="hljs-keyword">void</span> run() {

        <span class="hljs-comment">// creating a new span.</span>
        Span span = tracer.buildSpan(<span class="hljs-string">"iam-alive"</span>).start();

        <span class="hljs-comment">// marking the span as child of...</span>
        Span activeSpan = tracer.buildSpan(<span class="hljs-string">"iam-alive-call"</span>).asChildOf(span).start();

        LOGGER.info(<span class="hljs-string">"initiator-service is alive"</span>);

        activeSpan.finish();
    }
}
</code></pre><p>I have used <code>TimerTask</code> for this example. Using <code>TimerTask</code> I have scheduled this service to run every 1 minute, and create a log entry mentioning that the service is alive.
I tied this custom TimerTask class to get triggered in a service class like below:</p>
<pre><code>package nerd.utopian.initiator.service;

<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> java.util.Objects.requireNonNull;

<span class="hljs-keyword">import</span> io.jaegertracing.internal.JaegerTracer;
<span class="hljs-keyword">import</span> java.util.Timer;
<span class="hljs-keyword">import</span> java.util.TimerTask;
<span class="hljs-keyword">import</span> javax.annotation.PostConstruct;
<span class="hljs-keyword">import</span> org.slf4j.Logger;
<span class="hljs-keyword">import</span> org.slf4j.LoggerFactory;
<span class="hljs-keyword">import</span> org.springframework.stereotype.Service;

@Service
public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">IAmAliveService</span> </span>{

  private <span class="hljs-keyword">static</span> final Logger LOGGER = LoggerFactory.getLogger(IAmAliveService.class);

  private JaegerTracer jaegerTracer;

  public IAmAliveService(JaegerTracer jaegerTracer) {
    <span class="hljs-built_in">this</span>.jaegerTracer = requireNonNull(jaegerTracer, <span class="hljs-string">"jaegerTracer is required but is missing"</span>);
  }

  @PostConstruct
  public <span class="hljs-keyword">void</span> isAliveService() {

    TimerTask timerTask = <span class="hljs-keyword">new</span> IAmAliveTimerTask(jaegerTracer);

    <span class="hljs-comment">// running timer task as daemon thread</span>
    Timer isAliveTimer = <span class="hljs-keyword">new</span> Timer(<span class="hljs-literal">true</span>);

    <span class="hljs-comment">// will execute every 1 minute.</span>
    isAliveTimer.scheduleAtFixedRate(timerTask, <span class="hljs-number">0</span>, <span class="hljs-number">60</span> * <span class="hljs-number">1000</span>);

    LOGGER.info(<span class="hljs-string">"isAliveService started..."</span>);
  }
}
</code></pre><p>Let's run the application and see what we are getting in the logs and in the Jaeger UI.</p>
<p><strong>Console:</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1653292229671/kSdgIYi8s.png" alt="image.png" /></p>
<p><strong>Jaeger UI:</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1653292342410/8N-AebB-q.png" alt="image.png" /></p>
<p>In this example I tried to show how can we create trace and add spans to it manually.</p>
<p>If we had to add trace information to header manually for context propagation, we would do something like below:</p>
<pre><code>Request.Builder requestBuilder = <span class="hljs-keyword">new</span> Request.Builder().url(serviceUrl);

tracer.inject(
    tracer.activeSpan().context(),
    Format.Builtin.HTTP_HEADERS,
    <span class="hljs-keyword">new</span> RequestBuilderCarrier(requestBuilder));
.
.
.
.
</code></pre><p>To extract the information from header in the next service call, we would do something like below:</p>
<pre><code>SpanContext parentContext = tracer.extract(Format.Builtin.HTTP_HEADERS, <span class="hljs-keyword">new</span> TextMapExtractAdapter(headers.toSingleValueMap()));
Span span = tracer.buildSpan(<span class="hljs-string">"orchestrator"</span>).asChildOf(parentContext).start();
</code></pre><h2 id="heading-ending-notes">🎯 Ending Notes</h2>
<p>I hope this post would have helped you in one way or the other. All the code changes that I did in this post are present at my GitHub <a target="_blank" href="https://github.com/anshulgammy/utopian-nerd/tree/main/usecases/spring-boot-jaeger-example">repository</a>.</p>
<p>If you have any suggestions for me, then please share that with me by commenting below.</p>
]]></content:encoded></item><item><title><![CDATA[The New Daily Driver Hunt is Difficult!]]></title><description><![CDATA[I remember of times back then when options were limited. There used to be a very small tuple of technical offerings which we would look into before making…]]></description><link>https://tech.anshulgautam.in/the-new-daily-driver-hunt-is-difficult</link><guid isPermaLink="true">https://tech.anshulgautam.in/the-new-daily-driver-hunt-is-difficult</guid><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[computer]]></category><dc:creator><![CDATA[Anshul Gautam]]></dc:creator><pubDate>Fri, 20 May 2022 18:19:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/j4uuKnN43_M/upload/v1653149168088/SsyQHH9M1.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I remember of times back then when options were limited. There used to be a very small tuple of technical offerings which we would look into before making that buying decision. Budget; of course it always took the hot prime seat, but considering the offerings that vehicle would bring in for me never made me ponder so much before I could start the journey. The life was peaceful, and technology advancement in the products were happily growing at ease. </p>
<p>Fast forward now, the budget again stays there occupying the hot prime seat. But with that the choices in technological intricacies are so huge that it makes me afraid. I get afraid of every buying decision. This is the fear of making a mistake which I might contemplate later. And hence most of the time I just delay or postpone indefinitely my decision to buy <em>'my next daily driver'</em>.</p>
<p>I imagine this as a situation wherein I am at a sea beach, which has a huge fleet of boats docked. I need to buy one and start my journey. Now I am very much confused which one to go with. I have the experience and an outline for my journey, but then there are also loads of incertitude on the journey ahead. Will my boat help me complete my journey? Or will it crumble midway? And may be who knows, the boat could fall apart just after I start my journey. I might need to get back to the shore, and make that difficult buy choice again.</p>
<p>This situation is weird. I know the boats are powerful, and every other one here at the dock are ahead and behind with one another by a very small margin. Yet they make my choice <em>'difficult'</em>.</p>
<h2 id="heading-but-i-made-a-decision">But I made a decision... 😎</h2>
<p>My new daily driver now is a Windows 10 laptop. It comes with AMD Ryzen 7, 5800H. It has Nvidia RTX 3050 dedicated graphics card. The RAM is at a sweet spot of 16 GB right now. And SSD is offering 512 GB of storage. The distinguishing aspect is the 14" screen which sits at 2.8 K of resolution, and it is an OLED display. 😊</p>
<p>I am a casual gamer as well. So there was an obvious impulsion in my head to have a Windows laptop. Linux distros are still not catching up well with gaming and Nvidia drivers support. Thus, a Windows laptop.</p>
<p>I was using a Macbook Air 2017 model to this date. The performance of this laptop to this date is still satisfactory. One thing which always saddened me was the screen quality. The company laptop that I use for my work has an amazing screen with very high nits of peak brightness. I love that display!
When I switch to my personal laptop, the Macbook Air, I feel it very difficult now to adjust my eyes on the screen. This triggered me to get a new personal laptop with a better display.</p>
<p>Once the churn to get a new laptop is ignited, how strange it is to see the dopamine bringing in even more reasons at place to go ahead, make a buy.</p>
<p>I waited. I waited a lot. I even earmarked my requirements in an excel and kept ticking/unticking them to make a solid decision. And if I have to go back to the golden days back then, and compare that to now, I will say that the <em>4 x 4</em> truth table has now turned into <em>16 x 16</em> truth table. Now, the different combinations together give rise to a lot of confusion. Narrowing them down slowly helps.</p>
<h2 id="heading-the-journey-with-the-new-daily-driver-has-started-positively">The journey with the new daily driver has started positively... ❤️</h2>
<p>I am writing this blog post with my new companion. I will be playing few games on Steam too. The download in enqueued.</p>
<p>And by the way, Windows 10 is much much better performant and stable than Windows 11. At least this is based on my personal observation with both these versions of Windows.</p>
]]></content:encoded></item><item><title><![CDATA[Using Liquibase to Manage Database States]]></title><description><![CDATA[As per the formal definitions, Liquibase is explained as: Liquibase is an open-source database-independent library for tracking, managing and applying…]]></description><link>https://tech.anshulgautam.in/using-liquibase-to-manage-database-states</link><guid isPermaLink="true">https://tech.anshulgautam.in/using-liquibase-to-manage-database-states</guid><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[Java]]></category><dc:creator><![CDATA[Anshul Gautam]]></dc:creator><pubDate>Thu, 19 May 2022 18:16:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1653156951964/-ATjXfCfI.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As per the formal definitions, Liquibase is explained as:</p>
<blockquote>
<p>Liquibase is an open-source database-independent library for tracking, managing and applying database schema changes. It works across various types of databases, and supports various file formats for defining the DB structure. The feature that is probably most attractive in Liquibase is its ability to roll changes back and forward from a specific point - saving you from the need to know what was the last change/script you ran on a specific DB instance.</p>
</blockquote>
<p>Key points to note here are:</p>
<ul>
<li><p><strong>Liquibase </strong>uses a changelog to explicitly list database changes in order. The changelog acts as a ledger of changes and contains a list of changesets(units of change) that Liquibase can execute on a database. The changesets files can be in various formats including XML, JSON, YAML, and SQL.</p>
</li>
<li><p>As we continue to change/enhance our DB structure through the development lifecycle we tend to add more changesets. A master file lists all the changeset files (or the directories where they are).</p>
</li>
<li><p>Liquibase tracks which changeSets have or have not been deployed in a tracking table called a <strong>DATABASECHANGELOG</strong>. If our database does not already contain a tracking table, Liquibase will create it for us.</p>
</li>
<li><p>Liquibase also prevents conflicts from different callers’ updates on a secondary table called <strong>DATABASECHANGELOGLOCK</strong>.</p>
</li>
<li><p>When we issue a liquibase update command, liquibase looks at the current state of DB, and identifies which changes have already happened. Then it run the rest of the changes - moving us to the latest revision of the structure defined.</p>
</li>
<li><p>By integrating Liquibase into the overall code version management system and continuous integration platform we can synch up our database versions with our app version.</p>
</li>
</ul>
<h2 id="heading-lets-start-with-integrating-liquibase-to-our-maven-project">Let's start with integrating Liquibase to our maven project</h2>
<p>Add the dependency for Liquibase in pom.xml.</p>
<pre><code><span class="hljs-operator">&lt;</span>dependency<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>groupId<span class="hljs-operator">&gt;</span>org.liquibase&lt;<span class="hljs-operator">/</span>groupId<span class="hljs-operator">&gt;</span>
     <span class="hljs-operator">&lt;</span>artifactId<span class="hljs-operator">&gt;</span>liquibase<span class="hljs-operator">-</span>core<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>artifactId<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>version<span class="hljs-operator">&gt;</span><span class="hljs-number">3.4</span><span class="hljs-number">.1</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>version<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>dependency<span class="hljs-operator">&gt;</span>
</code></pre><p>Create a changelog file, where sql related operation to be performed will be added.</p>
<pre><code><span class="hljs-operator">&lt;</span>?xml version<span class="hljs-operator">=</span><span class="hljs-string">"1.0"</span> encoding<span class="hljs-operator">=</span><span class="hljs-string">"UTF-8"</span> standalone<span class="hljs-operator">=</span><span class="hljs-string">"no"</span>?<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>databaseChangeLog ...&gt;

    <span class="hljs-operator">&lt;</span>changeSet author<span class="hljs-operator">=</span><span class="hljs-string">"John (generated)"</span> id<span class="hljs-operator">=</span><span class="hljs-string">"1439225004329-1"</span><span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>createTable tableName<span class="hljs-operator">=</span><span class="hljs-string">"APP_USER"</span><span class="hljs-operator">&gt;</span>
            <span class="hljs-operator">&lt;</span>column autoIncrement<span class="hljs-operator">=</span><span class="hljs-string">"true"</span> name<span class="hljs-operator">=</span><span class="hljs-string">"id"</span> <span class="hljs-keyword">type</span><span class="hljs-operator">=</span><span class="hljs-string">"BIGINT"</span><span class="hljs-operator">&gt;</span>
                <span class="hljs-operator">&lt;</span>constraints primaryKey<span class="hljs-operator">=</span><span class="hljs-string">"true"</span><span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
            <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>column<span class="hljs-operator">&gt;</span>
            <span class="hljs-operator">&lt;</span>column name<span class="hljs-operator">=</span><span class="hljs-string">"accessToken"</span> <span class="hljs-keyword">type</span><span class="hljs-operator">=</span><span class="hljs-string">"VARCHAR(255)"</span><span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
            <span class="hljs-operator">&lt;</span>column name<span class="hljs-operator">=</span><span class="hljs-string">"needCaptcha"</span> <span class="hljs-keyword">type</span><span class="hljs-operator">=</span><span class="hljs-string">"BIT(1)"</span><span class="hljs-operator">&gt;</span>
                <span class="hljs-operator">&lt;</span>constraints nullable<span class="hljs-operator">=</span><span class="hljs-string">"false"</span><span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
            <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>column<span class="hljs-operator">&gt;</span>
            <span class="hljs-operator">&lt;</span>column name<span class="hljs-operator">=</span><span class="hljs-string">"password"</span> <span class="hljs-keyword">type</span><span class="hljs-operator">=</span><span class="hljs-string">"VARCHAR(255)"</span><span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
            <span class="hljs-operator">&lt;</span>column name<span class="hljs-operator">=</span><span class="hljs-string">"refreshToken"</span> <span class="hljs-keyword">type</span><span class="hljs-operator">=</span><span class="hljs-string">"VARCHAR(255)"</span><span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
            <span class="hljs-operator">&lt;</span>column name<span class="hljs-operator">=</span><span class="hljs-string">"tokenExpiration"</span> <span class="hljs-keyword">type</span><span class="hljs-operator">=</span><span class="hljs-string">"datetime"</span><span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
            <span class="hljs-operator">&lt;</span>column name<span class="hljs-operator">=</span><span class="hljs-string">"username"</span> <span class="hljs-keyword">type</span><span class="hljs-operator">=</span><span class="hljs-string">"VARCHAR(255)"</span><span class="hljs-operator">&gt;</span>
                <span class="hljs-operator">&lt;</span>constraints nullable<span class="hljs-operator">=</span><span class="hljs-string">"false"</span><span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
            <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>column<span class="hljs-operator">&gt;</span>
            <span class="hljs-operator">&lt;</span>column name<span class="hljs-operator">=</span><span class="hljs-string">"preference_id"</span> <span class="hljs-keyword">type</span><span class="hljs-operator">=</span><span class="hljs-string">"BIGINT"</span><span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
            <span class="hljs-operator">&lt;</span>column name<span class="hljs-operator">=</span><span class="hljs-string">"address"</span> <span class="hljs-keyword">type</span><span class="hljs-operator">=</span><span class="hljs-string">"VARCHAR(255)"</span><span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>createTable<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>changeSet<span class="hljs-operator">&gt;</span>
    ...
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>databaseChangeLog<span class="hljs-operator">&gt;</span>
</code></pre><p>In the above file, we are creating a table named <code>APP_USER</code> with necessary columns. The changeset is identified by an id and an author – to make sure it can be uniquely identified and only applied once. We can save this file with name 'add-appuser-table-liquibase-script.xml'.</p>
<p>We can choose one of the option to run the changes on our DB on the application startup. In this example, we are prefering Spring Bean. The Spring bean for the liquibase configuration is below:</p>
<pre><code>@Bean
<span class="hljs-keyword">public</span> SpringLiquibase liquibase() {
    SpringLiquibase liquibase <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> SpringLiquibase();
    liquibase.setChangeLog(<span class="hljs-string">"classpath:liquibase/master.xml"</span>);
    liquibase.setDataSource(dataSource());
    <span class="hljs-keyword">return</span> liquibase;
}
</code></pre><p>The <code>master.xml</code> mentioned in the code above encapsulates all the liquibase scripts we will be writing as the application lifecycle proceeds. The sample master.xml file goes below:</p>
<pre><code><span class="hljs-operator">&lt;</span>?xml version<span class="hljs-operator">=</span><span class="hljs-string">"1.0"</span> encoding<span class="hljs-operator">=</span><span class="hljs-string">"utf-8"</span>?<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>databaseChangeLog
    xmlns<span class="hljs-operator">=</span><span class="hljs-string">"http://www.liquibase.org/xml/ns/dbchangelog"</span>
    xmlns:xsi<span class="hljs-operator">=</span><span class="hljs-string">"http://www.w3.org/2001/XMLSchema-instance"</span>
    xsi:schemaLocation<span class="hljs-operator">=</span><span class="hljs-string">"http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.5.xsd"</span><span class="hljs-operator">&gt;</span>

    <span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span> include all release changelogs below, <span class="hljs-keyword">as</span> the application grows up and whenever <span class="hljs-keyword">new</span> liquibase scripts are introduced. -<span class="hljs-operator">-</span><span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>include file<span class="hljs-operator">=</span><span class="hljs-string">"liquibase/add-appuser-table-liquibase-script.xml"</span><span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>databaseChangeLog<span class="hljs-operator">&gt;</span>
</code></pre><p>At app startup, we can ensure to call the Spring Bean which is configured for liquibase. With these steps, our liquibase scripts will start getting executed in your connected DB. We can track what all liquibase executed by quering in the DB: <code>select * from DATABASECHANGELOG;</code></p>
<p>For more granular control on Liquibase, we can make use of spring profile yml/property files where we can explicitly define parameters and values for different configuration. These values can then be used in the bean classes as per the requirement.</p>
]]></content:encoded></item><item><title><![CDATA[Distributed Tracing with Spring Boot Jaeger - Part 2]]></title><description><![CDATA[This is a two parts series on this article, where we have covered Distributed Tracing in a Spring Boot application using Jaeger. This is part 2 of the…]]></description><link>https://tech.anshulgautam.in/distributed-tracing-with-spring-boot-jaeger-part-2</link><guid isPermaLink="true">https://tech.anshulgautam.in/distributed-tracing-with-spring-boot-jaeger-part-2</guid><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[distributed system]]></category><dc:creator><![CDATA[Anshul Gautam]]></dc:creator><pubDate>Wed, 18 May 2022 17:27:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1652715996533/1mMdXF44s.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This is a two parts series on this article, where we have covered Distributed Tracing in a Spring Boot application using Jaeger. This is part 2 of the series.</p>
<p>If you are coming to this article directly, I will urge you to go through the part 1 of this series <a target="_blank" href="https://tech.anshulgautam.in/distributed-tracing-with-spring-boot-jaeger-part-1">here</a>.</p>
<ul>
<li><a target="_blank" href="https://tech.anshulgautam.in/distributed-tracing-with-spring-boot-jaeger-part-1">Part 1</a></li>
<li><a target="_blank" href="https://tech.anshulgautam.in/distributed-tracing-with-spring-boot-jaeger-part-2">Part 2</a></li>
<li><a target="_blank" href="https://tech.anshulgautam.in/distributed-tracing-with-spring-boot-jaeger-part-3">Part 3</a></li>
</ul>
<h2 id="heading-integrating-jaeger-in-our-spring-boot-project">🎯 Integrating Jaeger in our Spring Boot project</h2>
<p>Let's head over to pom.xml and add below dependency there.</p>
<pre><code>&lt;dependency&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>io.opentracing.contrib<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>opentracing-spring-jaeger-web-starter<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>3.3.1<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span></span>
&lt;/dependency&gt;
</code></pre><p>In this project I have used <code>&lt;version&gt;3.3.1&lt;/version&gt;</code>. At the time of writing this article, the current version I checked at official <a target="_blank" href="https://github.com/opentracing-contrib/java-spring-jaeger">Github repository</a> is mentioned as <code>3.3.2</code>. But the version <code>3.3.2</code> was not available in the maven central repository, that's why I went ahead with version <code>3.3.1</code>.</p>
<p>Okay, now we need to configure the Jaeger so that spans generated from the application are collected at the backend.</p>
<p>I configured the bare minimum stuff by while exposing the <code>JaegerTracer</code> bean. Below is how I did the configuration for <code>initiator-service</code> application.</p>
<pre><code>@Bean
public JaegerTracer jaegerTracer() {

    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> 
        <span class="hljs-comment">// Give a name to the configuration.</span>
        Configuration(<span class="hljs-string">"initiator"</span>)
        <span class="hljs-comment">// configure the sampler here.</span>
        .withSampler(<span class="hljs-keyword">new</span> SamplerConfiguration().withType(ConstSampler.TYPE).withParam(<span class="hljs-number">1</span>))
        <span class="hljs-comment">// Report and log spans? Well, yes please do!</span>
        .withReporter(<span class="hljs-keyword">new</span> ReporterConfiguration().withLogSpans(<span class="hljs-literal">true</span>))
        <span class="hljs-comment">// Get the Tracer object.</span>
        .getTracer();
}
</code></pre><p>We can do even more configuration here; like plugging in the MetricsFactory, Tracer tags etc. If you do ctrl+space after <code>.</code> in this builder method, you will be able to see more options popping up that you can use for your configuration.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652710696539/d2RAhf0RK.png" alt="image.png" /></p>
<p>For the simplicity sake, I have kept my configurations bare minimum.</p>
<p>This configuration for <code>JaegerTracer</code> bean needs to be done for <code>orchestrator-service</code> also.</p>
<pre><code>@Bean
public JaegerTracer jaegerTracer() {

    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Configuration(<span class="hljs-string">"orchestrator"</span>)
        .withSampler(<span class="hljs-keyword">new</span> SamplerConfiguration().withType(ConstSampler.TYPE).withParam(<span class="hljs-number">1</span>))
        .withReporter(<span class="hljs-keyword">new</span> ReporterConfiguration().withLogSpans(<span class="hljs-literal">true</span>))
        .getTracer();
}
</code></pre><p>Both our applications are ready to push the data to backend Jaeger UI. Let's start <code>initiator-service</code> and <code>orchestrator-service</code> now.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652711824888/GkVhuLnVd.png" alt="image.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652711862510/zZKeuoD8g.png" alt="image.png" /></p>
<h2 id="heading-start-the-jaeger-ui">🎯 Start the Jaeger UI</h2>
<p>Jaeger UI sits in the backend and stores all the tracing information sent by all the applications that have Jaeger clients present in them. Jaeger UI uses the data sailed from all these clients and present visualizations for us.</p>
<p>I will be running Jaeger UI in a docker container.</p>
<p>Pull the latest image from docker. At the time of writing this article it was <code>1.34</code>.</p>
<p><code>docker pull jaegertracing/all-in-one:1.34</code></p>
<p>Start the Jaeger UI in docker container using the below command:</p>
<p><code>docker run -d --name jaeger-ui -p 16686:16686 -p 6831:6831/udp jaegertracing/all-in-one:1.34</code></p>
<p>At the default port <code>16686</code> we will be able access the Jaeger UI from browser for visualization. <code>6831</code> is the default udp port where both our applications will be pushing the tracing data.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652711926680/Y2Vt3bauL.png" alt="image.png" /></p>
<p>Let's check if Jaeger UI is loading in the browser or not.</p>
<p><code>http://localhost:16686/</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652713434167/0hxg-J_Pu.png" alt="image.png" /></p>
<h2 id="heading-analyze-the-distributed-tracing">🎯 Analyze the distributed tracing</h2>
<p>Let's hit the <code>initiator-service</code> and try to see the response.</p>
<p><code>http://localhost:9091/v1/api/initiator/data/13</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652713504237/auY9y3z80.png" alt="image.png" /></p>
<p>The <code>initiator-service</code> called <code>orchestrator-service</code>, which in turn called the Numbers API. The <code>orchestrator-service</code> received response from Numbers API and responded back to <code>initiator-service</code>.</p>
<p>If we hit the Jaeger UI again, we should be able to see our services listed there.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652713725710/0dwty9Iu9.png" alt="image.png" /></p>
<p>Let's try to see traces under <code>initiator</code> service.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652713831934/lk81di7yk.png" alt="image.png" />
You can see that we have information available to us at each juncture, along with the time taken, in the application flow from <code>initiator-service</code> to <code>orchestrator-service</code>.</p>
<p>But wait. Before we analyze this visualization more, let's get back to console logs of our applications.</p>
<h2 id="heading-console-logs-for-initiator-service">🎯 Console logs for initiator-service</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652714204201/qbQ7i_tU2.png" alt="image.png" />
Here we have some valuable information. <code>Span reported: b4c041679573927b:cd787ecad024766b:b4c041679573927b:1 - GET</code>.</p>
<ul>
<li><code>b4c041679573927b</code> is root span id. </li>
<li><code>cd787ecad024766b</code> is current span id.</li>
<li><code>b4c041679573927b</code> is parent span id. </li>
</ul>
<p>The root and parent span id is same for <code>initiator-service</code>. Why so? This is so because from here only our communication started. As soon as we hit the <code>initiator-service</code> root span id was created. This happens to be parent span id as well because there was no preceding service call before this. If we see similar logs in <code>orchestrator-service</code> we will have root and parent span id different.</p>
<h2 id="heading-console-logs-for-orchestrator-service">🎯 Console logs for orchestrator-service</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652715020994/kz-A9tP1w.png" alt="image.png" /></p>
<ul>
<li><code>b4c041679573927b</code> is the root span id. This is same as root span id in <code>initiator-service</code>. It is uniquely identifying the transaction through these two services.</li>
<li><code>66ff4448982c410f</code> is the current span id. This one is unique.</li>
<li><code>cd787ecad024766b</code> is the parent span id. This is the current span id from <code>initiator-service</code>. Why so? This is so because <code>initiator-service</code> is the parent service which called the <code>orchestrator-service</code>.</li>
</ul>
<p>Now is a good time to go back to Jaeger UI and understand the same relationship there.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652715635405/lUx2P4k0C5.png" alt="image.png" /></p>
<p>In each of the expanded window, we can see how every span id is related to one another, stacked over one another in <strong>root </strong>-&gt; <strong>parent</strong> -&gt; <strong>child </strong>relationship.</p>
<h2 id="heading-what-happens-under-the-hood">🎯 What happens under the hood</h2>
<p>Under the hood we have <strong>OpenTracing</strong> implementation provided by Jaeger present in each of our application. These we can call as Jaeger Clients. We added this in our services via the <code>io.opentracing.contrib</code> dependency. They are responsible to intercept the service calls that happen from their host application and insert proper header information. These header information get passed over to the next subsequent calls, as part of context propagation.</p>
<h2 id="heading-conclusion">🎯 Conclusion</h2>
<p>I hope this post would have helped you in one way or the other. All the code changes that I did in this post are present at my GitHub <a target="_blank" href="https://github.com/anshulgammy/utopian-nerd/tree/main/usecases/spring-boot-jaeger-example">repository</a>.</p>
<p>If you have any suggestions for me, then please share that with me by commenting below.</p>
]]></content:encoded></item><item><title><![CDATA[Distributed Tracing with Spring Boot Jaeger - Part 1]]></title><description><![CDATA[This is a two parts series where we have covered Distributed Tracing in a Spring Boot application using Jaeger. This is part 1 of the series. In this…]]></description><link>https://tech.anshulgautam.in/distributed-tracing-with-spring-boot-jaeger-part-1</link><guid isPermaLink="true">https://tech.anshulgautam.in/distributed-tracing-with-spring-boot-jaeger-part-1</guid><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[distributed system]]></category><dc:creator><![CDATA[Anshul Gautam]]></dc:creator><pubDate>Mon, 16 May 2022 07:45:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/465HdvGQTc4/upload/v1652685769252/7tSYYS-Wv.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This is a two parts series where we have covered Distributed Tracing in a Spring Boot application using <strong>Jaeger</strong>. This is part 1 of the series.</p>
<ul>
<li><a target="_blank" href="https://tech.anshulgautam.in/distributed-tracing-with-spring-boot-jaeger-part-1">Part 1</a></li>
<li><a target="_blank" href="https://tech.anshulgautam.in/distributed-tracing-with-spring-boot-jaeger-part-2">Part 2</a></li>
<li><a target="_blank" href="https://tech.anshulgautam.in/distributed-tracing-with-spring-boot-jaeger-part-3">Part 3</a></li>
</ul>
<p>In this article we will try to understand what is distributed tracing, and how can we implement that in our Spring Boot projects.</p>
<h2 id="heading-what-is-distributed-tracing">🎯 What is distributed tracing?</h2>
<p><strong>Distributed tracing</strong>, also sometimes referred to as <strong>Request tracing</strong>, refers to the solution using which we can monitor requests flowing through the different applications or components in a distributed architecture. It allows teams to link the operations and requests occurring between multiple of their services together.</p>
<p>In a monolith application we a single entity which is doing all the thing for you. So if you have to monitor a request, then you are sure that the request will be travelling under the periphery of your own application only. Hence, monitoring a request in monolithic architecture based applications is comparatively easy.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652630543001/HWUtuJa8l.jpg" alt="monolithic vs distributed.jpg" /></p>
<p>Today we are dealing with distributed architecture mostly. This is comprised of several independent small applications which work together to serve a request from the user. These smaller distributed applications could be yours, or may be they are being managed by different teams, or different enterprises altogether.</p>
<p>In such an architecture of distributed nature, suppose you found that a particular request processing is taking longer than the usual time, and you must find out that bottleneck in the application flow. How will you find out the bottleneck in the request flow when all the moving pieces are not in your control? A single user request can travel through hundreds or thousands of microservices.</p>
<p>To quickly identify where things are going wrong, you need a central overview of how requests are performing across services. If you could visualize the entire flow and have ample data at your hand as the request flows through the smaller applications, you will be in a position to find out the bottleneck. After you have found the bottleneck  then may be you can connect with the team who is responsible for handling that component which is causing the issue, and ask them to analyze the issue. This is the core happiness that distributed tracing has to offer you. With a great distributed tracing tool can improve your team's response to performance issues, thereby improving the end-user experience.</p>
<h2 id="heading-solutions-available-for-implementing-distributed-tracing">🎯 Solutions available for implementing distributed tracing</h2>
<p>There are several solutions available to us at this point using which we can implement distributed tracing in our projects. Few popular solutions are:</p>
<ul>
<li>Jaeger</li>
<li>Zipkin</li>
<li>Dynatrace</li>
<li>Lightstep</li>
<li>Splunk</li>
</ul>
<p>There are even more solutions available. I named only a few of them here. In this article I will be talking about <strong>Jaeger</strong>, and implement that in a Spring Boot project.</p>
<h2 id="heading-key-terms-used-in-any-distributed-tracing-solution">🎯 Key terms used in any distributed tracing solution</h2>
<p>Before diving into the implementation of any solution in our projects, let's go through two key terms that are very important.</p>
<ul>
<li><strong>Span</strong>: Span describes an operation or work taking place on a service. Like a web server responding to an HTTP request or a single invocation of a function. It is the most granular level of information.</li>
<li><strong>Trace</strong>: Trace describes the end to end journey of one or more connected spans. It is considered to be distributed if its spans are across multiple services.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652632925981/9j6V8MvDU.png" alt="image.png" />
In this picture you can see that spans are confined to a service/application. They reside under their application only. However, trace covers the entire journey of a request, and they cover all the involved services/applications. A trace id will be unique for a request in all the services.</p>
<p>When we will be analyzing a trace later here, we will be going through various spans which are present inside it, and get information from every span.</p>
<h2 id="heading-overview-of-services-we-are-developing-with-jaeger-integrated-in-them">🎯 Overview of services we are developing with Jaeger integrated in them</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652633207376/OmPbtwHSD.png" alt="image.png" /></p>
<p>This solution has been developed by Uber to solve end to end distributed tracing problem across micro services. </p>
<p>We will be creating two spring boot micro services, and include Jaeger maven dependency in both of them.</p>
<ul>
<li>Service 1: <strong>initiator-service</strong></li>
<li>Service 2: <strong>orchestrator-service</strong></li>
</ul>
<p>User will be interacting via Service 1.
Service 2 will make a call to an external API called numbers API, which will return response to Service 2 and Service 2 will return response to Service 1. Service 1 will give this response to the end user.</p>
<p>In both these micro services, we have Spring Web dependency only present as of now.</p>
<pre><code>&lt;dependency&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-web<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span></span>
&lt;/dependency&gt;
</code></pre><p>In initiator-service we have a controller:</p>
<pre><code>@RestController
@RequestMapping(<span class="hljs-string">"/v1/api/initiator"</span>)
public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">InitiatorController</span> </span>{

  private InitiatorService initiatorService;

  public InitiatorController(
      InitiatorService initiatorService) {
    <span class="hljs-built_in">this</span>.initiatorService = initiatorService;
  }

  @GetMapping(<span class="hljs-string">"/data/{id}"</span>)
  public ResponseEntity&lt;<span class="hljs-built_in">String</span>&gt; getData(@PathVariable(<span class="hljs-string">"id"</span>) int id) {
    <span class="hljs-keyword">return</span> ResponseEntity.ok(initiatorService.getData(id));
  }
}
</code></pre><p>The <code>InitiatorService</code> goes like below:</p>
<pre><code>@Service
public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">InitiatorService</span> </span>{

  private RestTemplate restTemplate;

  public InitiatorService(RestTemplate restTemplate) {
    <span class="hljs-built_in">this</span>.restTemplate = restTemplate;
  }

  public <span class="hljs-built_in">String</span> getData(int id) {
    <span class="hljs-keyword">return</span> restTemplate.getForObject(<span class="hljs-string">"http://localhost:9092/v1/api/orchestrator/data/"</span> + id,
        <span class="hljs-built_in">String</span>.class);
  }
}
</code></pre><p>The initiator-service is running on port <code>9091</code>.
This is a very simple service which basically calls orchestrator-service.</p>
<p>In orchestrator-service we have a controller:</p>
<pre><code>@RestController
@RequestMapping(<span class="hljs-string">"/v1/api/orchestrator"</span>)
public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OrchestratorController</span> </span>{

  private OrchestratorService orchestratorService;

  public OrchestratorController(
      OrchestratorService orchestratorService) {
    <span class="hljs-built_in">this</span>.orchestratorService = orchestratorService;
  }

  @GetMapping(<span class="hljs-string">"/data/{id}"</span>)
  public ResponseEntity&lt;<span class="hljs-built_in">String</span>&gt; getData(@PathVariable(<span class="hljs-string">"id"</span>) int id) {
    <span class="hljs-keyword">return</span> ResponseEntity.ok(orchestratorService.getData(id));
  }
}
</code></pre><p>We have a <code>OrchestratorService</code> present:</p>
<pre><code>@Service
public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OrchestratorService</span> </span>{

  private RestTemplate restTemplate;

  public OrchestratorService(RestTemplate restTemplate) {
    <span class="hljs-built_in">this</span>.restTemplate = restTemplate;
  }

  public <span class="hljs-built_in">String</span> getData(int id) {
    <span class="hljs-keyword">return</span> restTemplate.getForObject(<span class="hljs-string">"http://numbersapi.com/"</span> + id, <span class="hljs-built_in">String</span>.class);
  }
}
</code></pre><p>The orchestrator-service runs on port <code>9092</code>. It makes a call to Numbers API. This is an external API which serves get request on its endpoint: <code>http://numbersapi.com/{id}</code>.
The {id} here is any integer value. This API returns a fact about the number passed.
For example when we make a call to <code>numbersapi.com/11</code>, we get a String response which is a fact on number 11.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652685542838/nJOtpVP0z.png" alt="image.png" /></p>
<p>If you hit this endpoint again, you might get another response fact on the number 11.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652685644837/BpzaezQx6.png" alt="image.png" /></p>
<p>Okay! I hope now you are clear on the basic set of services that we have with us. We will include Jaeger in them now. And by using Jaeger, we will be tracing how our request travelled through these two micro services, Service 1 to Service 2 to Numbers API, and back to Service 1. I have covered all this in very detail in <a target="_blank" href="https://tech.anshulgautam.in/distributed-tracing-with-spring-boot-jaeger-part-2">Part 2</a> of this series. Please check that out.</p>
<p>Complete code changes that I used are present at my Github <a target="_blank" href="https://github.com/anshulgammy/utopian-nerd/tree/main/usecases/spring-boot-jaeger-example">repository</a>.</p>
<p>If you have any suggestions for me, then please share that with me by commenting below.</p>
]]></content:encoded></item><item><title><![CDATA[BoB the Builder of Beans Plugin for IntelliJ]]></title><description><![CDATA[When you are implementing Builder Pattern in your code, I am sure you must have realized it's repetitive at places, and involves lot of typing. The boiler…]]></description><link>https://tech.anshulgautam.in/bob-the-builder-of-beans-plugin-for-intellij</link><guid isPermaLink="true">https://tech.anshulgautam.in/bob-the-builder-of-beans-plugin-for-intellij</guid><category><![CDATA[Hashnode]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[plugins]]></category><category><![CDATA[design patterns]]></category><dc:creator><![CDATA[Anshul Gautam]]></dc:creator><pubDate>Sun, 15 May 2022 08:21:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/9QTFMkh-ezM/upload/v1652585276548/wwszOK7zY.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When you are implementing Builder Pattern in your code, I am sure you must have realized it's repetitive at places, and involves lot of typing. The boiler plate code will keep on increasing if you have more number of properties in your class. </p>
<p>BoB the Builder of Beans is one such plugin present for IntelliJ using which you can create your bean builder just with a shortcut.</p>
<h2 id="heading-the-builder-pattern">The Builder Pattern</h2>
<p>Builder Pattern is a creational design pattern that helps you create complex objects through an alternative way, with lots of possible configuration options.</p>
<p>This pattern is really helpful when you want to get rid of long telescoping constructors in your code for object creation at different places.</p>
<p>Builder pattern supports chaining of initialization of object's properties.</p>
<p>eg:</p>
<p><code>myBuilder-&gt;setValueA(1)-&gt;setValueB(2)-&gt;build()</code></p>
<h2 id="heading-bob-the-builder-of-beans">BoB the Builder of Beans</h2>
<p>BoB the Builder of Beans is a plugin that allows you to generate Java boilerplate code effortlessly! BoB allows you to specify just fields of a Java class and then generate a patterned class with standard getters, hashcode and equals, and of course a builder.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652584632885/EGfS85Ob1.png" alt="image.png" /></p>
<p>It is perfect for generated JSON serialization classes or data transfer objects.</p>
<p>But wait why another plugin, when you already have shortcuts provided inside IntelliJ to create Getters/Setters, Constructors, just with a bit more effort isn't it an easy go to create Builder for the bean also? Well, it's not.</p>
<p>With BoB not only you can create Builders, but can also tune in even more granular properties so that creating a similar type of builders across the entire project is achieved. With <code>bob.propeties</code> you are basically overriding the defaults of the plugin and tuning in your own custom settings. You can the place this file in the project root folder, or may be distribute it to you fellow developers so that they can also make use of it and at the end you will get uniform builders across the entire project.</p>
<h2 id="heading-installing-this-plugin">Installing this plugin</h2>
<p>You can install this plugin from the IntelliJ IDEA marketplace, or directly from the official link <a target="_blank" href="https://plugins.jetbrains.com/plugin/12032-bob-the-builder-of-beans">here</a>.</p>
<p>For installing it via Market place, in IntelliJ IDEA go to File -&gt; Settings -&gt; Plugins -&gt; Marketplace.</p>
<p>Search for 'BoB the builder of beans' in the dialog, and click on install.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652585237193/U7Yg_A8TZ.png" alt="image.png" /></p>
<h2 id="heading-using-this-plugin">Using this plugin</h2>
<p>Go to the class where you would want to implement the builder.
In the example below, I have few properties defined in my class.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652602193940/EGnzMfVhM.png" alt="image.png" /></p>
<p>We just need to right click on this class -&gt; Generate -&gt; BoB the Builder of Beans</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652602287528/TIs9Kb4co.png" alt="image.png" /></p>
<p>And there you go. All the key components of your Builder has been created, including getters and setters as well.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652602372909/qoALTGYT5.png" alt="image.png" /></p>
<p>This plugin also creates the <code>toString()</code>, <code>hashCode</code> and <code>equals()</code> method for you.</p>
<p>The complete generated class using this plugin is shown below:</p>
<pre><code><span class="hljs-keyword">public</span> class Student {

  <span class="hljs-keyword">private</span> String fullName;
  <span class="hljs-keyword">private</span> String fatherName;
  <span class="hljs-keyword">private</span> String motherName;
  <span class="hljs-keyword">private</span> Date dateOfBirth;
  <span class="hljs-keyword">private</span> String homeAddress;
  <span class="hljs-keyword">private</span> String branch;
  <span class="hljs-keyword">private</span> long rollNumber;
  <span class="hljs-keyword">private</span> boolean isHostler;
  <span class="hljs-keyword">private</span> boolean isSpeciallyAbled;

  <span class="hljs-comment">// region Constructor, getters, setters, equals, hashCode, toString, builder -- generated by BoB the Builder of Beans</span>
  <span class="hljs-comment">// The code below has been generated by BoB the Builder of Beans based on the class' fields.</span>
  <span class="hljs-comment">// Everything after this comment will be regenerated if you invoke BoB again.</span>
  <span class="hljs-comment">// If you don't know who BoB is, you can find him here: https://bitbucket.org/atlassianlabs/bob-the-builder-of-beans</span>

  protected Student(String fullName, String fatherName, String motherName, Date dateOfBirth,
      String homeAddress, String branch, long rollNumber, boolean isHostler,
      boolean isSpeciallyAbled) {
    <span class="hljs-built_in">this</span>.fullName <span class="hljs-operator">=</span> Objects.requireNonNull(fullName);
    <span class="hljs-built_in">this</span>.fatherName <span class="hljs-operator">=</span> Objects.requireNonNull(fatherName);
    <span class="hljs-built_in">this</span>.motherName <span class="hljs-operator">=</span> Objects.requireNonNull(motherName);
    <span class="hljs-built_in">this</span>.dateOfBirth <span class="hljs-operator">=</span> Objects.requireNonNull(dateOfBirth);
    <span class="hljs-built_in">this</span>.homeAddress <span class="hljs-operator">=</span> Objects.requireNonNull(homeAddress);
    <span class="hljs-built_in">this</span>.branch <span class="hljs-operator">=</span> Objects.requireNonNull(branch);
    <span class="hljs-built_in">this</span>.rollNumber <span class="hljs-operator">=</span> rollNumber;
    <span class="hljs-built_in">this</span>.isHostler <span class="hljs-operator">=</span> isHostler;
    <span class="hljs-built_in">this</span>.isSpeciallyAbled <span class="hljs-operator">=</span> isSpeciallyAbled;
  }

  <span class="hljs-comment">// region Getters and setters -- generated by BoB the Builder of Beans</span>
  <span class="hljs-keyword">public</span> String getFullName() {
    <span class="hljs-keyword">return</span> fullName;
  }

  <span class="hljs-keyword">public</span> void setFullName(String fullName) {
    <span class="hljs-built_in">this</span>.fullName <span class="hljs-operator">=</span> Objects.requireNonNull(fullName);
  }

  <span class="hljs-keyword">public</span> String getFatherName() {
    <span class="hljs-keyword">return</span> fatherName;
  }

  <span class="hljs-keyword">public</span> void setFatherName(String fatherName) {
    <span class="hljs-built_in">this</span>.fatherName <span class="hljs-operator">=</span> Objects.requireNonNull(fatherName);
  }

  <span class="hljs-keyword">public</span> String getMotherName() {
    <span class="hljs-keyword">return</span> motherName;
  }

  <span class="hljs-keyword">public</span> void setMotherName(String motherName) {
    <span class="hljs-built_in">this</span>.motherName <span class="hljs-operator">=</span> Objects.requireNonNull(motherName);
  }

  <span class="hljs-keyword">public</span> Date getDateOfBirth() {
    <span class="hljs-keyword">return</span> dateOfBirth;
  }

  <span class="hljs-keyword">public</span> void setDateOfBirth(Date dateOfBirth) {
    <span class="hljs-built_in">this</span>.dateOfBirth <span class="hljs-operator">=</span> Objects.requireNonNull(dateOfBirth);
  }

  <span class="hljs-keyword">public</span> String getHomeAddress() {
    <span class="hljs-keyword">return</span> homeAddress;
  }

  <span class="hljs-keyword">public</span> void setHomeAddress(String homeAddress) {
    <span class="hljs-built_in">this</span>.homeAddress <span class="hljs-operator">=</span> Objects.requireNonNull(homeAddress);
  }

  <span class="hljs-keyword">public</span> String getBranch() {
    <span class="hljs-keyword">return</span> branch;
  }

  <span class="hljs-keyword">public</span> void setBranch(String branch) {
    <span class="hljs-built_in">this</span>.branch <span class="hljs-operator">=</span> Objects.requireNonNull(branch);
  }

  <span class="hljs-keyword">public</span> long getRollNumber() {
    <span class="hljs-keyword">return</span> rollNumber;
  }

  <span class="hljs-keyword">public</span> void setRollNumber(long rollNumber) {
    <span class="hljs-built_in">this</span>.rollNumber <span class="hljs-operator">=</span> rollNumber;
  }

  <span class="hljs-keyword">public</span> boolean getIsHostler() {
    <span class="hljs-keyword">return</span> isHostler;
  }

  <span class="hljs-keyword">public</span> void setIsHostler(boolean isHostler) {
    <span class="hljs-built_in">this</span>.isHostler <span class="hljs-operator">=</span> isHostler;
  }

  <span class="hljs-keyword">public</span> boolean getIsSpeciallyAbled() {
    <span class="hljs-keyword">return</span> isSpeciallyAbled;
  }

  <span class="hljs-keyword">public</span> void setIsSpeciallyAbled(boolean isSpeciallyAbled) {
    <span class="hljs-built_in">this</span>.isSpeciallyAbled <span class="hljs-operator">=</span> isSpeciallyAbled;
  }<span class="hljs-comment">// endregion Getters and setters</span>

  <span class="hljs-comment">// region hashCode() and equals() -- generated by BoB the Builder of Beans</span>
  @Override
  <span class="hljs-keyword">public</span> boolean equals(Object o) {
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span> <span class="hljs-operator">=</span><span class="hljs-operator">=</span> o) {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
    <span class="hljs-keyword">if</span> (o <span class="hljs-operator">=</span><span class="hljs-operator">=</span> null <span class="hljs-operator">|</span><span class="hljs-operator">|</span> getClass() <span class="hljs-operator">!</span><span class="hljs-operator">=</span> o.getClass()) {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }

    Student that <span class="hljs-operator">=</span> (Student) o;

    <span class="hljs-keyword">return</span> Objects.equals(<span class="hljs-built_in">this</span>.getFullName(), that.getFullName()) <span class="hljs-operator">&amp;</span><span class="hljs-operator">&amp;</span> Objects.equals(
        <span class="hljs-built_in">this</span>.getFatherName(), that.getFatherName()) <span class="hljs-operator">&amp;</span><span class="hljs-operator">&amp;</span> Objects.equals(<span class="hljs-built_in">this</span>.getMotherName(),
        that.getMotherName()) <span class="hljs-operator">&amp;</span><span class="hljs-operator">&amp;</span> Objects.equals(<span class="hljs-built_in">this</span>.getDateOfBirth(), that.getDateOfBirth())
        <span class="hljs-operator">&amp;</span><span class="hljs-operator">&amp;</span> Objects.equals(<span class="hljs-built_in">this</span>.getHomeAddress(), that.getHomeAddress()) <span class="hljs-operator">&amp;</span><span class="hljs-operator">&amp;</span> Objects.equals(
        <span class="hljs-built_in">this</span>.getBranch(), that.getBranch()) <span class="hljs-operator">&amp;</span><span class="hljs-operator">&amp;</span> Objects.equals(<span class="hljs-built_in">this</span>.getRollNumber(),
        that.getRollNumber()) <span class="hljs-operator">&amp;</span><span class="hljs-operator">&amp;</span> Objects.equals(<span class="hljs-built_in">this</span>.getIsHostler(), that.getIsHostler())
        <span class="hljs-operator">&amp;</span><span class="hljs-operator">&amp;</span> Objects.equals(<span class="hljs-built_in">this</span>.getIsSpeciallyAbled(), that.getIsSpeciallyAbled());
  }

  @Override
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> hashCode() {
    <span class="hljs-keyword">return</span> Objects.hash(getFullName(), getFatherName(), getMotherName(), getDateOfBirth(),
        getHomeAddress(), getBranch(), getRollNumber(), getIsHostler(), getIsSpeciallyAbled());
  }<span class="hljs-comment">// endregion hashCode() and equals()</span>

  <span class="hljs-comment">// region toString() -- generated by BoB the Builder of Beans</span>
  @Override
  <span class="hljs-keyword">public</span> String toString() {
    <span class="hljs-keyword">return</span> MoreObjects.toStringHelper(<span class="hljs-built_in">this</span>)
        .add(<span class="hljs-string">"fullName"</span>, getFullName())
        .add(<span class="hljs-string">"fatherName"</span>, getFatherName())
        .add(<span class="hljs-string">"motherName"</span>, getMotherName())
        .add(<span class="hljs-string">"dateOfBirth"</span>, getDateOfBirth())
        .add(<span class="hljs-string">"homeAddress"</span>, getHomeAddress())
        .add(<span class="hljs-string">"branch"</span>, getBranch())
        .add(<span class="hljs-string">"rollNumber"</span>, getRollNumber())
        .add(<span class="hljs-string">"isHostler"</span>, getIsHostler())
        .add(<span class="hljs-string">"isSpeciallyAbled"</span>, getIsSpeciallyAbled())
        .toString();
  }<span class="hljs-comment">// endregion toString()</span>

  <span class="hljs-comment">// region Builder -- generated by BoB the Builder of Beans</span>
  <span class="hljs-keyword">public</span> static Student.Builder builder() {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Student.Builder();
  }

  <span class="hljs-keyword">public</span> static Student.Builder builder(Student data) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Student.Builder(data);
  }

  <span class="hljs-keyword">public</span> static final class Builder {

    <span class="hljs-keyword">private</span> String fullName;
    <span class="hljs-keyword">private</span> String fatherName;
    <span class="hljs-keyword">private</span> String motherName;
    <span class="hljs-keyword">private</span> Date dateOfBirth;
    <span class="hljs-keyword">private</span> String homeAddress;
    <span class="hljs-keyword">private</span> String branch;
    <span class="hljs-keyword">private</span> long rollNumber;
    <span class="hljs-keyword">private</span> boolean isHostler;
    <span class="hljs-keyword">private</span> boolean isSpeciallyAbled;

    <span class="hljs-keyword">private</span> Builder() {
    }

    <span class="hljs-keyword">private</span> Builder(Student initialData) {
      <span class="hljs-built_in">this</span>.fullName <span class="hljs-operator">=</span> initialData.fullName;
      <span class="hljs-built_in">this</span>.fatherName <span class="hljs-operator">=</span> initialData.fatherName;
      <span class="hljs-built_in">this</span>.motherName <span class="hljs-operator">=</span> initialData.motherName;
      <span class="hljs-built_in">this</span>.dateOfBirth <span class="hljs-operator">=</span> initialData.dateOfBirth;
      <span class="hljs-built_in">this</span>.homeAddress <span class="hljs-operator">=</span> initialData.homeAddress;
      <span class="hljs-built_in">this</span>.branch <span class="hljs-operator">=</span> initialData.branch;
      <span class="hljs-built_in">this</span>.rollNumber <span class="hljs-operator">=</span> initialData.rollNumber;
      <span class="hljs-built_in">this</span>.isHostler <span class="hljs-operator">=</span> initialData.isHostler;
      <span class="hljs-built_in">this</span>.isSpeciallyAbled <span class="hljs-operator">=</span> initialData.isSpeciallyAbled;
    }

    <span class="hljs-keyword">public</span> Builder setFullName(String fullName) {
      <span class="hljs-built_in">this</span>.fullName <span class="hljs-operator">=</span> fullName;
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>;
    }

    <span class="hljs-keyword">public</span> Builder setFatherName(String fatherName) {
      <span class="hljs-built_in">this</span>.fatherName <span class="hljs-operator">=</span> fatherName;
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>;
    }

    <span class="hljs-keyword">public</span> Builder setMotherName(String motherName) {
      <span class="hljs-built_in">this</span>.motherName <span class="hljs-operator">=</span> motherName;
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>;
    }

    <span class="hljs-keyword">public</span> Builder setDateOfBirth(Date dateOfBirth) {
      <span class="hljs-built_in">this</span>.dateOfBirth <span class="hljs-operator">=</span> dateOfBirth;
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>;
    }

    <span class="hljs-keyword">public</span> Builder setHomeAddress(String homeAddress) {
      <span class="hljs-built_in">this</span>.homeAddress <span class="hljs-operator">=</span> homeAddress;
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>;
    }

    <span class="hljs-keyword">public</span> Builder setBranch(String branch) {
      <span class="hljs-built_in">this</span>.branch <span class="hljs-operator">=</span> branch;
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>;
    }

    <span class="hljs-keyword">public</span> Builder setRollNumber(long rollNumber) {
      <span class="hljs-built_in">this</span>.rollNumber <span class="hljs-operator">=</span> rollNumber;
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>;
    }

    <span class="hljs-keyword">public</span> Builder setIsHostler(boolean isHostler) {
      <span class="hljs-built_in">this</span>.isHostler <span class="hljs-operator">=</span> isHostler;
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>;
    }

    <span class="hljs-keyword">public</span> Builder setIsSpeciallyAbled(boolean isSpeciallyAbled) {
      <span class="hljs-built_in">this</span>.isSpeciallyAbled <span class="hljs-operator">=</span> isSpeciallyAbled;
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>;
    }

    <span class="hljs-keyword">public</span> Student build() {
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Student(fullName, fatherName, motherName, dateOfBirth, homeAddress, branch,
          rollNumber, isHostler, isSpeciallyAbled);
    }
  }<span class="hljs-comment">// endregion Builder</span>
  <span class="hljs-comment">// endregion Constructor, getters, setters, equals, hashCode, toString, builder</span>
}
</code></pre><h2 id="heading-conclusion">Conclusion</h2>
<p>This plugin is very useful and a must have for Java developers. I hope this post gave you complete idea around this plugin, and how you can install this and use.</p>
<p>If you have never used this plugin before, do give it a try. I am sure you will love this too like I do.</p>
]]></content:encoded></item><item><title><![CDATA[Maven Helper Dependency Analyzer Plugin for IntelliJ]]></title><description><![CDATA[This is a very common problem where we come across conflicting dependencies in our maven projects. A dependency can be present as a transitive dependency…]]></description><link>https://tech.anshulgautam.in/maven-helper-dependency-analyzer-plugin-for-intellij</link><guid isPermaLink="true">https://tech.anshulgautam.in/maven-helper-dependency-analyzer-plugin-for-intellij</guid><category><![CDATA[Hashnode]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[maven]]></category><dc:creator><![CDATA[Anshul Gautam]]></dc:creator><pubDate>Thu, 12 May 2022 15:38:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/tzfD-clzUTU/upload/v1652368247630/T-iXqfsFL.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This is a very common problem where we come across conflicting dependencies in our maven projects. A dependency can be present as a transitive dependency across several dependencies, and can potentially cause conflict at the runtime. This problem surfaces into a bigger shape when their versions are different. An older version is an outdated version for you may be as it won't offer latest classes bundled inside it. On the other hand it can also be a situation wherein the older version had the classes that you need but the newer major release version had those classes removed. Now you are in trouble.</p>
<p>In this post we will be discussing about an IntelliJ IDEA plugin which helps you find out the conflicting dependencies from your IDE, with a nice and reliable UI.</p>
<h2 id="heading-the-maven-helper-plugin">The Maven Helper Plugin</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652374246926/Rjc2YWkmA.png" alt="image.png" />
This <a target="_blank" href="https://plugins.jetbrains.com/plugin/7179-maven-helper">plugin</a> helps you with:</p>
<ul>
<li>Providing an easy way for analyzing and excluding conflicting dependencies</li>
<li>Gives actions to run/debug maven goals for a module that contains the current file or on the root module</li>
<li>Action to open terminal at the current maven module path</li>
<li>Provides actions to run/debug the current test file.</li>
</ul>
<p>Maven has a goal <code>mvn dependency:tree</code> which gives you information on the dependency hierarchy in your maven projects. But the representation is not so good. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652375330527/Th3WFGajG.png" alt="image.png" /></p>
<p>We will see later in this post how this plugin shows you the same information.</p>
<h2 id="heading-installing-this-plugin">Installing this plugin</h2>
<p>You can install this plugin from the IntelliJ IDEA marketplace, or directly from the official link <a target="_blank" href="https://plugins.jetbrains.com/plugin/7179-maven-helper">here</a>.</p>
<p>For installing it via Market place, in IntelliJ IDEA go to File -&gt; Settings -&gt; Plugins -&gt; Marketplace.</p>
<p>Search for 'Maven Helper' in the dialog, and click on install.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652374490511/o8O6rmpIq.png" alt="image.png" /></p>
<h2 id="heading-using-this-plugin">Using this plugin</h2>
<p>Go to your pom.xml. Once you have installed this plugin, you should be able to see an option called Dependency Analyzer. Just click on that.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652374895197/xgMNqSkVQ.png" alt="image.png" /></p>
<p>Now, let's say that I want to know from where a dependency called <code>jsr305</code> is coming from. I will click on 'All Dependencies as Tree' and enter <code>jsr305</code> in the search box. Check the Filter checkbox.
And here you go. You will be able to see from what all dependencies you are getting <code>jsr305</code> in your project.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652375172271/Rg54IPPQ-.png" alt="image.png" /></p>
<p>In case you want to see the conflicting dependencies, just click on Conflicts radio button. This will show you the conflicts that you have for the entered artifact.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This plugin is very useful and a must have for Java developers. I firmly believe this should be present in IntelliJ by default.</p>
<p>If you have never used this plugin before, do give it a try. I am sure you will love this too like I do.</p>
]]></content:encoded></item><item><title><![CDATA[Homebrew: The macOS Package Manager]]></title><description><![CDATA[If you are a software developer, then it is highly unlikely of you to not have come across the terminal program. You must have used it once in a while in…]]></description><link>https://tech.anshulgautam.in/homebrew-the-macos-package-manager</link><guid isPermaLink="true">https://tech.anshulgautam.in/homebrew-the-macos-package-manager</guid><category><![CDATA[Homebrew]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[2Articles1Week]]></category><dc:creator><![CDATA[Anshul Gautam]]></dc:creator><pubDate>Mon, 09 May 2022 15:37:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/qIAw1kNk1p8/upload/v1651861497566/lSgGcVYBk.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you are a software developer, then it is highly unlikely of you to not have come across the terminal program. You must have used it once in a while in the course of your work. These terminal programs are shipped with almost all the operating systems. </p>
<p>Terminal is the program where in your write and issue your commands, and they are executed using the underlying processing engine or shell. Depending upon the operating system you use, you will get a different terminal shell. For example, Linux operating systems will provide bash or zsh based terminal programs. Macintosh is unix based operating system and its terminal program is also bash or zsh based. Microsoft Windows provide DOS based terminal program.</p>
<p>In this article I am going to discuss about a package manager, called <strong>Homebrew</strong>, for your Mac terminal.</p>
<h2 id="heading-what-is-homebrew">What is Homebrew</h2>
<p><strong>Homebrew</strong> is a package manager for your Mac terminal. Using Homebrew you can install tools and application packages available in the Homebrew library for your computer.</p>
<p>Before you start installing packages using Homebrew, you need to install the Homebrew itself first.</p>
<p>As the <a target="_blank" href="https://brew.sh">official documentation</a> says, you can install using below command in your terminal.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1651906843588/VZQcOOwY_.png" alt="image.png" /></p>
<p>Once Homebrew is installed, trying running <code>brew --version</code> command in your terminal. You should be able to see the installed Homebrew version. This also confirms that Homebrew is installed correctly on your machine.</p>
<p>You should get output something like below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1651905554314/IWBcLlIMi.png" alt="image.png" /></p>
<p>Homebrew 3.4.10 is the current stable version available to us at the time of writing this article.</p>
<p>Before we dive into installing packages using Homebrew, let's try to understand few important key terms around it.</p>
<h2 id="heading-important-terms-related-to-homebrew">Important terms related to Homebrew</h2>
<ul>
<li><p><strong>Formulae</strong>: Homebrew maintains a definition file for its package, like a script file, which tells how to build and install the package for you on your mac. These are basically ruby scripts. This was developed for Hombrew as part of <code>Homebrew/homebrew-core project</code>. Every package that you can install using <code>brew</code> comes with its formula.</p>
</li>
<li><p><strong>Tap</strong>: Tap is a Git repository of Formulae. This repository gets cloned at the below location on your computer once you installed Homebrew: <code>/usr/local/Homebrew/Library/Taps/homebrew/homebrew-core</code>.</p>
</li>
</ul>
<p>Using <code>brew tap</code> you can add more repositories to the list of formulae that brew tracks, updates, and installs from.</p>
<ul>
<li><p><strong>Cask</strong>: It is an extension of Homebrew. It is used to install macOS native GUI applications. This was started independently, but later became part of the Homebrew project under  <code>Homebrew/homebrew-cask</code> project.</p>
</li>
<li><p><strong>Cellar</strong>: This is the location where Homebrew installs the application. The default path is <code>/usr/local/Cellar</code>.</p>
</li>
</ul>
<p><strong><em>Note</em></strong>: Paths that I have shown in this article are for Intel Macs.</p>
<h2 id="heading-playing-around-with-homebrew">Playing around with Homebrew</h2>
<p>Once you have installed Homebrew, it clones a git repository in your machine where details about the packages and their formulae are stored. You update this repository using the command <code>brew update</code>. This will update your downloaded git repository, which is present at <code>/usr/local/Homebrew/Library/Taps/homebrew/homebrew-core</code> with the latest code. Now when you want to install something, or update something, Homebrew will refer to this repository and see what it can offer for you.</p>
<p>You update all the installed packages using the command <code>brew upgrade</code>.</p>
<p>Use this command to see the list of packages which are currently installed by Homebrew: <code>brew list</code>.</p>
<p>Next, let's say we want to install git on our Mac using Homebrew. There is a formula available for it, by name 'git'. You will install git using the command <code>brew install &lt;formula&gt;</code>. So, for installing git our command will be: <code>brew install git</code>.</p>
<p>Homebrew will install this at your Cellar. So for the git, it will get installed at the location <code>/usr/local/Cellar/git/&lt;version&gt;/</code>.</p>
<p>The binaries file for git will be present in <code>/usr/local/Cellar/git/&lt;version&gt;/bin/git</code>.</p>
<p>Homebrew will also add a symlink from <code>/usr/local/bin/git</code> to the binary file of git.
This is to help Homebrew keep track of what's installed by the Homebrew itself, and what all that have been installed by other ways.</p>
<p>One more important thing to note here is that when the package that you are trying to install has some transitive dependencies, then those dependencies also get installed along with the original package.</p>
<p>Let's try to understand installation of transitive packages by an example where I will be installing <code>wget</code> on my Mac.</p>
<p>I will go my terminal and issue the command <code>brew install wget</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1651911150216/TVzw1f11d.png" alt="image.png" />
In the terminal you will be able to see list of transitive dependencies in wget, which Homebrew will also install for us. These transitive dependencies are needed by wget to run and that is why these dependencies are getting installed as well.</p>
<p>Once wget installation is complete, let's go ahead and check what all packages do we have now. We will be checking this by issuing the command <code>brew list</code>. Keep in mind that I had deleted all the previous packages, and my Cellar was empty.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1651911234802/ZjQ_tvmS6.png" alt="image.png" /></p>
<p>Okay, so along with wget we also have ca-certificates, gettext, libidn2, libunistring    and openssl@1.1 now installed on our computer. Great!</p>
<h2 id="heading-installing-a-gui-application-using-homebrew">Installing a GUI Application using Homebrew</h2>
<p>Like I mentioned before, we use cask extension in Homebrew to install GUI application. We will issue the command <code>brew install --cask google-chrome</code> to install chrome on our system.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1651912434857/oyQcxIIcv.png" alt="image.png" /></p>
<p>See it has installed the application and also added it in <code>/Applications/</code> folder. This will be available in our Launchpad as well.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1651913073722/cPwxJHwvI.png" alt="image.png" /></p>
<p>This application being a GUI desktop application, this was not added to Cellar.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1651912949389/znTEhO9-w.png" alt="image.png" /></p>
<p>Doing <code>brew list</code> will show all the packages, and how they were installed. Notice it shows cask for the Google Chrome, as we installed it using cask.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1651943402413/zW5deCaZ9.png" alt="image.png" /></p>
<h2 id="heading-ending-notes">Ending Notes</h2>
<p>I hope this post gave you an idea on Homebrew, and how you can use that to install and manage packages on your Mac. I will reiterate here again that all the path values that I shared in this article are for Intel powered Mac computers. For Apple M1, these path values might vary.</p>
]]></content:encoded></item><item><title><![CDATA[Function Currying in Java]]></title><description><![CDATA[Learn about function currying in Java with a simple use case study on Sandwiches]]></description><link>https://tech.anshulgautam.in/function-currying-in-java</link><guid isPermaLink="true">https://tech.anshulgautam.in/function-currying-in-java</guid><category><![CDATA[Java]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[2Articles1Week]]></category><dc:creator><![CDATA[Anshul Gautam]]></dc:creator><pubDate>Sat, 07 May 2022 15:36:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1651504496856/ejX7G3AZY.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-overview">🎯 Overview</h2>
<p>You must be aware of out of the box functional interfaces provided by Java since the advent of version 8.</p>
<p>These functional interfaces like <code>Function&lt;T, R&gt;</code>, <code>BiFunction&lt;T, U, R&gt;</code>, <code>Consumer&lt;T&gt;</code> etc present in <code>java.util.function</code> package help you with out of the box functional interfaces so that you need not create them on your own.
Also, they bring uniformity in the code bases by having similar functional interfaces all around for the same type and same usage.</p>
<p>These functional interfaces in one way also have a limitation; on the number of arguments they can handle and work on.</p>
<p>For example, <code>Function&lt;T, R&gt;</code> will take in object of type T and apply the function to return object of type R.</p>
<p>What if you want to apply a function based on two objects? Well, yes, there is a <code>BiFunction&lt;T, U, R&gt;</code> for you to use. But then, what if you want to have four objects to make use of while applying the function and return some object type?</p>
<p>This problem can be solved using <strong><em>currying</em></strong>.</p>
<h2 id="heading-what-is-currying">🎯 What is Currying</h2>
<p>With currying in Java we can define high order functions and then pass the first order function and function arguments in a chained cascaded fashion.</p>
<p>In other words, we can relate this to having broken a bigger function with many arguments into several functions of single argument, which are chained in such a way that the final output from the original bigger function stays the same.</p>
<p>Let's dive more into this with one problem statement which we will solve using currying in Java.</p>
<h2 id="heading-the-problem-statement">🎯 The problem statement</h2>
<p>We have a <code>Sandwich</code> class which has properties like bread, veggies, onion, eggs, pepper etc. We want to prepare the Sandwich by instantiating this class.</p>
<p>The <code>Sandwich</code> class will be instantiated in <code>SandwichOvenOperator</code> class, in a curried Function manner.</p>
<h2 id="heading-implementation">🎯 Implementation</h2>
<pre><code><span class="hljs-comment">// This class has Builder pattern implemented inside it to create Sandwiches</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Sandwich</span> </span>{

    private <span class="hljs-built_in">String</span> bread;
    private boolean veggies;
    private boolean eggs;
    private boolean meat;
    private boolean pepper;
    private boolean onion;
    .
    .
    .
    .
}
</code></pre><p>There is one <code>SandwichOven</code> interface which extends from Function.</p>
<pre><code>interface SandwichOven <span class="hljs-keyword">extends</span>
        <span class="hljs-built_in">Function</span>&lt;<span class="hljs-built_in">String</span>,
                <span class="hljs-built_in">Function</span>&lt;<span class="hljs-built_in">Boolean</span>,
                        <span class="hljs-built_in">Function</span>&lt;<span class="hljs-built_in">Boolean</span>,
                                <span class="hljs-built_in">Function</span>&lt;<span class="hljs-built_in">Boolean</span>,
                                        <span class="hljs-built_in">Function</span>&lt;<span class="hljs-built_in">Boolean</span>,
                                                <span class="hljs-built_in">Function</span>&lt;<span class="hljs-built_in">Boolean</span>, Sandwich&gt;&gt;&gt;&gt;&gt;&gt; {

}
</code></pre><p>The class which implements this interface is below:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SandwichOvenOperator</span> <span class="hljs-title">implements</span> <span class="hljs-title">SandwichOven</span> </span>{

    @Override
    public <span class="hljs-built_in">Function</span>&lt;<span class="hljs-built_in">Boolean</span>,
            <span class="hljs-built_in">Function</span>&lt;<span class="hljs-built_in">Boolean</span>,
                    <span class="hljs-built_in">Function</span>&lt;<span class="hljs-built_in">Boolean</span>,
                            <span class="hljs-built_in">Function</span>&lt;<span class="hljs-built_in">Boolean</span>,
                                    <span class="hljs-built_in">Function</span>&lt;<span class="hljs-built_in">Boolean</span>, Sandwich&gt;&gt;&gt;&gt;&gt; apply(<span class="hljs-built_in">String</span> bread) {
        <span class="hljs-keyword">return</span> veggies -&gt; eggs -&gt; meat -&gt; pepper -&gt; onion -&gt; Sandwich.builder()
                .setBread(bread)
                .setEggs(eggs)
                .setMeat(meat)
                .setOnion(onion)
                .setPepper(pepper)
                .setVeggies(veggies)
                .build();
    }
}
</code></pre><p>Notice how we are returning the <code>Sandwich</code> instance using the curried function in the chain.</p>
<p>I am triggering <code>Sandwich</code> creation from the <code>main()</code> method.</p>
<pre><code>public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main(<span class="hljs-built_in">String</span>[] args) {
    SandwichOven sandwichOven = <span class="hljs-keyword">new</span> SandwichOvenOperator();
    <span class="hljs-comment">// performing apply() in the order of veggies -&gt; eggs -&gt; meat -&gt; pepper -&gt; onion, which is</span>
    <span class="hljs-comment">// defined in the SandwichOvenOperator.apply(bread) method.</span>
    Sandwich sandwich = sandwichOven
            .apply(<span class="hljs-string">"oregano"</span>) <span class="hljs-comment">// for bread</span>
            .apply(<span class="hljs-literal">true</span>) <span class="hljs-comment">// for veggies</span>
            .apply(<span class="hljs-literal">true</span>) <span class="hljs-comment">// for eggs</span>
            .apply(<span class="hljs-literal">false</span>) <span class="hljs-comment">// for meat</span>
            .apply(<span class="hljs-literal">true</span>) <span class="hljs-comment">// for pepper</span>
            .apply(<span class="hljs-literal">false</span>);<span class="hljs-comment">// for onion</span>
    System.out.println(<span class="hljs-string">"Sandwich prepared: "</span> + sandwich);
}
</code></pre><p>When we are operating the <code>SandwichOven</code> to prepare the Sandwich, we are following the chain order veggies -&gt; eggs -&gt; meat -&gt; pepper -&gt; onion, which is defined in the <code>SandwichOvenOperator.apply(bread)</code> method.</p>
<h2 id="heading-conclusion">🎯 Conclusion</h2>
<p>I hope this post gave you an overview of currying in Java using a simple example of preparing Sandwiches.</p>
<p>All the code changes that I showed in this post here are present at my GitHub <a target="_blank" href="https://github.com/anshulgammy/utopian-nerd/tree/main/usecases/java/java8-function-currying">repository</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Circuit Breaker Pattern using Resilience4J - Decorators]]></title><description><![CDATA[Learn about Resilience4j with simpler examples for retry and circuit breaker design pattern]]></description><link>https://tech.anshulgautam.in/circuit-breaker-pattern-using-resilience4j-decorators</link><guid isPermaLink="true">https://tech.anshulgautam.in/circuit-breaker-pattern-using-resilience4j-decorators</guid><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[design patterns]]></category><category><![CDATA[Spring]]></category><category><![CDATA[Java]]></category><dc:creator><![CDATA[Anshul Gautam]]></dc:creator><pubDate>Thu, 05 May 2022 15:35:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1651400370894/5Nuycrzfb.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This post is in continuation of my <a target="_blank" href="https://tech.anshulgautam.in/circuit-breaker-pattern-using-resilience4j-annotations">previous</a> post on this blog. In the previous post I discussed on what is circuit breaker, and how we can implement that using Resilience4j annotations.</p>
<p>In this post I will be discussing on implementing the same use case with Resilience4j, but this time using <strong><em>Decorators</em></strong>.</p>
<p>In case you are coming to this post directly, I will urge you to read through my <a target="_blank" href="https://tech.anshulgautam.in/circuit-breaker-pattern-using-resilience4j-annotations">previous</a> post first on Resilience4j.</p>
<h2 id="heading-recap-of-the-use-case-from-previous-post">🎯 Recap of the use case from previous post</h2>
<p>The caller method will make call to another method which will throw RuntimeException. Our circuit breaker implementation will keep an eye on this method throwing exception, and in case there is any exception it will provide a fallback route which will get executed when there is an exception.</p>
<p>This is a very simple use case. But it gives you an idea how to bind the circuit breaker implementation to guard your methods and provide a fallback route. </p>
<p>All this will be done in this post using decorators offered by Resilience4j. Remember that we need to have minimum Java version 8. This is because Resilience4j decorators are built on top of Java 8 functional interfaces.</p>
<h2 id="heading-integrate-resilience4j-in-spring-boot-project">🎯 Integrate Resilience4j in Spring Boot Project</h2>
<p>We will be adding below dependencies in pom.xml. Notice that we are not adding Spring AOP dependency here like we had to include when we were implementing using annotations.</p>
<pre><code>&lt;!-- Below dependency gives Retry support <span class="hljs-keyword">in</span> Resilience4j --&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>io.github.resilience4j<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>resilience4j-retry<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>${resilience4j-version}<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span></span>

&lt;!-- Below dependency gives CircuitBreaker support <span class="hljs-keyword">in</span> Resilience4j --&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>io.github.resilience4j<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>resilience4j-circuitbreaker<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>${resilience4j-version}<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span></span>

&lt;!-- Below dependency provides core circuit breaker support <span class="hljs-keyword">in</span> Resilience4j --&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>io.github.resilience4j<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>resilience4j-core<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>${resilience4j-version}<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span></span>

&lt;!-- Below dependency provides decorator support/functional interface <span class="hljs-keyword">in</span> Resilience4j <span class="hljs-keyword">for</span> Java <span class="hljs-number">8</span> and above --&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>io.github.resilience4j<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>resilience4j-all<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>${resilience4j-version}<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span></span>
</code></pre><h2 id="heading-implementation-using-decorators">🎯 Implementation using Decorators</h2>
<p>Resilience4j make use of Java 8 functional interfaces for its decorators. 
The below method is explicitly throwing RuntimeException.</p>
<pre><code><span class="hljs-comment">/**
 * We have configured Retry and CircuitBreaker on this method.
 * Idea is to try 'Retry' first for the configured number of times. If even after retrying this for the
 * configured number of times we continue to get exception, then CircuitBreaker will come into action.
 */</span>
public <span class="hljs-keyword">void</span> runService() {
    Decorators.ofSupplier(() -&gt; {
                LOGGER.info(<span class="hljs-string">"Printing from ResilientService.runService() for Decorator Implementation"</span>);
                <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
                    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(<span class="hljs-string">"Some RuntimeException occurred!"</span>);
                }
                <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
            }).withRetry(retryService)
            .withCircuitBreaker(circuitBreaker)
            .withFallback(Arrays.asList(RuntimeException.class),
                    e -&gt; {
                        fallbackService();
                        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
                    }).
            decorate().get();
}
</code></pre><p>In the method above, we have plugged in four independent components. Let's see one by one each one of them.</p>
<ol>
<li>Actual logic which the method is supposed to do. This is the code instruction which can throw exception, and hamper the flow in our application. This code instruction has been supplied in <code>Decorators.ofSupplier()</code>. Circuit Breaker will trip when exception is thrown from here.</li>
<li><code>Retry</code> component. This is the component which has retry related configuration within it using which retry will be performed. This is supplied using <code>.withRetry()</code>.</li>
<li><code>CircuitBreaker</code> component. This is the component which has circuit breaking logic instruction within it using resilience4j configuration. This is supplied using <code>.withCircuitBreaker()</code>.</li>
<li><code>Fallback</code> component. This is the component which will be executed as part of fallback, when there is an exception of the provided type. In the example, I have plugged in <code>fallbackService()</code> method which will be executed when there is a <code>RuntimeException</code> raised. This is supplied within <code>.withFallback()</code>.</li>
</ol>
<p>Now, let's see how I am preparing Retry and CircuitBreaker components.</p>
<h2 id="heading-preparing-the-retry-component-for-resilience4j-decorator">🎯 Preparing the Retry component for Resilience4j decorator</h2>
<pre><code>@Bean
@Qualifier(Constants.RESILIENCE_RETRY_NAME)
public Retry resilientServiceRetry(
        @Value(<span class="hljs-string">"${resilience4j.retry.name}"</span>) <span class="hljs-built_in">String</span> retryName,
        @Value(<span class="hljs-string">"${resilience4j.retry.retryService.maxRetryAttempts}"</span>) Integer maxAttempts,
        @Value(<span class="hljs-string">"${resilience4j.retry.retryService.waitDuration}"</span>) Integer waitDurationSeconds
) {
    final RetryConfig config = RetryConfig.custom()
            .maxAttempts(maxAttempts)
            .retryExceptions(RuntimeException.class)
            .waitDuration(Duration.ofSeconds(waitDurationSeconds))
            .build();
    final RetryRegistry registry = RetryRegistry.of(config);
    Retry retry = registry.retry(retryName, config);
    <span class="hljs-keyword">return</span> retry;
}
</code></pre><p>Configuration key value pairs are present in application.properties file. I am injecting them in the method and then preparing the Retry object.</p>
<p><code>maxAttempts</code> define the number of times retry operation will be performed.</p>
<p>In <code>retryExceptions</code> I have provided the exception class on which retry and circuit breaker will action. This method takes in <code>@Nullable Class&lt;? extends Throwable&gt;... errorClasses</code>.</p>
<p><code>waitDuration</code> is used to specify the wait duration after which each retry will be performed.</p>
<h2 id="heading-preparing-the-circuitbreaker-component-for-resilience4j-decorator">Preparing the CircuitBreaker component for Resilience4j decorator</h2>
<pre><code>@Bean
@Qualifier(Constants.RESILIENCE_CIRCUIT_BREAKER_NAME)
public CircuitBreaker resilientServiceCircuitBreaker(
        @Value(<span class="hljs-string">"${resilience4j.circuitbreaker.name}"</span>) <span class="hljs-built_in">String</span> circuitBreakerName,
        @Value(<span class="hljs-string">"${resilience4j.circuitbreaker.retryServiceCircuitBreaker.waitDurationInOpenState}"</span>) Integer waitDurationSeconds,
        @Value(<span class="hljs-string">"${resilience4j.circuitbreaker.retryServiceCircuitBreaker.slidingWindowSize}"</span>) Integer slidingWindowSize,
        @Value(<span class="hljs-string">"${resilience4j.circuitbreaker.retryServiceCircuitBreaker.failureRateThreshold}"</span>) Float failureRateThreshold,
        @Value(<span class="hljs-string">"${resilience4j.circuitbreaker.retryServiceCircuitBreaker.permittedNumberOfCallsInHalfOpenState}"</span>) Integer permittedNumberOfCallsInHalfOpenState
) {
    final CircuitBreakerConfig config = CircuitBreakerConfig
            .custom()
            .slidingWindowType(CircuitBreakerConfig.SlidingWindowType.COUNT_BASED)
            .slidingWindowSize(slidingWindowSize)
            .failureRateThreshold(failureRateThreshold)
            .waitDurationInOpenState(Duration.ofSeconds(waitDurationSeconds))
            .permittedNumberOfCallsInHalfOpenState(permittedNumberOfCallsInHalfOpenState)
            .build();
    final CircuitBreakerRegistry registry = CircuitBreakerRegistry.of(config);
    final CircuitBreaker circuitBreaker = registry.circuitBreaker(circuitBreakerName);
    <span class="hljs-keyword">return</span> circuitBreaker;
}
</code></pre><p>For creating circuit breaker component I am again fetching the configuration key values from application properties file and injecting them in the method. These values are used to create the <code>CircuitBreakerRegistry</code> object, from which we get the <code>CircuitBreaker</code> component.</p>
<h2 id="heading-configuration-properties">🎯 Configuration properties</h2>
<p>Configuration key value pairs are same as what we used while implementing using resilience4j annotations.</p>
<pre><code>#Resilience4j Retry specific configuration goes below
resilience4j.retry.name=retryService
#resilience4j.retry.retryAspectOrder=<span class="hljs-number">2</span>
resilience4j.retry.retryService.maxRetryAttempts=<span class="hljs-number">3</span>
resilience4j.retry.retryService.waitDuration=<span class="hljs-number">1</span>

#Resilience4j CircuitBreaker specific configuration goes below
resilience4j.circuitbreaker.name=retryServiceCircuitBreaker
#resilience4j.circuitbreaker.circuitBreakerAspectOrder=<span class="hljs-number">1</span>
resilience4j.circuitbreaker.retryServiceCircuitBreaker.waitDurationInOpenState=<span class="hljs-number">3</span>
resilience4j.circuitbreaker.retryServiceCircuitBreaker.permittedNumberOfCallsInHalfOpenState=<span class="hljs-number">3</span>
#resilience4j.circuitbreaker.retryServiceCircuitBreaker.slidingWindowType=COUNT_BASED
resilience4j.circuitbreaker.retryServiceCircuitBreaker.slidingWindowSize=<span class="hljs-number">2</span>
resilience4j.circuitbreaker.retryServiceCircuitBreaker.failureRateThreshold=<span class="hljs-number">30</span>
</code></pre><h2 id="heading-conclusion">🎯 Conclusion</h2>
<p>In this post, I used resilience4j implementation using decorators. I hope this was helpful for you.</p>
<p>All the code changes that I shown in this post are present in my GitHub <a target="_blank" href="https://github.com/anshulgammy/utopian-nerd/tree/main/usecases/resilience4j-with-springboot/resilience4j-decorator">repository</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Circuit Breaker Pattern using Resilience4j - Annotations]]></title><description><![CDATA[Learn about Resilience4j with simpler examples for retry and circuit breaker design pattern]]></description><link>https://tech.anshulgautam.in/circuit-breaker-pattern-using-resilience4j-annotations</link><guid isPermaLink="true">https://tech.anshulgautam.in/circuit-breaker-pattern-using-resilience4j-annotations</guid><category><![CDATA[Spring]]></category><category><![CDATA[Java]]></category><category><![CDATA[design patterns]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Hashnode]]></category><dc:creator><![CDATA[Anshul Gautam]]></dc:creator><pubDate>Sun, 01 May 2022 15:34:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1650306556908/NUXwzPB7a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-what-is-circuit-breaker-pattern">🎯 What is Circuit Breaker Pattern?</h2>
<p>Circuit Breaker Pattern in Software Development is a design pattern which is analogous to <strong>MCB</strong>(Miniature Circuit Breaker) switches in electricity wiring at our home. When there is flow of excessive current, the MCB switch trips and disconnects the circuit preventing electrical faults and electrical equipment failure.</p>
<p>The Circuit Breaker Pattern says that there is a proxy present in your application via which call to the other entity is being made. If there is a huge latency in getting response from this other entity, or if the entity is not available all together, then this proxy disconnects the route and prevents clients from making call to this other entity.</p>
<p>Here, the other entity can be a service within your own application or some other external service.</p>
<p>If there is a delay in getting the response in the synchronous call, the thread making this call has to wait. Imagine several other threads staying blocked for the same reason. This invites high resource usage which doesn't yield anything fruitful. In such scenarios, it becomes an obvious choice to handle it properly. We can plug in something via the proxy, like an alternate route, which will respond when there is fault in the application flow. The proxy will stop routing the call to faulty entities and will trigger the alternate route to handle this fault. This ensures that our costly resources are being utilized properly.</p>
<p>Circuit Breaker Pattern incorporation becomes matter of utmost importance in micro service architecture where we can have several other external and internal services to make call to.</p>
<p>In such a distributed state of application, we must incorporate circuit breaker in our applications.</p>
<h2 id="heading-circuit-breaker-implementation">🎯 Circuit Breaker Implementation</h2>
<p>There are several implementation present right now which you can use in your applications for circuit breaker. Making use of one of the implementation in your projects prevent you from re-inventing the wheel as you don't need to write the implementation yourself, somebody has already done that for you. And with popularity and good community support available for that implementation, you are rest assured that you will be getting security fixes/updates for them on time.</p>
<p>Hystrix and Resilience4j are two such popular implementation available to us. In this post I will be making use of Resilience4j annotations with Spring Boot to demonstrate the implementation of Circuit Breaker Pattern.</p>
<h2 id="heading-resilience4j">🎯 Resilience4j</h2>
<blockquote>
<p><a target="_blank" href="https://github.com/resilience4j/resilience4j">Resilience4j</a> is a Java library that helps us build resilient and fault-tolerant applications. It provides a framework for writing code to prevent and handle such issues.</p>
</blockquote>
<p>Resilience4j is a lightweight fault tolerance library inspired by Netflix Hystrix, but designed for Java 8 and functional programming. Resilience4j provides annotations and higher-order functions (decorators) to enhance any functional interface, lambda expression or method reference with a Circuit Breaker, Rate Limiter, Retry or Bulkhead.</p>
<h2 id="heading-resilience4j-states">🎯 Resilience4j States</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1651394129246/p1iWOMnSy.jpg" alt="resilience4j states.jpg" />
Resilience4j has three states:</p>
<ul>
<li><strong>Closed</strong>: When resilience4j is in closed state, it means there is no fault in the application flow and method calls are getting routed via the proxy properly as expected.</li>
<li><strong>Open</strong>: In open state, call to faulty service is prevented, and call goes to the fallback method always.</li>
<li><strong>Half Open</strong>: It is an intermediary state which is in between open and closed states. Before moving to open or closed state, circuit breaker stays in half open state. In this state all the comparison with resilience4j configured values(like failure rate threshold, wait time etc) are done to see whether the circuit can be moved to <code>closed()</code> or to <code>open()</code> state.</li>
</ul>
<h2 id="heading-integrate-resilience4j-in-spring-boot-project">🎯 Integrate Resilience4j in Spring Boot Project</h2>
<p>We will be adding below dependencies in pom.xml of our Spring Boot project.</p>
<pre><code>&lt;!-- Spring Boot Starter AOP is required <span class="hljs-keyword">for</span> Resilience4j Spring Boot to work --&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-aop<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span></span>

&lt;!-- Resilience4j Spring Boot <span class="hljs-number">2</span> support via Annotations --&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>io.github.resilience4j<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>resilience4j-spring-boot2<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>${resilience4j.version}<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span></span>
</code></pre><p>We need to have Spring AOP present in the classpath. If not, then circuit breaker won't work. This is so because while implementing resilience4j with annotations, it internally makes use of Spring proxies. In the example here I will be using annotations.</p>
<p>The resilience4j-spring-boot2 version I will be using is 1.7.0.</p>
<pre><code>&lt;resilience4j.version&gt;<span class="hljs-number">1.7</span><span class="hljs-number">.0</span>&lt;/resilience4j.version&gt;
</code></pre><h2 id="heading-implementation-using-annotations">🎯 Implementation using Annotations</h2>
<p>For the implementation, I am going to use a very simple use case.
The caller method will make call to another method which will throw RuntimeException. Our circuit breaker implementation will keep an eye on this method throwing exception, and in case there is any exception it will provide a fallback route which will get executed when there is an exception.</p>
<p>This is a very simple use case. But it gives you an idea how to bind the circuit breaker implementation to guard your methods and provide a fallback route.</p>
<pre><code>@CircuitBreaker(name = <span class="hljs-string">"serviceCircuitBreaker"</span>, fallbackMethod = <span class="hljs-string">"fallbackService"</span>)
public <span class="hljs-keyword">void</span> runService() {
    LOGGER.info(<span class="hljs-string">"Printing from ResilientService.runService()"</span>);
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(<span class="hljs-string">"Some RuntimeException occurred!"</span>);
}

private <span class="hljs-keyword">void</span> fallbackService(RuntimeException runtimeException) {
    LOGGER.info(<span class="hljs-string">"Printing Fallback for Resilient Service"</span>);
}
</code></pre><p>The method <code>runService</code> explicitly throws <code>RuntimeException</code>. You tie the resilience4j circuit breaker instance to it using <code>@CircuitBreaker</code> annotation. </p>
<p>It takes in field called <code>name</code> which assigns a name to your circuit breaker instance. </p>
<p>It also takes in field called <code>fallbackMethod</code> which is the name of the method which will be executed as a fallback method when there is some exception from the method.</p>
<p>Note that the fallback method needs to take in the type of exception argument which will be thrown. Here, we have RuntimeException which we want to guard on and that is why our fallback method has RuntimeException parameter. If there is any other exception thrown, which is not a RuntimeException, then this fallback method won't get executed.</p>
<p>Suppose the method <code>runService()</code> throws some another exception which is not a RuntimeException, for example say a custom exception called <code>ServiceCustomException</code>, then we would need to introduce another fallback method with ServiceCustomException as the parameter, to handle this exception in fallback. So in this case, we will have two fallback methods, one for handling RuntimeException, and another one for handling ServiceCustomException.</p>
<pre><code>@CircuitBreaker(name = <span class="hljs-string">"serviceCircuitBreaker"</span>, fallbackMethod = <span class="hljs-string">"fallbackService"</span>)
public <span class="hljs-keyword">void</span> runService() {
    LOGGER.info(<span class="hljs-string">"Printing from ResilientService.runService()"</span>);
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(<span class="hljs-string">"Some RuntimeException occurred!"</span>);
}

<span class="hljs-comment">/* For handling RuntimeException if thrown from runService() method */</span>
private <span class="hljs-keyword">void</span> fallbackService(RuntimeException runtimeException) {
    LOGGER.info(<span class="hljs-string">"Printing Fallback for Resilient Service, for RuntimeException"</span>);
}

<span class="hljs-comment">/* For handling ServiceCustomException if thrown from runService() method */</span>
private <span class="hljs-keyword">void</span> fallbackService(ServiceCustomException serviceCustomException) {
    LOGGER.info(<span class="hljs-string">"Printing Fallback for Resilient Service, for ServiceCustomException"</span>);
}
</code></pre><p>You can also club retry, rate limiter, bulkhead patterns with circuit breaker. Below I have shown you an example of clubbing the retry in the circuit breaker.</p>
<pre><code>@CircuitBreaker(name = <span class="hljs-string">"serviceCircuitBreaker"</span>, fallbackMethod = <span class="hljs-string">"fallbackService"</span>)
@Retry(name = <span class="hljs-string">"retryService"</span>)
public <span class="hljs-keyword">void</span> runService() {
    LOGGER.info(<span class="hljs-string">"Printing from ResilientService.runService()"</span>);
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(<span class="hljs-string">"Some RuntimeException occurred!"</span>);
}
</code></pre><p>We have configured <code>Retry</code> and <code>CircuitBreaker</code> on this method.
Idea is to try '<em>Retry</em>' first for the configured number of times. If even after retrying this for the configured number of times we continue to get exception, then circuit breaker will come into action.</p>
<p>Now, if things are clear so far then let's move further and see the resilience4j configuration.</p>
<h2 id="heading-resilience4j-configuration">🎯 Resilience4j Configuration</h2>
<p>I have used following configuration values for resilience4j circuit breaker</p>
<pre><code>#Resilience4j Retry specific configuration goes below
resilience4j.retry.retryAspectOrder=<span class="hljs-number">2</span>
resilience4j.retry.instances.retryService.maxRetryAttempts=<span class="hljs-number">3</span>
resilience4j.retry.instances.retryService.retryExceptions=java.lang.RuntimeException
resilience4j.retry.instances.retryService.waitDuration=<span class="hljs-number">1</span>s

#Resilience4j CircuitBreaker specific configuration goes below
resilience4j.circuitbreaker.circuitBreakerAspectOrder=<span class="hljs-number">1</span>
resilience4j.circuitbreaker.instances.serviceCircuitBreaker.waitDurationInOpenState=<span class="hljs-number">3</span>s
resilience4j.circuitbreaker.instances.serviceCircuitBreaker.permittedNumberOfCallsInHalfOpenState=<span class="hljs-number">3</span>
resilience4j.circuitbreaker.instances.serviceCircuitBreaker.slidingWindowType=COUNT_BASED
resilience4j.circuitbreaker.instances.serviceCircuitBreaker.slidingWindowSize=<span class="hljs-number">2</span>
resilience4j.circuitbreaker.instances.serviceCircuitBreaker.failureRateThreshold=<span class="hljs-number">30</span>
</code></pre><p><code>circuitBreakerAspectOrder</code> has been set to 1, and <code>retryAspectOrder</code> has been set to 2. By default, the retry mechanism has lower priority and hence it warps around the circuit breaker aspect. By doing this change, we gave higher priority to retry.</p>
<p>So with this, we will retry first for the configured number of times, and if retry limit is exhausted then circuit breaker will come into action with its configuration.</p>
<p><code>failureRateThreshold</code> is the percentage of failure that resilience4j is witnessing, at which the circuit breaker will move to open state.</p>
<p>Most of the configuration values are self explanatory as per their key name in the properties file. You can find more information on resilience4j configuration values over <a target="_blank" href="https://resilience4j.readme.io/docs/getting-started-3#configuration">here</a>.</p>
<h2 id="heading-conclusion">🎯 Conclusion</h2>
<p>This post gives you a basic idea on what circuit breaker is, and how we can implement that in our projects using resilience4j. In this post, I used resilience4j implementation using annotations. In the next post I will discuss implementing the same using decorators. And in that approach spring proxies will not be used.</p>
<p>All the code changes that I shown in this example are present in my GitHub <a target="_blank" href="https://github.com/anshulgammy/utopian-nerd/tree/main/usecases/resilience4j-with-springboot/resilience4j-annotation">repository</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Debugging Java Streams with IntelliJ Plugin]]></title><description><![CDATA[Explore debugging Java Streams using Java Stream Debugger IntelliJ plugin]]></description><link>https://tech.anshulgautam.in/debugging-java-streams-with-intellij-plugin</link><guid isPermaLink="true">https://tech.anshulgautam.in/debugging-java-streams-with-intellij-plugin</guid><category><![CDATA[Java]]></category><category><![CDATA[plugins]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Hashnode]]></category><dc:creator><![CDATA[Anshul Gautam]]></dc:creator><pubDate>Sat, 09 Apr 2022 15:13:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649420158977/TeRUf-gwo.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>With Java 8 Streams, we are now able to process elements in streams in functional style; in declarative way. This has made processing elements easier and with an option to do these processing operations parallelly. </p>
<p>One of the problem people face with large stream pipeline is that when these pipelines need to be debugged. Suppose there are 10 intermediate operations being performed on a stream pipeline. And the output from the net stream is not coming as expected. So a developer would need to debug and see which intermediate operation is actually causing the issue.</p>
<p>The problem is that the stream pipelines are not easy to debug. Even if you put debug points in the code for Java stream, only those debug points will get executed where instructions are written inside curly braces. Debug points put across method references do not work well. Hence, it becomes cumbersome to debug stream pipeline.</p>
<h2 id="heading-java-stream-debugger-plugin">🎯 Java Stream Debugger Plugin</h2>
<p><strong>Jetbrains </strong>offers a plugin called <strong>Java Stream Debugger</strong> plugin which you can install in your IntelliJ IDEA.
This plugin comes pre-installed and enabled in recent versions of the IntelliJ IDEA, but in case you have an older version of the installation then you can install this plugin.</p>
<p>You can find link to the plugin <a target="_blank" href="https://plugins.jetbrains.com/plugin/9696-java-stream-debugger">here</a>.</p>
<p>This plugin evaluates the entire stream pipeline, and shows output based on every operation plugged into the stream.</p>
<h2 id="heading-plugin-demonstration">🎯 Plugin Demonstration</h2>
<p>Let's start with writing a Java stream.</p>
<p>We have a <code>List&lt;Greeting&gt;</code> object which we want to stream, and get <code>List&lt;String&gt;</code> object. String value in the output list denotes the <code>Greeting</code> object's <code>message</code> attribute and these are those messages whose corresponding <code>id</code> is an even number.</p>
<p>So, the Greeting class has below attributes.</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Greeting</span> </span>{
  private long id;
  private <span class="hljs-built_in">String</span> message;

  <span class="hljs-comment">// getters setters constructors</span>
}
</code></pre><p>Let's have a look on the stream where we are using <code>List&lt;Greeting&gt;</code> and generating <code>List&lt;String&gt;</code> object.</p>
<pre><code>public List&lt;<span class="hljs-built_in">String</span>&gt; getEvenIdGreetingList() {
    List&lt;<span class="hljs-built_in">String</span>&gt; greetingMessageList = GREETING_LIST
        .stream()
        .filter(greeting -&gt; greeting.getId() % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>)
        .map(greeting -&gt; greeting.getMessage())
        .collect(Collectors.toList());
    <span class="hljs-keyword">return</span> greetingMessageList;
}
</code></pre><p>The <code>GREETING_LIST</code> is a hard coded list of <code>Greeting</code>. Quickly showing you below how I had constructed this.</p>
<pre><code>private <span class="hljs-keyword">static</span> final List&lt;Greeting&gt; GREETING_LIST = Arrays.asList(
      <span class="hljs-keyword">new</span> Greeting(<span class="hljs-number">1</span>, <span class="hljs-string">"Greeting Message 1"</span>),
      <span class="hljs-keyword">new</span> Greeting(<span class="hljs-number">2</span>, <span class="hljs-string">"Greeting Message 2"</span>),
      <span class="hljs-keyword">new</span> Greeting(<span class="hljs-number">3</span>, <span class="hljs-string">"Greeting Message 3"</span>),
      <span class="hljs-keyword">new</span> Greeting(<span class="hljs-number">4</span>, <span class="hljs-string">"Greeting Message 4"</span>),
      <span class="hljs-keyword">new</span> Greeting(<span class="hljs-number">5</span>, <span class="hljs-string">"Greeting Message 5"</span>),
      <span class="hljs-keyword">new</span> Greeting(<span class="hljs-number">6</span>, <span class="hljs-string">"Greeting Message 6"</span>));
</code></pre><p>Let's start the debugging.</p>
<p>I have put the debug point at the start of this stream. Let's start the debugging now.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1649515904267/B1yZkitWm.png" alt="image.png" /></p>
<p>In the Debug tab of IntelliJ, click on the icon which I have highlighted in the screenshot below. This will bring up the dialog where stream will be evaluated.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1649516116153/G8uQFY-cM.png" alt="image.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1649516144712/kjz92VBZX.png" alt="image.png" /></p>
<p>You will be able to see the stream trace. It will show evaluated result against each of the operation.
For example, after applying the filter operation we get below result:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1649516234451/_qAt358Cd.png" alt="image.png" /></p>
<p>The map operation gives below result, which is now <code>List&lt;String&gt;</code>:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1649516287122/CG1_TH-VC.png" alt="image.png" /></p>
<p>collect terminal operation gives below result:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1649516322816/etHqx78GV.png" alt="image.png" /></p>
<p>This is how you can see the evaluation of your Java stream pipeline with ease, and debug for your use cases. Output from each operation in the stream is shown in a separate tab in the stream trace dialog window, just like I showed you in screenshots above.</p>
<h2 id="heading-conclusion">🎯 Conclusion</h2>
<p>In this post we explored the <strong>Java Stream Debugger</strong> plugin, which is one of the most important tool to have in your toolkit as a Java developer. It helps to see the evaluation of Java streams with ease, and you can perform your debugging.</p>
<p>If you found this post useful, please show some love by leaving a comment for me and by sharing this article.</p>
]]></content:encoded></item><item><title><![CDATA[Async Method Calls using CompletableFuture in Spring Boot]]></title><description><![CDATA[Configure ThreadPoolTaskExecutor in Spring Boot application for achieving async method calls]]></description><link>https://tech.anshulgautam.in/async-method-calls-using-completablefuture-in-spring-boot</link><guid isPermaLink="true">https://tech.anshulgautam.in/async-method-calls-using-completablefuture-in-spring-boot</guid><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Hashnode]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[Java]]></category><category><![CDATA[asynchronous]]></category><dc:creator><![CDATA[Anshul Gautam]]></dc:creator><pubDate>Fri, 08 Apr 2022 08:57:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649409903426/xc98KJcb6.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In my previous <a target="_blank" href="https://tech.anshulgautam.in/reactive-programming-using-completablefuture-in-java">post</a>, I discussed on <code>CompletableFuture</code> provided by Java concurrency API in <strong>JDK 8</strong> onwards.</p>
<p>In this article, I want to discuss on using CompletableFuture in Spring Boot application.</p>
<h2 id="heading-threadpooltaskexecutor-in-spring-boot">🎯 ThreadPoolTaskExecutor in Spring Boot</h2>
<p>Spring offers ThreadPoolTaskExecutor as a Java bean which is an abstraction of ThreadPoolExecutor of Java concurrency API.</p>
<p>It has key configuration values which you can configure for your application.</p>
<ul>
<li><p><code>corePoolSize</code>: It is the minimum number of workers which Spring will keep alive without getting timed out.</p>
</li>
<li><p><code>maxPoolSize</code>: It defines the maximum number of threads that can be created by Spring.</p>
</li>
<li><p><code>queueCapacity</code>: It defines the capacity for the ThreadPoolExecutor's BlockingQueue.</p>
</li>
</ul>
<p>These configuration values are delegated to underlying Java concurrency API, to the ThreadPoolExecutor.</p>
<p>The major advantage of using ThreadPoolTaskExecutor is that you can modify these values at runtime using <strong>JMX</strong>. But that's the food for another post later on this blog.</p>
<h2 id="heading-creating-threadpooltaskexecutor-configuration">🎯 Creating ThreadPoolTaskExecutor Configuration</h2>
<p>Let's create a ThreadPoolTaskExecutor in a Spring configuration class.</p>
<pre><code>@Configuration
@EnableAsync
public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThreadPoolTaskExecutorConfig</span> </span>{

  @Bean(<span class="hljs-string">"customThreadPoolTaskExecutor"</span>)
  public Executor getThreadPoolTaskExecutor() {
    ThreadPoolTaskExecutor threadPoolTaskExecutor = <span class="hljs-keyword">new</span> ThreadPoolTaskExecutor();
    threadPoolTaskExecutor.setCorePoolSize(<span class="hljs-number">2</span>);
    threadPoolTaskExecutor.setMaxPoolSize(<span class="hljs-number">2</span>);
    threadPoolTaskExecutor.setQueueCapacity(<span class="hljs-number">100</span>);
    threadPoolTaskExecutor.setThreadNamePrefix(<span class="hljs-string">"utopian-thread-"</span>);
    threadPoolTaskExecutor.initialize();
    <span class="hljs-keyword">return</span> threadPoolTaskExecutor;
  }
}
</code></pre><p>You need to annotate <code>@EnableAsync</code> on this configuration class. This ensures that Spring uses thread pool in the background to run <code>@Async</code> methods in your application.</p>
<p>Now with this configuration created, any asynchronous method you write in your Spring application, will use threads from the thread pool for asynchronous processing.</p>
<p>It becomes a very handy feature, and now you don't need to handle Executors on your own. Spring will do that for you based on the configuration provided.</p>
<h2 id="heading-creating-asynchronous-method">🎯 Creating Asynchronous Method</h2>
<p>Let's write a method in service layer, which returns CompletableFuture&gt;. We want our controller to call this asynchronously. This method returns hard coded list of employees.</p>
<pre><code>@Async(<span class="hljs-string">"customThreadPoolTaskExecutor"</span>)
  public CompletableFuture&lt;List&lt;Employee&gt;&gt; getAllEmployees() {

    LOGGER.info(<span class="hljs-string">"EmployeeService.getAllEmployees() running on: {}"</span>,
        Thread.currentThread().getName());

    <span class="hljs-keyword">return</span> CompletableFuture.completedFuture(EMPLOYEES_LIST);
  }
</code></pre><p>I have annotated the method with <code>@Async</code> to allow this method to run asynchronously.</p>
<p>Also notice that I have provided the bean name for Executor which I want to use for this method. In case you have multiple Executor defined, you can annotate your methods with <code>@Async</code> using the executor bean name that you want to use for that method.</p>
<p>Let's now tie this service method from controller. I want to make a GET call to controller and get the list of employees.</p>
<p>Now since we tied the ThreadPoolTaskExecutor in our application, we expect that threads from our configured thread pool will be picked up and used to process the <code>@Async</code> methods.</p>
<pre><code>@GetMapping(<span class="hljs-string">"/employee"</span>)
  public ResponseEntity&lt;List&lt;Employee&gt;&gt; getAllEmployees()
      throws ExecutionException, InterruptedException {

    <span class="hljs-keyword">return</span> ResponseEntity.status(HttpStatus.OK).body(employeeService.getAllEmployees().get());
  }
</code></pre><p>Time to hit the API now. This API is running at port 8080.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1649354822159/-bdfG2I15.png" alt="image.png" /></p>
<p>Let's hit this URL multiple times. We expect that threads from our thread pool will switch among themselves to process our <code>@Async</code> methods in the service layer.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1649354983705/gPQva9tRn.png" alt="image.png" /></p>
<p>As expected! Threads are being picked up from our thread pool and they are being switched among themselves.</p>
<p>Had we two different service hit; say one service hit on <code>@Async</code> method1, and another service hit on <code>@Async</code> method2 then we will be able to see in the console that both these methods are executing by two different threads concurrently.</p>
<h2 id="heading-github-repository">🎯 Github Repository</h2>
<p>I have pushed all the code changes that I used in this article at my <a target="_blank" href="https://github.com/anshulgammy/utopian-nerd/tree/main/usecases/completablefuture-springboot">Github</a> repository. Please check that out.</p>
<p>It has more than one API; so you will be able test the two asynchronous methods in the service layers being executed by two different threads; when hit at the same time by the client.</p>
<p>I hope this post was useful.</p>
]]></content:encoded></item><item><title><![CDATA[Reactive Programming using CompletableFuture in Java]]></title><description><![CDATA[Practical use case that discusses nested operation on CompletableFuture in Java]]></description><link>https://tech.anshulgautam.in/reactive-programming-using-completablefuture-in-java</link><guid isPermaLink="true">https://tech.anshulgautam.in/reactive-programming-using-completablefuture-in-java</guid><category><![CDATA[Java]]></category><category><![CDATA[concurrency]]></category><category><![CDATA[asynchronous]]></category><category><![CDATA[2Articles1Week]]></category><dc:creator><![CDATA[Anshul Gautam]]></dc:creator><pubDate>Thu, 07 Apr 2022 07:27:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649832687155/eQrvzoFgB.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Java 8 introduced <strong>CompletableFuture </strong>as part of it's concurrency API. This is very helpful when we want to nest operations around asynchronous computations, using the native Java API only.</p>
<p>Prior to introducing CompletableFuture, we had <strong>Future</strong> which provided asynchronous callbacks. But there were few problems associated with Future. CompletableFuture addresses them well.</p>
<p>Let's start with understanding what were the issues with Future, that paved the way for CompletableFuture.</p>
<h2 id="heading-drawbacks-with-future">🎯 Drawbacks with Future</h2>
<ul>
<li>We cannot manually complete the Future object</li>
<li>Lack of proper Exception Handling options available</li>
<li>We cannot chain multiple Future objects together</li>
</ul>
<p>In the below example, I am creating a simple Future, and trying to get the result from it.</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FuturesDemo</span> </span>{

  public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main(<span class="hljs-built_in">String</span>[] args) {

    Random random = <span class="hljs-keyword">new</span> Random();

    FutureTask[] futureTaskArray = <span class="hljs-keyword">new</span> FutureTask[<span class="hljs-number">5</span>];

    <span class="hljs-keyword">for</span> (int i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++) {
      futureTaskArray[i] = <span class="hljs-keyword">new</span> FutureTask&lt;Integer&gt;(() -&gt; {
        Thread.sleep(<span class="hljs-number">2000</span>);
        <span class="hljs-keyword">return</span> random.nextInt(<span class="hljs-number">1</span>, <span class="hljs-number">9</span>);
      });
      Thread thread = <span class="hljs-keyword">new</span> Thread(futureTaskArray[i]);
      thread.start();
    }

    <span class="hljs-keyword">for</span> (int i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++) {
      <span class="hljs-keyword">try</span> {
        System.out.println(
            <span class="hljs-string">"Output obtained for FutureTask number "</span> + i + <span class="hljs-string">" : "</span> + futureTaskArray[i].get());
      } <span class="hljs-keyword">catch</span> (InterruptedException e) {
        e.printStackTrace();
      } <span class="hljs-keyword">catch</span> (ExecutionException e) {
        e.printStackTrace();
      }
    }
  }
}
</code></pre><p>There are five <code>FutureTask</code> objects being created here. Each <code>FutureTask</code> has the logic to produce a random number. Output from all these future objects are being obtained in the second for loop where we are doing <code>.get</code> on each of the FutureTask.</p>
<p>Now, what if we had to club the operation on <code>futureTaskArray[1]</code> and <code>futureTaskArray[2]</code> together? Get the output from one, and then supply that to another. This kind of clubbing together of multiple Future is not possible.</p>
<p>Also, see Future do not provide any manual way to end the future. There is no method provided for it. So if there is any <code>FutureTask</code> taking more time, the main thread will stay blocked.</p>
<h2 id="heading-completablefuture-to-the-rescue">🎯 CompletableFuture to the rescue</h2>
<p>CompletableFuture helps us in solving the issues that we had with Future. It provides more robust way to do asynchronous computations. There are lots of helpful method operations provided to us out of the box.</p>
<p>Let's have a look on some key methods from CompletableFuture</p>
<ul>
<li><p><code>runAsync()</code>: This is helpful when we want some instructions to run asynchronously and we do not expect any output.
This method takes Runnable, and there is one more overloaded method which takes Runnable and Executor.
If you are not providing Executor to runAsync(), then threads will be picked up from common fork join pool. If you have provided the Executor, then threads will be picked from the Executor's thread pool.</p>
</li>
<li><p><code>supplyAsync()</code>: This is helpful when we want to execute some instructions asychronously and also expect some output. This method takes Supplier type, and there is one more overloaded method which takes Supplier and Executor.
If you are not providing Executor to supplyAsync(), then threads will be picked up from common fork join pool. If you have provided the Executor, then threads will be picked from the Executor's thread pool.</p>
</li>
</ul>
<h2 id="heading-hands-on-example">🎯 Hands on example</h2>
<p>Let's create a CompletableFuture object and play around it.</p>
<pre><code>CompletableFuture&lt;List&lt;Employee&gt;&gt; getNewJoinerEmployees(List&lt;Employee&gt; employees,
      ExecutorService executorService)
      throws ExecutionException, InterruptedException {
    <span class="hljs-keyword">return</span> CompletableFuture.supplyAsync(() -&gt; {
      System.out.println(<span class="hljs-string">"getNewJoinerEmployees on thread: "</span> + Thread.currentThread().getName());
      List&lt;Employee&gt; employeesList = employees.stream().filter(
              employee -&gt; ChronoUnit.MONTHS.between(employee.getDateOfJoining(), LocalDate.now()) &lt;= <span class="hljs-number">6</span>)
          .collect(Collectors.toList());
      System.out.println(employeesList);
      <span class="hljs-keyword">return</span> employeesList;
    }, executorService);
  }
</code></pre><p>In this example we are working on <code>List&lt;Employee&gt;</code> and filtering out those Employees who have not yet completed more than six months of tenure in their offices.
This <code>List&lt;Employee&gt;</code> is being returned as CompletableFuture.</p>
<p>Now let's see how can we apply nested operation on this returned CompletableFuture object, <code>thenApply()</code>, and <code>thenRun()</code>.</p>
<p>In this example, we want to get list of employees who have not completed the 6 months in their offices, and for those employees we want to send an email to complete mandatory trainings. After having sent the email, we want this application to shut down.</p>
<pre><code><span class="hljs-keyword">try</span> {
      <span class="hljs-comment">// Fetching all the employees present in the company's database.</span>
      <span class="hljs-comment">// (Tried to simulate such a situation, there is no DB though in this example)</span>
      employeesService
          .getAllEmployeesCompletableFuture(executorService)
          .thenApply(
              <span class="hljs-comment">// Fetching those employees who are new joiners,</span>
              <span class="hljs-comment">// whose System Current Date - DateOfJoining &lt;= 6 months</span>
              employees -&gt; {
                <span class="hljs-keyword">try</span> {
                  <span class="hljs-keyword">return</span> employeesService.getNewJoinerEmployees(employees, executorService);
                } <span class="hljs-keyword">catch</span> (ExecutionException ex) {
                  ex.printStackTrace();
                  <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
                } <span class="hljs-keyword">catch</span> (InterruptedException ex) {
                  ex.printStackTrace();
                  <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
                }
              })
          .thenApply(
              <span class="hljs-comment">// Fetching those employees who are new joiners,</span>
              <span class="hljs-comment">// and whose trainings are not yet completed.</span>
              employees -&gt; {
                <span class="hljs-keyword">try</span> {
                  <span class="hljs-keyword">return</span> employeesService.getTrainingsNotCompletedEmployees(employees.get(),
                      executorService);
                } <span class="hljs-keyword">catch</span> (InterruptedException e) {
                  e.printStackTrace();
                  <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
                } <span class="hljs-keyword">catch</span> (ExecutionException e) {
                  e.printStackTrace();
                  <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
                }
              })
          .thenAccept(
              <span class="hljs-comment">// Collecting List&lt;String&gt; emailIds of those new joiner employees who have not</span>
              <span class="hljs-comment">// completed their trainings, and sending reminder email on those email ids.</span>
              employees -&gt; {
            <span class="hljs-keyword">try</span> {
              employeesService.sendEmailsToEmployeesForTraining(employees.get(),
                  executorService);
            } <span class="hljs-keyword">catch</span> (InterruptedException e) {
              e.printStackTrace();
            } <span class="hljs-keyword">catch</span> (ExecutionException e) {
              e.printStackTrace();
            }
          })
          <span class="hljs-comment">// After all the CompletableFuture are done, doing System.exit() to terminate</span>
          <span class="hljs-comment">// the application.</span>
          .thenRun(() -&gt; {
            System.exit(<span class="hljs-number">0</span>);
          });
    } <span class="hljs-keyword">catch</span> (InterruptedException e) {
      e.printStackTrace();
    } <span class="hljs-keyword">catch</span> (ExecutionException e) {
      e.printStackTrace();
    }
</code></pre><p><code>thenApply()</code> takes in Function type. It accepts a Function instance and uses it to process the result and then returns a Future object result.</p>
<p><code>thenAccept()</code> takes in Consumer type.</p>
<p><code>thenRun()</code> takes in the Runnable type.</p>
<p>Like a DSL, we have nested the operation on different CompletableFuture in the example above.</p>
<h2 id="heading-github-repository">🎯 Github Repository</h2>
<p>Code that I have used in this article is available at my <a target="_blank" href="https://github.com/anshulgammy/utopian-nerd/tree/main/usecases/java/completable-futures-demo">Github</a> repository. Please check that out as well.</p>
<h2 id="heading-conclusion">🎯 Conclusion</h2>
<p>In this article we discussed with very basic examples that how can we implement CompletableFuture, and what were the drawbacks with Future.</p>
]]></content:encoded></item><item><title><![CDATA[Docker Refresher]]></title><description><![CDATA[Basics of Docker to help developers get quick started with containerization]]></description><link>https://tech.anshulgautam.in/docker-refresher</link><guid isPermaLink="true">https://tech.anshulgautam.in/docker-refresher</guid><category><![CDATA[Java]]></category><category><![CDATA[Docker]]></category><category><![CDATA[docker images]]></category><category><![CDATA[2Articles1Week]]></category><dc:creator><![CDATA[Anshul Gautam]]></dc:creator><pubDate>Tue, 05 Apr 2022 12:56:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649831752951/qJetBOnlR.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-lets-start-by-understanding-what-is-docker">🔍 Let's start by understanding what is Docker?</h2>
<p>Docker is a platform for building, running, and shipping applications which run and perform the same way everywhere else; just like the way it is supposed to work on the developer's machine.</p>
<p>When a developer is building an application, it is not supposed to run only on his machine. Ultimately we want to move this to different environments; like QA for testing, may be move to Staging environment for some pre-production testing or for user acceptance testing, and then move to production environment where our end users will be using the application. That's the end goal basically.</p>
<p>More often we come across applications not working the same way in all the environments. This can be because of several reasons, I am naming few of them here:</p>
<ul>
<li>One or more files are missing</li>
<li>Software version mismatch</li>
<li>Different configuration settings in different environments and mismatch between them</li>
<li>Different operating system in the target environment</li>
</ul>
<p>Well, now with the essence of Docker as a platform that you have, you can relate to how Docker can solve above problems. It will solve these problems by giving you the  runtime that you need to run your application everywhere, be it development environment, or QA, or staging, or production. If it runs at one place, it is guaranteed to run at every other place, provided that you have Docker installed at those every other place.</p>
<p>While we are discussing on runtime environment, on the same note, we are aware that a developer needs to create that environment on the development machine so that he or she can start working. The developer would install MySQL, Java, Cassandra etc... and then tune these to the expected configuration values.</p>
<p>So much effort goes into it. Isn't it?</p>
<p>Docker helps you ease off these pain points. You just provide a list of things that you need to prepare the runtime environment for your application, and Docker will make sure that all those are there for you.</p>
<p>It's like you asking your friend, "hey this is the grocery list, get them for me; and after you have brought them, place them at these these places; and then you please boil two eggs for me." And your friend does that for you. 
If you have a good friend, you can ask for even more, like may be ask to prepare sandwiches as well after the grocery is done. </p>
<p>That friend is <strong>Docker</strong>.</p>
<p>So why wait? Go ahead and <a target="_blank" href="https://docs.docker.com/engine/install/">install</a> Docker on your local system. And once you are done, read on!</p>
<h2 id="heading-the-dockerfile">🔍 The Dockerfile</h2>
<p>The '<strong>Dockerfile</strong>' is the file, with no extension, that you will use to write steps for instructing the Docker Engine. The Docker engine reads through the steps mentioned in the Dockerfile, and uses that to prepare an image which we call as '<strong>Docker Image</strong>'.</p>
<p>So, if we revisit the grocery store example above, the Dockerfile is that piece of paper on which you prepare the list of items, and all other information on what your friend has to do. </p>
<h2 id="heading-the-docker-image">🔍 The Docker Image</h2>
<p><strong>Docker Image</strong> is like a blue print, a packaged template plan, which will be used to create one or more real time instance of your runtime environment, called '<strong>Docker Container</strong>'.</p>
<p>You can relate Docker Image and the Docker Container something like this,</p>
<blockquote>
<p>If Docker Image is a 'class', then Docker Containers are 'instances' of that class.</p>
</blockquote>
<p>Cool Stuff! Isn't it?</p>
<p>Docker images are comprised of several layers. Each instruction/step in your Dockerfile forms a layer in the image.
When Docker Engine creates your container, it reads through the image file and performs its operation in layered approach.</p>
<p>Reads first instruction, executes that instruction... One layer done.
Reads second instruction, executes that instruction... Second layer done.</p>
<p>So on, and so forth.</p>
<h2 id="heading-the-docker-container">🔍 The Docker Container</h2>
<p>Like I said above, <strong>Docker Containers</strong> are real time instances of the Docker Image.
The Docker Container is an enclosure, an isolated environment, inside which your application will run. It will have all the necessary dependencies present along with configuration for your application to run.</p>
<p>Docker packages all the perquisites required for your application like operating system, libraries etc. and create a runtime environment in the docker container for our application.</p>
<p>All this is done by issuing a single docker command.</p>
<p>To summarize the discussion we did so far, as a developer you will:</p>
<ul>
<li>Install Docker on your machine</li>
<li>Write a Dockerfile which will have necessary instructions to Docker Engine</li>
<li>Issue a command to start building the image from Docker file. (Hey Docker! Go ahead and build an image for me using this Dockerfile)</li>
<li>Issue a command to start the docker container. (Hey Docker! I saw you created the image. Now run this image)</li>
</ul>
<p>There are lots of commands in Docker CLI, through which we ask Docker Engine to do stuffs for us. I want to show handful number of those commands to you. But a bit later. Please bear with me.</p>
<h2 id="heading-docker-container-vs-virtual-machinesvm">🔍 Docker Container vs Virtual Machines(VM)</h2>
<p>Dockerized Application run in Docker Container, which is an isolated environment from the host machine.</p>
<p>Virtual Machines also provide us an isolated environment to run our application with all the libraries and configurations.</p>
<p>But Docker is different from Virtual Machine.</p>
<p>Virtual Machines are an abstraction of a physical hardware machine, built over the Hypervisor. </p>
<p><strong>Hypervisors </strong>manage Virtual Machines.</p>
<p>With Virtual Machines:</p>
<ul>
<li>Each VM needs a full-blown OS. If these OS are licensed, then just think of the associated overall cost.</li>
<li>These are slow to start.</li>
<li>These are very resource intensive. They take up certain percentage of the physical hardware associated with your host machine. For example, if you have two virtual machines running, then your physical RAM and CPU gets divided among those two VMs, after setting aside some of these resources for the host machine to run itself.</li>
</ul>
<p>With Docker:</p>
<ul>
<li>Docker as a platform is installed just like any other application on your host operating system. It will then work as a service in the background on your operating system.</li>
<li>Containers give us isolation, but they are lightweight.</li>
<li>They don't need a full blown OS, instead they make use of OS on the host. A Linux container requires a Linux kernel on the host. A Windows container requires a windows kernel.</li>
<li>Need less hardware resources.</li>
<li>They start quickly.</li>
<li>Docker containers are meant to run the application or a service. Unlike Virtual Machine, they are not meant to host an operating system altogether.
Once the service or application running inside the container crashes or stops, the container stops as well.</li>
</ul>
<h2 id="heading-docker-architecture">🔍 Docker Architecture</h2>
<p>The Docker as a platform is comprised of Client Server Architecture. It is installed on a host machine, running Linux/Windows kernel.
Client component talks to Server Component, called as Docker Engine. 
The communication between the client and server component happens over REST APIs, over UNIX sockets or a network interface.</p>
<p>The Docker Engine has a long-running daemon process, '<strong>dockerd</strong>'. dockerd keeps listening to the commands issued, and executes them.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1649090773348/7oEOfNuw1.png" alt="docker architecture.png" /></p>
<p>Docker client and the docker daemon can run on the same host or can run on different hosts and communicate through sockets or a Restful API.</p>
<p>As shown in the diagram, we issue commands at Client side, using the CLI.</p>
<p><strong>Registry </strong>is like 'Github' for Docker Images. We pull a docker image from or push a docker image to Docker Registry. Docker provides a public registry for us, called <a target="_blank" href="https://hub.docker.com/">Docker Hub</a>, where base images from most of the vendors are available. On top of that base image, we can start building our own image.</p>
<h2 id="heading-a-handful-of-docker-commands">📍 A Handful of Docker Commands</h2>
<p>I deliberately delayed Docker Commands. I have seen people jumping to docker commands directly without understanding the bare minimum concept behind docker.</p>
<p>Now, if you have read through the concepts so far that I discussed, let's see some docker commands that we can execute in docker CLI. </p>
<p><strong>run</strong>- start a container.</p>
<p>This command starts a container using a Docker Image. In case the image doesn't exist in local, docker will pull this image from Docker Hub and then run the container for us.</p>
<p>You can use <strong>tag</strong>, after the semicolon in the image name, to run a particular version.</p>
<p>eg:</p>
<pre><code>docker run nginx:<span class="hljs-number">5.2</span>
</code></pre><p>Use <strong>-i</strong> flag to run in the interactive mode. You can club this with <strong>-t</strong> flag as well to attach a pseudo terminal.</p>
<p>eg:</p>
<pre><code>docker run java-program-image:latest -it
</code></pre><p>While running your docker image with docker run, if you haven't provided the container name then docker will use a default container name for it. But in case you want to name a container, then you can do like below using <strong>--name</strong> flag.</p>
<pre><code>docker run --name bumbler-java java-program-image:latest
</code></pre><p>Port mapping can be achieved by using <strong>-p</strong> flag. It tells at what port of the host, the container's port will be accessible.</p>
<p>eg:</p>
<pre><code>docker run -p <span class="hljs-number">8705</span>:<span class="hljs-number">8705</span> java-program
</code></pre><p>Using docker run, it runs in <strong>attached </strong>mode.
This means, the container will be running in the <strong>foreground</strong>. You would need to press <strong>Ctrl + C</strong> to stop the continuous logs, which will also stop the container.
If you want to run in <strong>background </strong>in <strong>detached </strong>mode, then use the <strong>-d</strong> flag.</p>
<p>eg:</p>
<pre><code>docker run -d nginx
</code></pre><p>If you want to get a detached container to attached mode, then we can do using '<strong>attach</strong>'.</p>
<p>eg:</p>
<pre><code>docker attach &lt;container_id&gt;
</code></pre><p><strong>ps </strong>- lists running containers. Use <strong>-a</strong> to see all container, running as well as stopped containers</p>
<p>eg:</p>
<pre><code>docker ps
docker ps -a
</code></pre><p><strong>stop </strong>- stops a running container.</p>
<p>eg:</p>
<pre><code>docker stop silly_sammet
</code></pre><p><strong>rm </strong>- remove a stopped container</p>
<p>eg:</p>
<pre><code>docker rm silly_sammet
</code></pre><p><strong>images </strong>- List images</p>
<p>eg:</p>
<pre><code>docker images
</code></pre><p><strong>rmi </strong>- Remove images which are no longer required</p>
<p>eg:</p>
<pre><code>docker rmi nginx
</code></pre><p>We would need to remove all the dependent images before we can delete this image.</p>
<p><strong>pull </strong>- download an image, and not run it</p>
<p>eg:</p>
<pre><code>docker pull nginx
</code></pre><p><strong>exec </strong>- execute a command inside the container</p>
<p>eg:</p>
<pre><code>docker exec container_name cat /etc/hosts
</code></pre><p>This command will print the content of hosts file present in the container.</p>
<p><strong>environment variables</strong> (-e, --env, --env-file) - Use the -e, --env, and --env-file flags to set environment variables in the container you are running, or overwrite variables that are defined in the Dockerfile of the image.</p>
<p>eg:</p>
<pre><code>docker run -e MYVAR1=bar --env MYVAR2=foo --env-file ./env.list ubuntu bash
</code></pre><p>The next section in this article tries to containerize a simple Java program. I will try to cover few more concepts as part of that example. But before going to that section, I urge you to pull an image from docker hub and run in your local. Concepts, and the commands we discussed so far are enough to help you with this.</p>
<p>So what I expect you to do is:</p>
<ul>
<li>Pull <strong>hello-world</strong> image from <a target="_blank" href="https://hub.docker.com/_/hello-world">docker hub</a></li>
<li>Run this image in a container whose container should be named as 'bumbler-container'</li>
<li>The container's port 1234 should be exposed to host machine at port 7890.</li>
</ul>
<p>If you were able to run this, then please comment the output you got in comments section of this article.</p>
<h2 id="heading-containerizing-a-java-application-demo">📍 Containerizing a Java Application Demo</h2>
<p>I have a simple Java class, which greets the user with Hello. I want to containerize it; ie this Java program should run inside docker container.</p>
<p>Let's have a look on the Java program</p>
<pre><code>package dev.bumbler;

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

    public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main(<span class="hljs-built_in">String</span>[] args) {
        System.out.println(<span class="hljs-string">"Hello "</span> +  System.getenv(<span class="hljs-string">"user"</span>) + <span class="hljs-string">"!"</span>);
    }
}
</code></pre><p>The program will take the name of the user from environment variable, and will print 'Hello ${user}', where ${user} will be filled with the user's name.</p>
<p>If you notice closely, I have used a package for this class. When I will write the Dockerfile I need to ensure that the package structure is also addressed in my instruction.</p>
<p>Okay, let's create the Dockerfile.</p>
<pre><code># Start <span class="hljs-keyword">with</span> a base image containing Java runtime
FROM openjdk:<span class="hljs-number">17</span>

# Setting an environment variable <span class="hljs-keyword">with</span> a <span class="hljs-keyword">default</span> value
ENV user user

# creating a <span class="hljs-keyword">new</span> directory inside container
RUN mkdir /<span class="hljs-keyword">var</span>/java-docker-demo/

# Copying contents inside the src folder to our newly created directory inside container
COPY /src/ <span class="hljs-regexp">/var/</span>java-docker-demo/

# setting work directory <span class="hljs-keyword">for</span> the docker RUN/CMD/ENTRYPOINT commands
WORKDIR /<span class="hljs-keyword">var</span>/java-docker-demo/

# At the time <span class="hljs-keyword">of</span> building the image, asking docker to compile the Java file <span class="hljs-keyword">as</span> well
RUN javac dev/bumbler/JavaDockerDemo.java

# Instructing docker to run the program when I start the container
ENTRYPOINT [<span class="hljs-string">"java"</span>, <span class="hljs-string">"dev/bumbler/JavaDockerDemo"</span>]
</code></pre><p>Each of the instruction in the Dockerfile will form a layer while building the image.</p>
<p>I have used <strong>openjdk:17</strong> as the base image. Docker will go and fetch this image from Docker Hub. On top of this image, we are instructing the Docker what to do next.</p>
<p>Comments that I have mentioned on each instruction is kind of self explanatory, and I hope they explain you why I used them. But I will explain few of them.</p>
<p>The <strong>RUN</strong> takes the command that we want to run at the time of building the image. This will not be executed at the time of starting the container.</p>
<p><strong>ENTRYPOINT </strong>executes the command when container is starting. That is why I used java file run command in ENTRYPOINT.</p>
<p>We can also use <strong>CMD </strong>to execute our command when container starts. If you have more than one CMD, then only the last CMD command will be executed.</p>
<p><strong>ENV</strong> initializes an environment variable. In case we do not provide any argument at the time of starting the container, then the default will be used; which is 'user' here in this case.
You can also do the same thing using <strong>ARG</strong>. But then, this variable will be accessible at the time of building the image only. With <strong>ENV</strong>, we have this value available at the time of building the image, as well as at the time of running the container.</p>
<p>We build this image using the command from the CLI:</p>
<pre><code>docker build . -t java-docker-demo
</code></pre><p>Docker will show us below in the CLI logs output:</p>
<pre><code>Sending build context to Docker daemon  <span class="hljs-number">36.86</span>kB
Step <span class="hljs-number">1</span>/<span class="hljs-number">7</span> : FROM openjdk:<span class="hljs-number">17</span>
<span class="hljs-number">17</span>: Pulling <span class="hljs-keyword">from</span> library/openjdk
<span class="hljs-attr">e4430e06691f</span>: Pull complete
<span class="hljs-number">99</span>ce5342b806: Pull complete
<span class="hljs-number">603e156</span>f2a3d: Pull complete
<span class="hljs-attr">Digest</span>: sha256:<span class="hljs-number">3</span>d88de143bdd54d3e873302355564818e0ac0d17dbacc9869090197b7dd8a8f3
<span class="hljs-attr">Status</span>: Downloaded newer image <span class="hljs-keyword">for</span> openjdk:<span class="hljs-number">17</span>
 ---&gt; <span class="hljs-number">34</span>aba91dbd13
Step <span class="hljs-number">2</span>/<span class="hljs-number">7</span> : ENV user user
 ---&gt; Running <span class="hljs-keyword">in</span> b6c63f968b4d
Removing intermediate container b6c63f968b4d
 ---&gt; <span class="hljs-number">338685</span>f87805
Step <span class="hljs-number">3</span>/<span class="hljs-number">7</span> : RUN mkdir /<span class="hljs-keyword">var</span>/java-docker-demo/
 ---&gt; Running <span class="hljs-keyword">in</span> dee95735538c
Removing intermediate container dee95735538c
 ---&gt; <span class="hljs-number">4</span>cc8ad362972
Step <span class="hljs-number">4</span>/<span class="hljs-number">7</span> : COPY /src/ <span class="hljs-regexp">/var/</span>java-docker-demo/
 ---&gt; <span class="hljs-number">784</span>de505e733
Step <span class="hljs-number">5</span>/<span class="hljs-number">7</span> : WORKDIR /<span class="hljs-keyword">var</span>/java-docker-demo/
 ---&gt; Running <span class="hljs-keyword">in</span> <span class="hljs-number">105585</span>b3a226
Removing intermediate container <span class="hljs-number">105585</span>b3a226
 ---&gt; <span class="hljs-number">7032</span>efa086e5
Step <span class="hljs-number">6</span>/<span class="hljs-number">7</span> : RUN javac dev/bumbler/JavaDockerDemo.java
 ---&gt; Running <span class="hljs-keyword">in</span> <span class="hljs-number">1693</span>d31fdb81
Removing intermediate container <span class="hljs-number">1693</span>d31fdb81
 ---&gt; <span class="hljs-number">2</span>cf1e43cfeaf
Step <span class="hljs-number">7</span>/<span class="hljs-number">7</span> : ENTRYPOINT [<span class="hljs-string">"java"</span>, <span class="hljs-string">"dev/bumbler/JavaDockerDemo"</span>]
 ---&gt; Running <span class="hljs-keyword">in</span> <span class="hljs-number">4</span>aa6afeaa459
Removing intermediate container <span class="hljs-number">4</span>aa6afeaa459
 ---&gt; <span class="hljs-number">206</span>edabe9cb5
Successfully built <span class="hljs-number">206</span>edabe9cb5
Successfully tagged java-docker-demo:latest
</code></pre><p>I didn't have the openjdk image in my local. That is why it was fetched from the registry. Notice how our instructions from the Dockerfile are getting executed in steps, one after the another, in a layered way.</p>
<p>Now our image <strong>java-docker-demo</strong> is ready. Next, I will run this image on the container.</p>
<pre><code>docker run --name java-docker-demo-container java-docker-demo
</code></pre><p>It prints 'Hello user!'. We have not passed the value for environment variable. Next, I will run this by providing environment variable using <strong>-e</strong> flag.</p>
<pre><code>docker run --name java-docker-demo-container -e user=Bumbler java-docker-demo
</code></pre><p>I passed the user value as <strong>Bumbler</strong>. Let's see the output.</p>
<p>Output:</p>
<pre><code>Hello Bumbler!
</code></pre><h2 id="heading-conclusion">🪄 Conclusion</h2>
<p>I hope this post gave you an idea on Docker, and will help you to quickly start working with it.
Once you are comfortable with these concepts, you might want to start with Docker Compose. It helps you define, manage and share multi-container applications which are supposed to work together.</p>
<p>All the code changes I used in this article are present at my <a target="_blank" href="https://github.com/anshulgammy/utopian-nerd/tree/main/usecases/java/java-docker-demo">Github</a> repository. Do not forget to checkout.</p>
]]></content:encoded></item><item><title><![CDATA[Reactive Programming in Spring Boot Application]]></title><description><![CDATA[Learn basics of Reactive Services Implementation in Spring Boot Applications using Project Reactor]]></description><link>https://tech.anshulgautam.in/reactive-programming-in-spring-boot-application</link><guid isPermaLink="true">https://tech.anshulgautam.in/reactive-programming-in-spring-boot-application</guid><category><![CDATA[Spring]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[Reactive Programming]]></category><category><![CDATA[Java]]></category><category><![CDATA[projects]]></category><dc:creator><![CDATA[Anshul Gautam]]></dc:creator><pubDate>Sun, 27 Mar 2022 17:38:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649832168637/cFtUvbIKZ.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In one of my previous <a target="_blank" href="https://tech.anshulgautam.in/reactive-programming-using-rxjava">post</a> on this website, I had discussed about Reactive Programming, and how we can implement that in Java using RxJava.</p>
<p>In this post, I will be discussing on building a Reactive Spring Boot Application.
The application that I will build is going to be a very simple Restful API, which will have two endpoints.
One endpoint will fetch the data synchronously. Another endpoint will fetch the same data asynchronously.</p>
<p>In case you need a very quick overview on Spring Boot, you can check out <a target="_blank" href="https://bumbler.anshulgautam.in/spring-boot-refresher">here</a>.</p>
<h2 id="heading-libraries-available-for-reactive-programming-in-java">🎯 Libraries available for Reactive Programming in Java</h2>
<p>Among popular Reactive Programming Libraries for Java, the three most frequently used libraries are:</p>
<ul>
<li>RxJava</li>
<li>Reactor</li>
<li>Java 9 Flow Reactive Stream</li>
</ul>
<p>In this article, I am going to use Reactor, from <a target="_blank" href="https://projectreactor.io/">Project Reactor</a>.</p>
<h2 id="heading-reactor">🎯 Reactor</h2>
<p>Spring is known for creating wrappers around the underlying specification, and offer easier integration of those specifications in Spring Applications.</p>
<p>In case you are wondering what is Reactor, this is what the official documentation states:</p>
<blockquote>
<p>Reactor is a fourth-generation reactive library, based on the Reactive Streams
specification, for building non-blocking applications on the JVM.</p>
</blockquote>
<p>With Reactor, we get seamless integration of reactive programming in our Spring applications.</p>
<p>As part of Project Reactor, we get several modules that we can include in our application. Each module has its own purpose to fulfill.</p>
<p>I will be working with <strong>Reactor Core</strong> and <strong>Reactor Netty</strong> mostly in this article.</p>
<h2 id="heading-prerequisite-concepts">🎯 Prerequisite concepts</h2>
<p>Before we dive into the implementation, lets revisit important underlying concepts around Reactive Programming and Reactive Systems.</p>
<p><strong>1. Reactive Programming is not Reactive System in itself.</strong></p>
<p>Reactive programming is development model structured around asynchronous data streams.</p>
<p>Reactive Manifesto defines what are Reactive Systems. It is an architectural style to build responsive distributed systems. The manifesto mentions of four key properties:</p>
<p><strong>Responsive</strong>: A reactive system needs to handle requests in a reasonable time.</p>
<p><strong>Resilient</strong>: A reactive system must stay responsive in the face of failures (crash, timeout, 500 error etc), so it must be designed for failures and deal with them appropriately.</p>
<p><strong>Elastic</strong>: A reactive system must stay responsive under various loads. Consequently, it must scale up and down, and be able to handle the load with minimal resources.</p>
<p><strong>Message driven</strong>: Components from a reactive system interacts using asynchronous message passing.</p>
<p>Just by including reactive programming in our application, the application doesn't become a Reactive System. For an application to be a Reactive System, it must obey all the properties mentioned by the Reactive Manifesto.</p>
<p><strong>2. Thread Per Request Model</strong></p>
<p>Application servers create a new thread for every incoming request.</p>
<p>When a request comes to the server then a new thread is created. For a blocking call, this thread synchronously executes the instructions as part of processing the request. It needs to wait for IO operations like getting response from some external API, or to get response from the database, etc. It stays blocked, until the response arrives to it. Meanwhile, if another request comes in to the server, the server creates a new thread again to process that new request.</p>
<p>Usually, there is a limit to the number of threads that can be created in the server, which is decided by the Thread Pool limit for the server. Beyond this limit, no new threads can be created. So its evident that no new request will be served once the thread pool limit is reached.</p>
<p>Also, thread creation is costly. So to keep creating new threads for every incoming request doesn't seem to be a correct. Right?</p>
<p>Reactive Programming tries to solve this problem. Here the thread from the thread pool doesn't stay blocked for IO operation. Instead, it executes the instruction and return to serve another request. Once response to IO operation needed by the thread arrives through interrupt or a callback, processing happens, and the service response to the user is returned.</p>
<p>This way, effective utilization of resources is achieved, with bare minimum burden to the application server.</p>
<p><strong>3. Horizontal Scaling</strong></p>
<p>With hardware costs getting cheaper, cloud services becoming cheaper, at first glance it seems appropriate to have more instances put together and the system be horizontally scaled when load increases. But think for a while, there is still cost involved whenever you spin up a new instance.</p>
<p>Why not solve this issue with one instance only? </p>
<p>With asynchronous calls in reactive programming we effectively utilize our threads. This way without spinning up extra servers, loadbalancers, we will be able to manage with single instance of the service only. It makes the whole deal even more cheaper.</p>
<p><strong>4. Backpressure</strong></p>
<p>Backpressure solves the flow control problem in the network. </p>
<p>When the consumer is overwhelmed with the huge volume of data arriving to it for processing, the entire system gets impacted.</p>
<p>In Reactive Programming with non-blocking calls, the consumer can ask publisher to send data in smaller amount which it can handle. It's like asking I can process 100 elements at a time, give me this much Mr. Publisher. Once I complete processing this 100 elements, send me the next 100. This way, the entire system can stay in motion all the time.</p>
<p><strong>5. Data Flow as Event Driven Stream</strong></p>
<p>In traditional database systems, a thread connects to database and waits until the data arrives.
We have event driven database systems now, which make use of reactive database drivers like <strong>reactive mongodb</strong>, that respond to the request via event stream.</p>
<p>With Reactive Programming, thread from the application makes a call to Reactive Repository of underlying database system asking for data, and then returns. The database system after having collected the data raises another event with the sought data. The thread gets this data through the event stream and then can process it.</p>
<p>This way, database systems also contribute to making the whole IO operation asynchronous.</p>
<h2 id="heading-lets-play-with-reactor">🎯 Let's play with Reactor</h2>
<p>Start by adding Spring Reactive Web dependency in our maven project. I created the project from <a target="_blank" href="https://start.spring.io">Spring Initializr</a>, and chose to have Spring Reactive Web dependency. </p>
<p>In case you are going to add this dependency directly in your pom.xml, then below are its coordinates.</p>
<pre><code>&lt;dependency&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-webflux<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span></span>
&lt;/dependency&gt;
</code></pre><p>Before we start writing the web service, it will be better if we get our hands dirty with few Reactor data types and understand about their key offerings.</p>
<p>We can create a junit test class and start playing.</p>
<p>Let's try creating a <em>Mono </em>and a <em>Flux </em>object and try subscribing to them.</p>
<p><em>Mono</em> and <em>Flux</em> are Publishers in Reactor. This means that they are responsible for publishing the data.</p>
<p><em>Mono</em>, as per the literal meaning of the term '<strong>mono</strong>' serves us with only one element.</p>
<p><em>Flux</em> on the other hand serves with more than one elements. It is a stream of single type of items over time.</p>
<pre><code>    @Test
    public <span class="hljs-keyword">void</span> testMono() {
        Mono&lt;<span class="hljs-built_in">String</span>&gt; stringMono = Mono.just(<span class="hljs-string">"Big Bang"</span>);
        stringMono.subscribe(System.out::println);
    }
</code></pre><p>Output:</p>
<pre><code>Output:
Big Bang
</code></pre><p>Here we have created a Mono object using Mono.just(). We subscribe to this Mono using .<em>subscribe()</em>.</p>
<pre><code>    @Test
    public <span class="hljs-keyword">void</span> testFlux() {
        Flux&lt;<span class="hljs-built_in">String</span>&gt; stringFlux = Flux.just(<span class="hljs-string">"Alan"</span>, <span class="hljs-string">"Bob"</span>, <span class="hljs-string">"Mark"</span>);
        stringFlux.subscribe(System.out::println);
    }
</code></pre><p>Output:</p>
<pre><code>Alan
Bob
Mark
</code></pre><p>Here we have created a Flux object, which is going to serve us with three String elements.</p>
<p>We can subscribe to this the same way like Mono, by using .<em>subscribe()</em> on the Flux object.</p>
<p>If you try adding .log() to any of the publisher Mono or Flux, you will be able to see the logs printing from various components of the reactor workflow.</p>
<pre><code>Mono&lt;<span class="hljs-built_in">String</span>&gt; stringMono = Mono.just(<span class="hljs-string">"Big Bang"</span>).log();
stringMono.subscribe(System.out::println);
</code></pre><p>Output:</p>
<pre><code><span class="hljs-number">2022</span><span class="hljs-number">-03</span><span class="hljs-number">-26</span> <span class="hljs-number">21</span>:<span class="hljs-number">33</span>:<span class="hljs-number">44.770</span>  INFO <span class="hljs-number">13104</span> --- [           main] reactor.Mono.Just<span class="hljs-number">.1</span>                      : | onSubscribe([Synchronous Fuseable] Operators.ScalarSubscription)
<span class="hljs-number">2022</span><span class="hljs-number">-03</span><span class="hljs-number">-26</span> <span class="hljs-number">21</span>:<span class="hljs-number">33</span>:<span class="hljs-number">44.785</span>  INFO <span class="hljs-number">13104</span> --- [           main] reactor.Mono.Just<span class="hljs-number">.1</span>                      : | request(unbounded)
<span class="hljs-number">2022</span><span class="hljs-number">-03</span><span class="hljs-number">-26</span> <span class="hljs-number">21</span>:<span class="hljs-number">33</span>:<span class="hljs-number">44.785</span>  INFO <span class="hljs-number">13104</span> --- [           main] reactor.Mono.Just<span class="hljs-number">.1</span>                      : | onNext(Big Bang)
Big Bang
<span class="hljs-number">2022</span><span class="hljs-number">-03</span><span class="hljs-number">-26</span> <span class="hljs-number">21</span>:<span class="hljs-number">33</span>:<span class="hljs-number">44.785</span>  INFO <span class="hljs-number">13104</span> --- [           main] reactor.Mono.Just<span class="hljs-number">.1</span>                      : | onComplete()
</code></pre><p>Appending .log() to the Flux object.</p>
<pre><code>Flux&lt;<span class="hljs-built_in">String</span>&gt; stringFlux = Flux.just(<span class="hljs-string">"Alan"</span>, <span class="hljs-string">"Bob"</span>, <span class="hljs-string">"Mark"</span>).log();
stringFlux.subscribe(System.out::println);
</code></pre><p>Output:</p>
<pre><code><span class="hljs-number">2022</span><span class="hljs-number">-03</span><span class="hljs-number">-26</span> <span class="hljs-number">21</span>:<span class="hljs-number">34</span>:<span class="hljs-number">40.049</span>  INFO <span class="hljs-number">24092</span> --- [           main] reactor.Flux.Array<span class="hljs-number">.1</span>                     : | onSubscribe([Synchronous Fuseable] FluxArray.ArraySubscription)
<span class="hljs-number">2022</span><span class="hljs-number">-03</span><span class="hljs-number">-26</span> <span class="hljs-number">21</span>:<span class="hljs-number">34</span>:<span class="hljs-number">40.049</span>  INFO <span class="hljs-number">24092</span> --- [           main] reactor.Flux.Array<span class="hljs-number">.1</span>                     : | request(unbounded)
<span class="hljs-number">2022</span><span class="hljs-number">-03</span><span class="hljs-number">-26</span> <span class="hljs-number">21</span>:<span class="hljs-number">34</span>:<span class="hljs-number">40.049</span>  INFO <span class="hljs-number">24092</span> --- [           main] reactor.Flux.Array<span class="hljs-number">.1</span>                     : | onNext(Alan)
Alan
<span class="hljs-number">2022</span><span class="hljs-number">-03</span><span class="hljs-number">-26</span> <span class="hljs-number">21</span>:<span class="hljs-number">34</span>:<span class="hljs-number">40.049</span>  INFO <span class="hljs-number">24092</span> --- [           main] reactor.Flux.Array<span class="hljs-number">.1</span>                     : | onNext(Bob)
Bob
<span class="hljs-number">2022</span><span class="hljs-number">-03</span><span class="hljs-number">-26</span> <span class="hljs-number">21</span>:<span class="hljs-number">34</span>:<span class="hljs-number">40.049</span>  INFO <span class="hljs-number">24092</span> --- [           main] reactor.Flux.Array<span class="hljs-number">.1</span>                     : | onNext(Mark)
Mark
<span class="hljs-number">2022</span><span class="hljs-number">-03</span><span class="hljs-number">-26</span> <span class="hljs-number">21</span>:<span class="hljs-number">34</span>:<span class="hljs-number">40.049</span>  INFO <span class="hljs-number">24092</span> --- [           main] reactor.Flux.Array<span class="hljs-number">.1</span>                     : | onComplete()
</code></pre><p>You can see that logs are getting printed from different components of the the reactor workflow. But what are these, and where are they coming from? Let's try to find out.</p>
<h2 id="heading-reactor-core-components">🎯 Reactor Core Components</h2>
<p>Reactor is comprised of three key components. These are all interfaces:</p>
<p><strong>1. Publisher</strong>: This publishes the data. The subscriber needs to subscribe to a publisher in order to get the data from that publisher.</p>
<pre><code>public interface Publisher&lt;T&gt; {
    <span class="hljs-keyword">void</span> subscribe(Subscriber&lt;? <span class="hljs-built_in">super</span> T&gt; var1);
}
</code></pre><p><strong>2. Subscriber</strong>: This is the consumer of the data. It has below four abstract methods.</p>
<pre><code>public interface Subscriber&lt;T&gt; {
    <span class="hljs-keyword">void</span> onSubscribe(Subscription var1);

    <span class="hljs-keyword">void</span> onNext(T var1);

    <span class="hljs-keyword">void</span> onError(Throwable var1);

    <span class="hljs-keyword">void</span> onComplete();
}
</code></pre><p><strong>3. Subscription</strong>: When we do publisher.subscribe(), a subscription gets registered for us. This subscription represents the relationship between publisher and subscriber.</p>
<p>request() method is used to enable backpressure. By passing the long argument to this method we are asking to provide that much amount of data at once.</p>
<p>cancel() method is used to end the subscription relationship between the subscriber and the publisher.</p>
<pre><code>public interface Subscription {
    <span class="hljs-keyword">void</span> request(long var1);

    <span class="hljs-keyword">void</span> cancel();
}
</code></pre><p>The below flow diagram specifies how these three interfaces are inter-connected and how abstract methods declared in these interfaces are getting called, one after the another.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1648314808216/gV60JJZU4.png" alt="publisher-subscription-subscriber.png" /></p>
<p>Now, after having seen this flow diagram, I hope the logs that were getting printed in examples above from the test playground makes more sense.</p>
<p>Let's see how we can handle the error. The syntactical way to handle error is same for Mono and Flux.</p>
<p>In the example below I have explicitly thrown an exception from the Flux. I am handling this exception then at the subscriber level.</p>
<pre><code>Flux&lt;<span class="hljs-built_in">String</span>&gt; stringFlux = Flux
        .just(<span class="hljs-string">"Alan"</span>, <span class="hljs-string">"Bob"</span>, <span class="hljs-string">"Mark"</span>)
        .concatWith(Flux.error(<span class="hljs-keyword">new</span> RuntimeException(<span class="hljs-string">"Some Error Occurred"</span>)))
        .concatWithValues(<span class="hljs-string">"Lucy"</span>)
        .log();
stringFlux.subscribe(System.out::println, error -&gt; {
    System.out.println(<span class="hljs-string">"Subscriber has received some error: "</span> + error.getMessage());
});
</code></pre><p>Fair enough. So far, we got out hands dirty with the very basics of reactor in spring boot. </p>
<p>Let's start writing a simple Restful API in Spring Boot.</p>
<h2 id="heading-writing-the-restful-api">Writing the Restful API</h2>
<p>Our application will expose two endpoints.</p>
<ul>
<li><strong>/v1/api/students</strong>: It fetches student details synchronously.</li>
<li><strong>/v1/api/async/students</strong>: It fetches student details asynchronously.</li>
</ul>
<p>Student class has bare minimum attributes</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span> </span>{

    private long Id;
    private <span class="hljs-built_in">String</span> name;

    public Student(long id, <span class="hljs-built_in">String</span> name) {
        Id = id;
        <span class="hljs-built_in">this</span>.name = name;
    }

    public long getId() {
        <span class="hljs-keyword">return</span> Id;
    }

    public <span class="hljs-keyword">void</span> setId(long id) {
        Id = id;
    }

    public <span class="hljs-built_in">String</span> getName() {
        <span class="hljs-keyword">return</span> name;
    }

    public <span class="hljs-keyword">void</span> setName(<span class="hljs-built_in">String</span> name) {
        <span class="hljs-built_in">this</span>.name = name;
    }
}
</code></pre><p>We will start with the controller now.</p>
<pre><code>@RestController
@RequestMapping(<span class="hljs-string">"/v1/api"</span>)
public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">StudentController</span> </span>{

    private StudentService studentService;

    @Autowired
    public StudentController(StudentService studentService) {
        <span class="hljs-built_in">this</span>.studentService = studentService;
    }

    <span class="hljs-comment">/**
     * Fetches List of Students synchronously.
     *
     * <span class="hljs-doctag">@return </span>- ResponseEntity&lt;List&lt;Student&gt;&gt;
     */</span>
    @GetMapping(<span class="hljs-string">"/students"</span>)
    public ResponseEntity&lt;List&lt;Student&gt;&gt; getSyncStudents() {
        <span class="hljs-keyword">return</span> ResponseEntity.ok(studentService.getStudentsList());
    }

    <span class="hljs-comment">/**
     * Fetches Flux of Students.
     *
     * <span class="hljs-doctag">@return </span>- Flux&lt;Student&gt;
     */</span>
    @GetMapping(value = <span class="hljs-string">"/async/students"</span>, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux&lt;Student&gt; getAsyncStudents() {
        <span class="hljs-keyword">return</span> studentService.getStudentsFlux();
    }
}
</code></pre><p>StudentService is injected in this controller.</p>
<p>At getAsyncStudents() method, you will observe I have used produces of type MediaType.TEXT_EVENT_STREAM_VALUE. This is required to emit the response as asynchronous event stream.</p>
<p>Now, let's have a look on the StudentService class.</p>
<pre><code>@Service
public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">StudentService</span> </span>{

    public List&lt;Student&gt; getStudentsList() {
        List&lt;Student&gt; fetchedStudentList =
                IntStream.rangeClosed(<span class="hljs-number">1</span>, <span class="hljs-number">20</span>)
                        .peek(element -&gt; System.out.println(<span class="hljs-string">"Fetched student with id: "</span> + element))
                        .peek(StudentService::sleep)
                        .mapToObj(element -&gt; {
                            int rollNumber = element;
                            <span class="hljs-built_in">String</span> name = <span class="hljs-string">"Student "</span> + rollNumber;
                            <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Student(rollNumber, name);
                        }).collect(Collectors.toList());
        <span class="hljs-keyword">return</span> fetchedStudentList;
    }

    private <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> sleep(int element) {
        <span class="hljs-keyword">try</span> {
            Thread.sleep(<span class="hljs-number">1000</span>);
        } <span class="hljs-keyword">catch</span> (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
</code></pre><p>We are fetching the hard coded values using IntStream.rangeClosed(1, 20).</p>
<p>In order to simulate the slow IO while fetching the data, I have on purpose used Thread.sleep(1000). After every record fetched, there is a delay of 1 second.</p>
<p>Here, with getStudentsList(), we have a blocking call. Thread will need to keep on waiting until all the data elements are fetched, and the List is prepared. Only after the complete List is prepared, the response is returned. </p>
<p>So, for our blocking call, we will see that consumer has to wait for 20 seconds before it gets the List of Student.</p>
<p>With non blocking call, we will see that the consumer doesn't need to wait for the complete list to arrive. Consumer will be getting data as every element gets processed, and is emitted by the Flux.</p>
<pre><code>@Service
public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">StudentService</span> </span>{

    private <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> sleep(int element) {
        <span class="hljs-keyword">try</span> {
            Thread.sleep(<span class="hljs-number">1000</span>);
        } <span class="hljs-keyword">catch</span> (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public Flux&lt;Student&gt; getStudentsFlux() {
        Flux&lt;Student&gt; fetchedStudentFlux = Flux.range(<span class="hljs-number">1</span>, <span class="hljs-number">20</span>)
                .delayElements(Duration.ofSeconds(<span class="hljs-number">1</span>))
                .doOnNext(element -&gt; System.out.println(<span class="hljs-string">"Fetched student with id: "</span> + element))
                .map(element -&gt; {
                    int rollNumber = element;
                    <span class="hljs-built_in">String</span> name = <span class="hljs-string">"Student "</span> + rollNumber;
                    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Student(rollNumber, name);
                });
        <span class="hljs-keyword">return</span> fetchedStudentFlux;
    }
}
</code></pre><p>In getStudentsFlux() method we are preparing the Flux of students. We have added a delay of 1 second as well here to simulate delay in fetching records as part of IO.</p>
<p>One important thing to note is that List is a blocking data type. We cannot use List or any existing data type for that matter for making asynchronous calls. That is why project reactor had to introduce Mono and Flux types so that we can make asynchronous calls.</p>
<p>In getStudentsFlux() if we use List, then it will become a blocking call.</p>
<p>Now when we try to fetch data on endpoint /v1/api/async/students, we will see that we are getting data one by one. The consumer will not wait for all the data to arrive at once.</p>
<h2 id="heading-ending-notes">🎯 Ending Notes</h2>
<p>I hope this post helped you understand the basics of Reactive Programming in Spring applications. I have made all the code changes used in this article available at my GitHub repository <a target="_blank" href="https://github.com/anshulgammy/utopian-nerd/tree/main/usecases/spring-reactive/spring-reactive-crud-rest-apis">here</a>. </p>
<p>The repository also has CRUD operations performed in Reactive way, using ReactiveMongoRepository, with functional endpoints.</p>
<p>Do check out this repository.</p>
]]></content:encoded></item><item><title><![CDATA[Reactive Programming using RxJava]]></title><description><![CDATA[Learn basics of Reactive Programming using RxJava with simpler examples]]></description><link>https://tech.anshulgautam.in/reactive-programming-using-rxjava</link><guid isPermaLink="true">https://tech.anshulgautam.in/reactive-programming-using-rxjava</guid><category><![CDATA[rxjava]]></category><category><![CDATA[Reactive Programming]]></category><category><![CDATA[Java]]></category><dc:creator><![CDATA[Anshul Gautam]]></dc:creator><pubDate>Fri, 25 Mar 2022 12:46:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649832364778/aKiA_cSO_.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-what-is-rxjava">🎯 What is RxJava?</h2>
<p>The official documentation defines it as:</p>
<blockquote>
<p>It is a Java VM implementation of Reactive Extensions. Reactive Extensions is a library for composing asynchronous and event-based programs by using observable sequences.</p>
</blockquote>
<p>In simpler terms, RxJava incorporates <strong>Reactive Programming</strong> paradigm in <strong>Java</strong>, and helps you consume data in motion, <strong>asynchronously</strong>.</p>
<p>You don't need to scan through the data in motion(<strong>pull based blocking calls</strong>), in fact the each data element in the motion will come to you(<strong>push based non-blocking calls</strong>). Now as the data keeps coming to you, you can work with it the way you want.</p>
<h2 id="heading-but-why-do-we-need-reactive-programming-in-java">🎯 But why do we need Reactive Programming in Java?</h2>
<p>Let's consider an example of an ECommerce website where user purchases some items from the website, and after the payment receives a notification in form of email and sms. Here, we have two services present:</p>
<ul>
<li>Payment Service</li>
<li>Notification Service</li>
</ul>
<p>Without reactive programming, we would be coding for this requirement something like below:</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PaymentService</span> </span>{
    /
    .
    .
    .
    /

    public <span class="hljs-keyword">void</span> success(User user) {
        notificationService.sendEmail(user);
        notificationService.sendSms(user);
    }
}
</code></pre><p>In this approach, you can see that PaymentService is behaving pro-actively, and NotificationService is sort of behaving irresponsible. Why is that so?</p>
<p>This is so because PaymentService is doing more than what it should do.
It is processing the payment, and also triggering the notification. NotificationService is waiting for PaymentService to trigger it. It is not doing anything on its own.
Isn't it violation of Single Responsibility Principle?</p>
<p>With Reactive Programming, we make both of the service responsible, reactive to events, and make them work for what they are intended to. They do their job, and then raise an event marking success or failure at their end. Based on the event raised, other services would start their work.</p>
<p>The implementation with Reactive Programming will look something like below.</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PaymentService</span> </span>{
    /
    .
    .
    .
    /

    public <span class="hljs-keyword">void</span> success(User user) {
        Message message = <span class="hljs-keyword">new</span> Message(<span class="hljs-string">"Payment Done"</span>, user);

        broadcastService.broadcast(message);
    }
}

public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NotificationService</span> </span>{
    /
    .
    .
    .
    /

    public <span class="hljs-keyword">void</span> listen(Message message) {
        sendEmail(message.getUser());
        sendSms(message.getUser());
    }
}
</code></pre><p>I think the above code snippets give you an idea on how Reactive Programming helps us. This is not the complete code, but at least it gives you sense of Reactive Programming.</p>
<p>So, in simpler terms, we can say that Reactive Programming is programming with asynchronous data streams.</p>
<p>But wait, Java has in built support for Future and CompletableFuture. Right?</p>
<p>Reactive Programming is by default asynchronous. It gives you DSL to make your life easier, allowing you to write too little code to make your logic work asynchronously. The amount of code that you will write with vanilla Java Future, and the complexity involved in it, these all get over simplified when you use Reactive Programming with RxJava.</p>
<p>RxJava is by default single threaded. It has a component called Scheduler, which helps in scheduling of work to different threads.</p>
<h2 id="heading-components-in-rxjava">🎯 Components in RxJava</h2>
<p>In RxJava, few important concepts involved here are: <strong>Observable</strong>, <strong>Observer</strong>, <strong>Scheduler </strong>and <strong>Operator</strong>.</p>
<p><strong>Observable </strong>-&gt; (<strong>pushes data</strong>) -&gt; <strong>Observer</strong></p>
<ul>
<li><p><strong>Observable </strong>is the entity which pushes/emits the data stream towards the Observer.</p>
</li>
<li><p><strong>Observer</strong> keeps listening to the Observable. It is the entity which will consume the data elements, and work with them or take any action.</p>
</li>
<li><p><strong>Operator</strong> is the entity which can transform, merge, split or process the data pushed by the Observable before it reaches Observer. It provides an elegant declarative solution to complex asynchronous tasks. You can chain different operators together.</p>
</li>
<li><p><strong>Scheduler </strong> manage threads. It is the component in Rx that tells observable and observers on which thread they should run.</p>
</li>
</ul>
<p>Like I mentioned before, RxJava is by default works on single threaded model. This doesn't mean that every task in your application is going to run on a single thread only. </p>
<p>For example consider that in an application there is a heavy resource intensive task, and for that a heavy thread is needed, call it <em>Thread-Elephant</em>. Along with this, there are several light weight tasks, which can safely run on a lighter thread, call it <em>Thread-Feather</em>. </p>
<p>Scheduler is the component in RxJava which can switch between threads, and schedule the heavy task to be computed on the <em>Thread-Elephant</em>, and can switch to <em>Thread-Feather</em> for other light weight tasks in the application. By doing this, the main thread never gets blocked.</p>
<h2 id="heading-integrating-rxjava-in-java-applications">🎯 Integrating RxJava in Java Applications</h2>
<p>Maven and Gradle projects can make use of dependency which enables the RxJava support for your Java applications.</p>
<p>Below dependency needs to be added in your maven project.</p>
<pre><code>&lt;dependency&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>io.reactivex.rxjava2<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>rxjava<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>2.2.21<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span></span>
&lt;/dependency&gt;
</code></pre><p>While working with RxJava, it is advisable to have knowledge on Java Lambdas and Method Reference concepts. It makes life easier.</p>
<h2 id="heading-lets-play-with-rxjava">🎯 Let's play with RxJava</h2>
<p>Let's create a very simple Observable.</p>
<pre><code><span class="hljs-comment">/**
 * Creating Observable from '*just*', and subscribing to it.
 */</span>
private <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> observableFromJust() {
    Observable.just(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>)
            .subscribe(HelloRxJava::print);
}
</code></pre><p>The Observable is created here using '<em>just</em>', and it emits integers. Our Observer subscribes to it, and prints integers emitted by the Observable.</p>
<p>The most frequently way to create Observable is by using '<em>create</em>'.</p>
<pre><code><span class="hljs-comment">/**
 * Creating Observable from ObservableOnSubscribe&lt;T&gt; using create, and subscribing to it.
 */</span>
private <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> observableFromCreate() {
    Observable&lt;Integer&gt; observable = Observable.create(observableEmitter -&gt; {
        observableEmitter.onNext(<span class="hljs-number">1</span>);
        observableEmitter.onNext(<span class="hljs-number">2</span>);
        observableEmitter.onNext(<span class="hljs-number">3</span>);
        observableEmitter.onNext(<span class="hljs-number">4</span>);
        observableEmitter.onNext(<span class="hljs-number">5</span>);
    });
    observable.subscribe(System.out::println);
}
</code></pre><p>You can create Observables from Iterable, Callable and Future also, using self explanatory methods like <em>Observable.fromIterable()</em>, <em>Observable.fromCallable()</em> and <em>Observable.fromFuture()</em>.</p>
<p>Okay, now let's try to employ Operators on our Observable. </p>
<p>Like I mentioned, Operator will help you do transformation to your data elements in the stream of data being emitted. </p>
<p>I have used <em>filter()</em> to do the filter operation, and then <em>map()</em> to transform the elements.
One more thing you will notice in the below example is that I have used <em>Observable.range()</em> to create Observable to emit integers from 1 to 10; even more simpler way to create Observable.
Well, this creates Observable of Integers present in the range defined.</p>
<pre><code>Observable&lt;Integer&gt; observable = Observable.range(<span class="hljs-number">1</span>, <span class="hljs-number">10</span>);

observable
    <span class="hljs-comment">// filtering the element on the basis of odd and even. Only even numbers will be considered.</span>
    .filter(element -&gt; element % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>)
    <span class="hljs-comment">// multiplying the element with 10</span>
    .map(element -&gt; element * <span class="hljs-number">10</span>)
    .subscribe(System.out::println);
</code></pre><p>Let's work around Schedulers now. Like I mentioned, Scheduler in RxJava helps to switch between threads.</p>
<p>In the example code below, I am trying to find out which thread our subscriber is working on. This example shows that by default, all the operation is going on in the main thread.</p>
<pre><code>Observable&lt;Integer&gt; observable = Observable.range(<span class="hljs-number">1</span>, <span class="hljs-number">10</span>);

observable
    <span class="hljs-comment">// filtering the element on the basis of odd and even. Only even numbers will be considered.</span>
    .filter(element -&gt; element % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>)
    <span class="hljs-comment">// multiplying the element with 10</span>
    .map(element -&gt; element * <span class="hljs-number">10</span>)
    .subscribe(element -&gt; {
        System.out.println(Thread.currentThread().getName());
        print(element);
    });
</code></pre><p>Output:</p>
<pre><code>main
Printing number: <span class="hljs-number">20</span>
main
Printing number: <span class="hljs-number">40</span>
main
Printing number: <span class="hljs-number">60</span>
main
Printing number: <span class="hljs-number">80</span>
main
Printing number: <span class="hljs-number">100</span>
</code></pre><p>Let's try to switch to a different thread now using <em>observeOn()</em> and static methods from Schedulers class.</p>
<pre><code>Observable.range(<span class="hljs-number">1</span>, <span class="hljs-number">10</span>)
    .filter(element -&gt; element % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>)
    .map(element -&gt; element * <span class="hljs-number">10</span>)
    .observeOn(Schedulers.computation())
    .subscribe(element -&gt; {
        System.out.println(element);
        System.out.println(Thread.currentThread().getName());
    });
</code></pre><p>Output:</p>
<pre><code><span class="hljs-number">20</span>
RxComputationThreadPool<span class="hljs-number">-1</span>
<span class="hljs-number">40</span>
RxComputationThreadPool<span class="hljs-number">-1</span>
<span class="hljs-number">60</span>
RxComputationThreadPool<span class="hljs-number">-1</span>
<span class="hljs-number">80</span>
RxComputationThreadPool<span class="hljs-number">-1</span>
<span class="hljs-number">100</span>
RxComputationThreadPool<span class="hljs-number">-1</span>

Process finished <span class="hljs-keyword">with</span> exit code <span class="hljs-number">0</span>
</code></pre><p>We also have <em>subscribeOn()</em> operator available as well which helps to switch to a different thread. </p>
<p>The difference between <em>observeOn()</em> and <em>subscribeOn()</em> is that the former makes sure that chained operators till the point where you have used <em>observeOn()</em> will work on the separate thread. With <em>subscribeOn()</em>, the entire observable works on a separate thread.</p>
<p>This is really helpful when we have lots of operators chained and we want to segregate the work load on different threads.</p>
<p>One important thing to note. In Java, if you try running the code like above which executes on a separate thread, you might not see the expected output. The reason is, the Java main thread just exists. You will need to provide something to stop the main thread from exiting. I used a very simple <em>Thread.sleep()</em> to check the output.</p>
<pre><code>Observable.range(<span class="hljs-number">1</span>, <span class="hljs-number">10</span>)
    .filter(element -&gt; element % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>)
    .map(element -&gt; element * <span class="hljs-number">10</span>)
    .observeOn(Schedulers.computation())
    .subscribe(element -&gt; {
        System.out.println(element);
        System.out.println(Thread.currentThread().getName());
    });

<span class="hljs-keyword">try</span> {
    Thread.sleep(<span class="hljs-number">2000</span>);
} <span class="hljs-keyword">catch</span> (InterruptedException e) {
    e.printStackTrace();
}
</code></pre><h2 id="heading-error-handling-in-rxjava">🎯 Error Handling in RxJava</h2>
<p>You can handle error at the observer/subscribe level, or at the operator level. </p>
<p>In the below example I have shown handling error when I am doing the subscribe. You can see below that there is one null getting emitted by the Observable.</p>
<p>Observable doesn't allow to emit null, since RxJava 2.x. I have added that on purpose so that Exception gets raised.</p>
<pre><code>Observable&lt;Integer&gt; observable = Observable.create(emitter -&gt; {
    emitter.onNext(<span class="hljs-number">1</span>);
    emitter.onNext(<span class="hljs-number">2</span>);
    emitter.onNext(<span class="hljs-number">3</span>);
    emitter.onNext(<span class="hljs-number">4</span>);
    emitter.onNext(<span class="hljs-number">5</span>);
    emitter.onNext(<span class="hljs-literal">null</span>);
});

observable
    .filter(element -&gt; element % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>)
    .map(element -&gt; element * <span class="hljs-number">10</span>)
    <span class="hljs-comment">// the second argument is for Consumer&lt;? super Throwable&gt; onError</span>
    .subscribe(System.out::println, (error) -&gt; {
        System.out.println(<span class="hljs-string">"Error happened: "</span> + error.getMessage());
    });
</code></pre><p>Output:</p>
<pre><code><span class="hljs-number">20</span>
<span class="hljs-number">40</span>
<span class="hljs-built_in">Error</span> happened: onNext called <span class="hljs-keyword">with</span> <span class="hljs-literal">null</span>. Null values are generally not allowed <span class="hljs-keyword">in</span> <span class="hljs-number">2.</span>x operators and sources.

Process finished <span class="hljs-keyword">with</span> exit code <span class="hljs-number">0</span>
</code></pre><p>Handling error at the operator level on Observable is shown in the code below.</p>
<pre><code>Observable&lt;Integer&gt; observable = Observable.create(emitter -&gt; {
    emitter.onNext(<span class="hljs-number">1</span>);
    emitter.onNext(<span class="hljs-number">2</span>);
    emitter.onNext(<span class="hljs-number">3</span>);
    emitter.onNext(<span class="hljs-number">4</span>);
    emitter.onNext(<span class="hljs-number">5</span>);
    emitter.onNext(<span class="hljs-literal">null</span>);
});

observable
    .filter(element -&gt; element % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>)
    .map(element -&gt; element * <span class="hljs-number">10</span>)
    <span class="hljs-comment">// if there is an error, then -1 will be returned</span>
    .onErrorReturnItem(<span class="hljs-number">-1</span>)
    .subscribe(System.out::println);
</code></pre><p>Output:</p>
<pre><code><span class="hljs-number">20</span>
<span class="hljs-number">40</span>
<span class="hljs-number">-1</span>

Process finished <span class="hljs-keyword">with</span> exit code <span class="hljs-number">0</span>
</code></pre><p>There are several other error related options available to us which can help to handle errors, like <em>onErrorReturn</em>, <em>onErrorResumeNext</em>, <em>doOnError </em>etc.</p>
<p>We can also use retry in the chain of operators. The intent of using retry is to retry the operation in case some error occurs. We can configure how the retry should be performed. Below is one simple example to make use of retry.</p>
<pre><code>Observable&lt;Integer&gt; observable = Observable.create(emitter -&gt; {
    emitter.onNext(<span class="hljs-number">1</span>);
    emitter.onNext(<span class="hljs-number">2</span>);
    emitter.onNext(<span class="hljs-number">3</span>);
    emitter.onNext(<span class="hljs-number">4</span>);
    emitter.onNext(<span class="hljs-number">5</span>);
    emitter.onNext(<span class="hljs-literal">null</span>);
});

observable
    .filter(element -&gt; element % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>)
    .map(element -&gt; element * <span class="hljs-number">10</span>)
    <span class="hljs-comment">// configured the retry here</span>
    .retryWhen(element -&gt; {
        <span class="hljs-keyword">return</span> element.take(<span class="hljs-number">10</span>).delay(<span class="hljs-number">2</span>, TimeUnit.SECONDS);
    })
    .subscribe(System.out::println);
</code></pre><p>Here retry will be attempted for every 2 seconds, 10 times.</p>
<p>Now that we have got a fair idea on RxJava components, and have got our hand dirty with the basic offerings, I believe we should go ahead and learn something about types of Observable also in this article.</p>
<h2 id="heading-types-of-observable">🎯 Types of Observable</h2>
<ul>
<li><p><strong>Hot Observable</strong>: These are the observable who do not wait for the observer to subscribe to them before they emit their data. Observers which subscribed late, they miss out the data previously emitted by this type of observable.</p>
</li>
<li><p><strong>Cold Observable</strong>: These are the observable which emit their data from start till end to all the observers who have subscribed to them. It is analogous to a Movie DVD, which an observer can play from start till end any time they want.</p>
</li>
<li><p><strong>Connectable Observable</strong>: These are the Cold Observable which are converted into Hot Observable. Suppose you have decided to host a movie party using a movie DVD to your friends at 9 PM. Those friends who join you late after 9 PM, they will miss out some part of the movie.</p>
</li>
</ul>
<p>Observable that we created so far in examples above, they are all Cold Observable.</p>
<p>Let's see an example of how we can create a Hot Observable.</p>
<pre><code>ConnectableObservable&lt;Integer&gt; observable = 
    Observable.range(<span class="hljs-number">1</span>, <span class="hljs-number">3</span>).publish();

observable.subscribe(element -&gt; {
    System.out.println(<span class="hljs-string">"Observer 1 printing: "</span> + element);
});
observable.subscribe(element -&gt; {
    System.out.println(<span class="hljs-string">"Observer 2 printing: "</span> + element);
});
observable.connect();
</code></pre><p>Output:</p>
<pre><code>Observer <span class="hljs-number">1</span> printing: <span class="hljs-number">1</span>
Observer <span class="hljs-number">2</span> printing: <span class="hljs-number">1</span>
Observer <span class="hljs-number">1</span> printing: <span class="hljs-number">2</span>
Observer <span class="hljs-number">2</span> printing: <span class="hljs-number">2</span>
Observer <span class="hljs-number">1</span> printing: <span class="hljs-number">3</span>
Observer <span class="hljs-number">2</span> printing: <span class="hljs-number">3</span>

Process finished <span class="hljs-keyword">with</span> exit code <span class="hljs-number">0</span>
</code></pre><p>Both the observers are reading the emitted data, and in the same order.</p>
<p>Also notice that I have used <em>.publish()</em> on the observable. As soon as we do <em>.publish()</em> on the observable, it returns <em>ConnectableObservable</em>. </p>
<p><em>ConnectableObservable</em> is a hot observable.</p>
<p>I hope you can relate to the explanation that I had given above. This was a cold observable only, but we did <em>.publish()</em> on it and converted it to a hot observable.</p>
<p>The hot observable starts emitting data once we do <em>.connect()</em> on them.</p>
<p>Let's try changing the order of the observer listening to the observable, and see how it behaves.</p>
<pre><code>ConnectableObservable&lt;Integer&gt; observable = 
    Observable.range(<span class="hljs-number">1</span>, <span class="hljs-number">3</span>).publish();

observable.subscribe(element -&gt; {
    System.out.println(<span class="hljs-string">"Observer 1 printing: "</span> + element);
});

observable.connect();

observable.subscribe(element -&gt; {
    System.out.println(<span class="hljs-string">"Observer 2 printing: "</span> + element);
});
</code></pre><p>Output:</p>
<pre><code>Observer <span class="hljs-number">1</span> printing: <span class="hljs-number">1</span>
Observer <span class="hljs-number">1</span> printing: <span class="hljs-number">2</span>
Observer <span class="hljs-number">1</span> printing: <span class="hljs-number">3</span>

Process finished <span class="hljs-keyword">with</span> exit code <span class="hljs-number">0</span>
</code></pre><p>The observer 2 is not able to get any data because before it could subscribe to the observable, all the data was emitted. Only observer 1 was subscribed beforehand, and that it is why it received all the emitted data.</p>
<h2 id="heading-ending-notes">🎯 Ending Notes</h2>
<p>I hope this post gives you an overview to the basics of Reactive Programming and RxJava.</p>
<p>The source code for all the snippets used in this post are present at my <a target="_blank" href="https://github.com/anshulgammy/utopian-nerd/tree/main/usecases/rxjava-basics">GitHub</a> repository. Please check this out. There are few more scenarios covered in RxJava in this repository that you can also play around with.</p>
]]></content:encoded></item><item><title><![CDATA[Spring Boot Refresher]]></title><description><![CDATA[Refresh yourself with basic concepts from Spring Boot]]></description><link>https://tech.anshulgautam.in/spring-boot-refresher</link><guid isPermaLink="true">https://tech.anshulgautam.in/spring-boot-refresher</guid><category><![CDATA[Springboot]]></category><category><![CDATA[Java]]></category><dc:creator><![CDATA[Anshul Gautam]]></dc:creator><pubDate>Tue, 08 Mar 2022 09:05:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649831521167/7DksJm523.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This article helps to get an overview of Spring Boot. This will also be helpful to refresh your basic concepts on this topic quickly.</p>
<h2 id="heading-what-is-spring-boot">🎯 What is Spring Boot?</h2>
<p>Spring Boot is comprised of two separate words; '<strong>Spring</strong>' and '<strong>Boot</strong>'.</p>
<p>'<strong>Spring</strong>' is the Spring Framework. This is the Java Application Framework which helps you write Java Enterprise Applications.</p>
<p>'<strong>Boot</strong>' is Bootstrap.
Spring Boot helps you Bootstrap a Spring Application.</p>
<p>Well, the official definition goes something like this:
<em>Spring Boot makes it easy to create stand-alone, production-grade Spring based applications that you can "just run".</em></p>
<p>In a typical Spring Framework, there are lots of configuration needed to be done. With Spring Boot, this is no longer the case. You can run the Spring Application with very less, or no configuration at all, and can easily run as a standalone application. </p>
<h2 id="heading-spring-vs-spring-boot">🎯 Spring vs Spring Boot</h2>
<p>Spring started of as a tool to provide dependency injection functionality. But today, Spring has grown into a lot more. It is a huge Application Framework now, which uses programming and configuration model. This has invites few problems with Spring Framework, like it involves multiple setup/configuration steps. It may lead to multiple build and deploy steps.</p>
<p>Spring Boot tries to cater to the functionalities provided by the Spring Framework, with very easy and minimum abstracted configuration steps. It does the most common configuration for you out of the box. In case your application needs some extra configuration, you can do that as well. 
In short, Spring Boot is:</p>
<ul>
<li>Opinionated</li>
<li>Convention over Configuration</li>
<li>Stand-alone</li>
<li>Production ready</li>
</ul>
<h2 id="heading-creating-spring-boot-application-with-maven">🎯 Creating Spring Boot Application with Maven</h2>
<p>You must be aware that Maven is build and dependency management tool. For creating Spring Boot Application via Maven, you need to add a parent project in the pom.xml:</p>
<pre><code>&lt;parent&gt;
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span></span>
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-parent<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span></span>
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>${latest.version}<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span></span>
 &lt;/parent&gt;
</code></pre><p>Here <code>${latest.version}</code> corresponds to the latest version of this parent project being offered by the Spring.</p>
<p>This parent project provides opinionated configuration for your child project. This ensures that the bare minimum configuration needed for your Spring Boot project is already provided to you and you don't need to work much on that part. This is analogous to child inheriting the property defined in the parent.
You will be focusing on writing business code mostly.</p>
<h2 id="heading-creating-spring-boot-application-with-spring-initializr">🎯 Creating Spring Boot Application with Spring Initializr</h2>
<p>Easiest way to create Spring Boot application from scratch is by going to <a target="_blank" href="https://start.spring.io/">Spring Initializr</a>. This portal will help you choose what all dependencies and their versions you would want in your project, and will create a scratch project for you. You can download the project zip file and start adding on your code.</p>
<h2 id="heading-starting-class-for-your-spring-boot-application">🎯 Starting Class for your Spring Boot Application</h2>
<pre><code>@SpringBootApplication
public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FirstSpringBootApplication</span> </span>{

    public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main(<span class="hljs-built_in">String</span> args[]) {
        SpringApplication.run(FirstSpringBootApplication.class, args);
    }
}
</code></pre><p>The <code>@SpringBootApplication</code> annotated on the class acts as the starting point in you application.
This does a lot of thing in the background for us:</p>
<ul>
<li>Sets up default configuration</li>
<li>Starts Spring application context</li>
<li>Performs class path scan
This will also start Tomcat server in case you have added Spring Web. Spring Web provides embedded Tomcat server out of the box.</li>
</ul>
<h2 id="heading-why-embedded-tomcat-server-in-spring-boot-application">🎯 Why Embedded Tomcat Server in Spring Boot Application</h2>
<p>Having an embedded Tomcat server in your project is helpful in few ways:</p>
<ul>
<li>Convenience</li>
<li>Servlet container config becomes part of application config</li>
<li>Stand-alone application</li>
<li>Useful for microservices architecture
Can we change embedded Tomcat server to a some different servlet container? Yes we can.</li>
</ul>
<h2 id="heading-customizing-spring-boot">🎯 Customizing Spring Boot</h2>
<p>You can configure using a properties file. 
You keep <code>application.properties</code> or <code>application.yml</code> file in your resources folder.
You can do the configuration by providing key value pairs in the properties file.
Eg:</p>
<pre><code>server.port=<span class="hljs-number">8765</span>
</code></pre><p>The above key value pair in our property file overrides the server port from 8080 to 8765.</p>
<p>Properties file is one of the easiest way to configure your application, and override the defaults that Sprint Boot provides to you out of the box.</p>
]]></content:encoded></item></channel></rss>