<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Arpan Banerjee on Medium]]></title>
        <description><![CDATA[Stories by Arpan Banerjee on Medium]]></description>
        <link>https://medium.com/@arpan-banerjee7?source=rss-adeb5e42707------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*M-EBoaVEbhh17OKHbIKZEQ.jpeg</url>
            <title>Stories by Arpan Banerjee on Medium</title>
            <link>https://medium.com/@arpan-banerjee7?source=rss-adeb5e42707------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 00:11:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arpan-banerjee7/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Monitor a SpringBoot application in New Relic using Micrometer]]></title>
            <link>https://medium.com/codex/monitor-a-springboot-application-in-new-relic-using-micrometer-64d135e5afca?source=rss-adeb5e42707------2</link>
            <guid isPermaLink="false">https://medium.com/p/64d135e5afca</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[new-relic]]></category>
            <dc:creator><![CDATA[Arpan Banerjee]]></dc:creator>
            <pubDate>Thu, 23 Mar 2023 17:26:47 GMT</pubDate>
            <atom:updated>2023-03-23T17:26:47.953Z</atom:updated>
            <content:encoded><![CDATA[<p>Set up your spring boot application to publish metrics using Micrometer and monitor them in New Relic</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uw3IaV-wHnYkMUrLBVTfpg.jpeg" /></figure><h4>Why Micrometer?</h4><p><a href="https://micrometer.io/docs">Micrometer</a> is a <em>dimensional-first</em> metrics collection facade whose aim is to allow you to time, count, and gauge your code with a <strong>vendor neutral API</strong>. Through classpath and configuration, you may select one or several monitoring systems to export your metrics data to.</p><p><strong>Think of it like SLF4J, but for metrics!</strong></p><p>SLF4J acts as a <a href="https://en.wikipedia.org/wiki/Facade_pattern">facade</a> for different logging frameworks (e.g., <a href="https://www.baeldung.com/java-logging-intro">java.util.logging, logback, Log4j</a>). It offers an abstract logging API , making the logging independent of the actual implementation. This allows for different logging frameworks to coexist. And it helps migrate from one framework to another. Similarly, you can imagine Micrometer to acts as an interface, which bridges the gap between different metric collection frameworks like Prometheus, New Relic, Atlas, Datadog etc. Using micrometer you can swicth your monitoring systems anytime keeping your application code setup in similar fashion.</p><p>In Micrometer, you collect metrics about your application using an interface called a Meter. Meters, according to their <a href="https://micrometer.io/docs/concepts#_registry">documentation</a>, are “created from and held in a MeterRegistry.” You can then register one or more MeterRegistry implementations to send metrics to a monitoring system, such as New Relic, Prometheus, Dynatrace, Atlas, Datadog etc. This approach decouples your metric instrumentation from the metrics backend you use, and it lets you register multiple MeterRegistry implementations to send the same metrics to multiple backends.</p><p>Let’s jump into the coding now!</p><p><strong>From what I have learned so far. There are 3 ways to integrate New Relic with a Spring Boot Application-</strong></p><ol><li>Using the Java Agent provided by New Relic</li><li><a href="https://newrelic.com/blog/how-to-relic/how-to-monitor-spring-boot-applications-using-micrometer-metrics">Using New Relic’s Micrometer Dependency</a></li><li><a href="https://micrometer.io/docs/registry/new-relic">Micormeter’s New Relic Dependency</a></li></ol><blockquote>Micormeter’s New Relic Dependency sents metrics to New Relic as events, which is outdated now as New Relic provides its own Micrometer MeterRegistry implementation based on dimensional metrics. It provides much superior integration capabilities and is the ideal choice to go for.</blockquote><p>For more details on this please visit the below mentioned pages.<br><a href="https://micrometer.io/docs/registry/new-relic"><em>https://micrometer.io/docs/registry/new-relic</em></a><em><br></em><a href="https://newrelic.com/blog/how-to-relic/how-to-monitor-spring-boot-applications-using-micrometer-metrics"><em>https://newrelic.com/blog/how-to-relic/how-to-monitor-spring-boot-applications-using-micrometer-metrics</em></a></p><h3>Using the Java Agent provided by New Relic</h3><ol><li>Download the Java Agent from this URL- <a href="https://docs.newrelic.com/docs/release-notes/agent-release-notes/java-release-notes/">https://docs.newrelic.com/docs/release-notes/agent-release-notes/java-release-notes/</a></li><li>Extract it.</li><li>Modify the newrelic.yml file inside the extracted folder to inlcude your <br>License_key:<br>App_name:</li><li>Create a SpringBoot application with some REST endpoints.</li><li>Build the application.</li><li>. Navigate to the root path where you have extracted the newrelic java agent.</li><li>Enter this command<br>`<em>java -javagent:&lt;path to your new relic jar&gt;\newrelic.jar -jar &lt;path to your application jar&gt;\&lt;you rapplication jar name&gt;.jar</em>`</li></ol><h4>To view the application metrics-</h4><ol><li>Log in to your New Relic account.</li><li>Go to Explorer Tab.</li><li>Click on Services-APM</li><li>You can see the name of your application(which you had mentioned in the newrelic.yml file) listed there.</li><li>Click on the application name.</li><li>The dashboard should look something like this.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*53_VeA5ylEGyPCrlTHcOkA.png" /></figure><h3>Using New Relic’s Micrometer Dependency</h3><p>This is the preferred way.</p><ol><li>Create a Spring Boot project</li><li>Add these two dependencies</li></ol><pre>    &lt;dependency&gt;<br>        &lt;groupId&gt;com.newrelic.telemetry&lt;/groupId&gt;<br>        &lt;artifactId&gt;micrometer-registry-new-relic&lt;/artifactId&gt;<br>        &lt;version&gt;0.7.0&lt;/version&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;dependency&gt;<br>       &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>       &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br><br></pre><p>3. Add this class to your project.</p><h4>MicrometerConfig Class</h4><pre>import java.net.InetAddress;<br>import java.net.UnknownHostException;<br><br>import org.springframework.boot.actuate.autoconfigure.metrics.CompositeMeterRegistryAutoConfiguration;<br>import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration;<br>import org.springframework.boot.actuate.autoconfigure.metrics.export.simple.SimpleMetricsExportAutoConfiguration;<br>import org.springframework.boot.autoconfigure.AutoConfigureAfter;<br>import org.springframework.boot.autoconfigure.AutoConfigureBefore;<br>import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br><br>import com.newrelic.telemetry.Attributes;<br>import com.newrelic.telemetry.micrometer.NewRelicRegistry;<br>import com.newrelic.telemetry.micrometer.NewRelicRegistryConfig;<br><br>import java.time.Duration;<br>import io.micrometer.core.instrument.config.MeterFilter;<br>import io.micrometer.core.instrument.util.NamedThreadFactory;<br><br>@Configuration<br>@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class })<br>@AutoConfigureAfter(MetricsAutoConfiguration.class)<br>@ConditionalOnClass(NewRelicRegistry.class)<br>public class MicrometerConfig {<br><br> @Bean<br> public NewRelicRegistryConfig newRelicConfig() {<br>  return new NewRelicRegistryConfig() {<br>   @Override<br>   public String get(String key) {<br>    return null;<br>   }<br><br>   @Override<br>   public String apiKey() {<br>    return &quot;your_api_key&quot;; // for production purposes take it from config file<br>   }<br><br>   @Override<br>   public Duration step() {<br>    return Duration.ofSeconds(5);<br>   }<br><br>   @Override<br>   public String serviceName() {<br>    return &quot;your_service_name&quot;; // for production purposes take it from config file<br>   }<br><br>  };<br> }<br><br> @Bean<br> public NewRelicRegistry newRelicMeterRegistry(NewRelicRegistryConfig config) throws UnknownHostException {<br>  NewRelicRegistry newRelicRegistry = NewRelicRegistry.builder(config)<br>    .commonAttributes(new Attributes().put(&quot;host&quot;, InetAddress.getLocalHost().getHostName())).build();<br>  newRelicRegistry.config().meterFilter(MeterFilter.ignoreTags(&quot;plz_ignore_me&quot;));<br>  newRelicRegistry.config().meterFilter(MeterFilter.denyNameStartsWith(&quot;jvm.threads&quot;));<br>  newRelicRegistry.start(new NamedThreadFactory(&quot;newrelic.micrometer.registry&quot;));<br>  return newRelicRegistry;<br> }<br>}</pre><p>4. Run the application.</p><blockquote>As I want to record how long a method takes to execute, I will be using the Micrometer Timer metric type. A timer records the duration of an activity, and its frequency. So I will be able to see how long my method takes to execute, and how often it’s called. This is why I have used @Timed annotation in my rest endpoints. Micrometer will now calculate the execution time of the method and expose them to New Relic.</blockquote><h4>Controller Class</h4><pre>package springboot.micrometer.demo.controller;<br><br>import java.util.Random;<br><br>import org.springframework.http.HttpStatus;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>import io.micrometer.core.annotation.Timed;<br><br>@RestController<br>@RequestMapping(&quot;/rest&quot;)<br>public class HelloController {<br> Random random = new Random();<br><br> @Timed(value = &quot;greeting1&quot;, histogram = true, percentiles = { 0.95, 0.99 }, extraTags = { &quot;version&quot;, &quot;1.0&quot; })<br> @GetMapping(&quot;/hello&quot;)<br> public String hello() throws InterruptedException {<br>  int number = random.nextInt(700 - 50) + 50;<br>  Thread.sleep(number);<br>  return &quot;Hello Arpan1&quot;;<br> }<br><br> @Timed(value = &quot;greeting2&quot;, histogram = true, percentiles = { 0.95, 0.99 }, extraTags = { &quot;version&quot;, &quot;1.0&quot; })<br> @GetMapping(&quot;/hello2&quot;)<br> public String hello2() {<br>  return &quot;Hello Arpan2&quot;;<br> }<br><br> @Timed(value = &quot;greeting3&quot;, histogram = true, percentiles = { 0.95, 0.99 }, extraTags = { &quot;version&quot;, &quot;1.0&quot; })<br> @GetMapping(&quot;/hello3&quot;)<br> public String hello3() {<br>  return &quot;Hello Arpan3&quot;;<br> }<br><br> @GetMapping(&quot;/hello4&quot;)<br> public String hello4() {<br>  return &quot;Hello Arpan4&quot;;<br> }<br><br> @Timed(value = &quot;greeting5&quot;, histogram = true, percentiles = { 0.95, 0.99 }, extraTags = { &quot;version&quot;, &quot;1.0&quot; })<br> @GetMapping(&quot;/hello5&quot;)<br> public ResponseEntity&lt;?&gt; hello5() {<br>  int number = random.nextInt(8 - 1) + 1;<br>  if (number == 3) {<br>   return new ResponseEntity&lt;&gt;(HttpStatus.SERVICE_UNAVAILABLE);<br>  }<br>  return new ResponseEntity&lt;&gt;(HttpStatus.OK);<br> }<br><br>}</pre><p>The <em>/hello5 </em>endpoint is designe to throw errors on random hits, so that we can view the error metrics in New Relic and set up custom alerts on it.</p><h4>To view the Application metrics-</h4><ol><li>Log in to your New Relic account.</li><li>Go to APM &amp; services.</li><li>You can see the name of your application(which you had mentioned in the MicrometerConfig file) listed there.</li><li>Click on the application name.</li><li>The dashboard should look something like this.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ffUuHbkFi0hHtM0vaWpGMA.png" /><figcaption>Dashboard</figcaption></figure><p>This is a very basic dashboard that you get out of the box. Now you can write custom queries and built a rich dashboard of your own.</p><p><strong>Before going away, I will show you how to see the API failures/errors.</strong></p><p>For this-</p><p>1. Click on Data, the Metrics Explorer</p><p>2. Type in the name of the Rest endpoint which you gave in the value attribute of the <em>@Timed </em>annotation <strong>@Timed(value = “greeting5”)</strong></p><p>3. Select the count metric.</p><p>4. Go to dimensions and select status. Here you can see the details of your api failures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fa1C08XYLYHs9Ry2z1_Now.png" /></figure><h3>Setting up Alert conditions</h3><p>Finally you can set up alert conditions on certain metric thresholds.</p><p>For example we can set alert conditions which will inform us if a certain API fails once within 2 minutes. <em>Our </em><em>/hello5 endpoint wil fail intermittenly so I had set up an alert on this.</em></p><p>This is how the alert dashboard looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yeO0aff3HuiIBNTSNzMenQ.png" /><figcaption>Alert Dashbaord</figcaption></figure><p>I had set up email notifications for alerts. This is how an alert mail from New Relic looks like. You can choose to get notified via slack, jira, service now incidents, mobile push etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RyqDFlvkv_dj0IhM6TPp-Q.png" /><figcaption>Alert Email Notification</figcaption></figure><blockquote>The demo spring boot application can be found here in my <a href="https://github.com/arpan-banerjee7/springboot-micrometer-newrelic-demo">GitHub</a> repo.</blockquote><p>That’s all for this blog! Do follow me on <a href="https://arpan-banerjee7.medium.com/">Medium</a>, <a href="https://www.linkedin.com/in/banerjee-arpan7/">Linkedin</a>, and <a href="https://github.com/arpan-banerjee7">GitHub </a>for more blogs like this!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64d135e5afca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/monitor-a-springboot-application-in-new-relic-using-micrometer-64d135e5afca">Monitor a SpringBoot application in New Relic using Micrometer</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of Server-Sent Events and EventSource- Live Progress Indicator using React and…]]></title>
            <link>https://medium.com/codex/implementation-of-server-sent-events-and-eventsource-live-progress-indicator-using-react-and-723596f35225?source=rss-adeb5e42707------2</link>
            <guid isPermaLink="false">https://medium.com/p/723596f35225</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[server-sent-events]]></category>
            <dc:creator><![CDATA[Arpan Banerjee]]></dc:creator>
            <pubDate>Mon, 26 Jul 2021 01:16:26 GMT</pubDate>
            <atom:updated>2021-08-11T10:48:29.538Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementation of Server-Sent Events and EventSource- Live Progress Indicator using React and Spring Boot</h3><h4>Understand how SSE works with a real-life use case- Loading Percentage Indicator on File Upload made using Spring Boot and React.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OW43FHM49m8wOCVw" /><figcaption>Photo by <a href="https://unsplash.com/@neonbrand?utm_source=medium&amp;utm_medium=referral">NeONBRAND</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you have this question in your mind- <strong><em>What’s Server-Sent Events?</em></strong><em> </em>Then I would highly recommend you to go through this article-<a href="https://medium.com/codex/getting-started-with-server-sent-events-and-understanding-when-to-use-polling-websockets-and-sse-87465f3bcf63"> <strong>Getting started with Server-Sent Events</strong></a><strong>.</strong></p><blockquote><a href="https://github.com/arpan-banerjee7/sse-progressbar">GitHub link to the demo that I am going to explain here.</a></blockquote><h4>Here’s brief info about SSE for those who are in a hurry!</h4><p><em>SSE is a lightweight protocol on top of HHTP Streaming that allows super light-weight subscribe-only capabilities to clients. Unlike WebSockets, SSE does not provide the capability of two-way communication but can be used by the server to push data to the clients in real-time. SSE enables a client to receive automatic updates from a server via an HTTP connection. It is designed to use the JavaScript EventSource API to subscribe to a stream of data in any popular browser.</em> <em>Through this interface, a client requests a particular URL to receive an event stream.</em></p><p><em>You might consider using Server-Sent Events when you have some rapidly updating data to display, but you do not want to poll the server. Examples might include displaying the status of a long-running business process, tracking stock price updates, or showing the current number of likes on a post on a social media network.</em></p><p>Now, that you know what’s SSE, I will explain to you the following things-</p><ul><li><strong>What was the Use Case?</strong></li><li><strong>Why did I choose to use SSE?</strong></li><li><strong>What are Events?</strong></li><li><strong>Implementation details.</strong></li></ul><h3>Use case</h3><p>The system processes the files extracts certain information and then saves it. Depending on the internet speed sometimes it might be a long wait for the user. So, to make the user experience as pleasant as possible, <strong>on file upload, display a real-time progress bar that shows how much the server has processed so far, without hitting endpoints repeatedly in the progress bar.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*0vS1rW0x0cKei76R2WzrVQ.png" /><figcaption>Server-Sent Events</figcaption></figure><h3>Why SSE?</h3><p>The requirement was to display a percentage indicating how much data was processed(parsed/read) in that file and then finally display 100% when the file was saved after the processing was done. So, I needed a way to continuously communicate to the client, sending it the percentage of the file that had been processed.</p><p>Server-Sent Event was a great solution for implementing this use case. I had to <em>display rapidly updating data without having to poll the server as it was about the progress for the same HTTP request.</em></p><p><strong>To understand how SSE works, you need to know what are events first.</strong></p><h3>What are Events?</h3><p>The server can send multiple events before closing the connection. Messages sent by the server should be text-based and the message starts with a keyword followed by a colon(:) and then a string message. ‘data’ is a keyword that represents a message for a client.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/159142cc0442436f03e72dec6b807ed1/href">https://medium.com/media/159142cc0442436f03e72dec6b807ed1/href</a></iframe><p>In the case of multiple messages, messages should be separated by a blank line otherwise client will treat them as a single event. The browser concatenates the above four lines and emits one event. To separate the message from each other, the server needs to send a blank line after each message. <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/SseEmitter.html">SseEmitter</a> used for emitting messages will take care of this next line and keyword format when you send multiple messages in Spring.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa805e6442b9b569aacfe88ac31c9857/href">https://medium.com/media/aa805e6442b9b569aacfe88ac31c9857/href</a></iframe><p>To process these events in the browser, an application needs to register a listener for the message event. The property data of the event object contains the message. The browser filters out the keyword data and the colon and only assigns the string after the colon to event.data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7a77ef9fa74619c0c4b6bb1cbb02c5a/href">https://medium.com/media/a7a77ef9fa74619c0c4b6bb1cbb02c5a/href</a></iframe><h4>Named Events</h4><p>A server can assign an event name to a message with the event: keyword. The event: line can precede or follow the data: line. In this example, the server sends 4 messages. The first message is an add event, the second a remove event then follows an add event again, and the last message is an unnamed event.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28e6f3ba8e292abdaa2880d34e108865/href">https://medium.com/media/28e6f3ba8e292abdaa2880d34e108865/href</a></iframe><p>Named events are processed differently by the client. They do not trigger the message handlers. Named events emit an event that has the same name as the event itself. For this example, we need 3 listeners to process all the messages. You cannot use the on... syntax for registering listeners to these events. They have to be registered with the addEventListener function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bde147bbe3bfbc5568d24d2320fb8f8f/href">https://medium.com/media/bde147bbe3bfbc5568d24d2320fb8f8f/href</a></iframe><p>I will be using <strong>Named Events</strong> for this demo for resolving concurrency issues. Using named events, multiple clients can call my “upload file” service simultaneously without any issue. The progress percentage for each of the clients will be as per their file processing and upload status. Progress percentage of one client won’t mess up the other. Please go through the implementation details to understand how did I achieve this.</p><h3>Implementation Details</h3><p>I will be using <strong>Spring Boot </strong>and <strong>React </strong>for this demo.</p><p>Spring Boot provides a way to implement SSE by using Flux which is a reactive representation of a stream of events, however, in this post, I will use the <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/SseEmitter.html">SseEmitter </a>class of Spring to create an async controller which will emit multiple messages to the client.</p><p>Here is the high-level architectural diagram of the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1aD6rliNjyImmFwbzDj8KA.jpeg" /><figcaption>High-Level Architecture</figcaption></figure><h4>General Steps involved in SSE are-</h4><ol><li>The client opens an HTTP connection.</li><li>The server can send any number of events(messages) to this connection asynchronously.</li><li>The server can close a connection or it can be closed because of some network error or any exception at the server-side.</li><li>In case the connection is closed because of any error from the server or any network error, the client will automatically try to re-connect</li></ol><h3>Server-Side Implementation in Spring Boot</h3><h4>Project Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*5vdCjzSkPKfhwDYKD9SilA.png" /><figcaption>Project Structure</figcaption></figure><p>I have created an async RESTcontroller with two methods responding to HTTP requests. One with @GetMappingannotation and another with @PostMapping annotation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dad8e9465fcd7987d87f838232344e82/href">https://medium.com/media/dad8e9465fcd7987d87f838232344e82/href</a></iframe><pre>private Map&lt;String, SseEmitter&gt; sseEmitters = new ConcurrentHashMap&lt;&gt;();</pre><ol><li>This <strong>map </strong>declared at the class level keeps track of the SseEmitters created for each client. I have used <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html">ConcurrentHashMap </a>for achieving concurrency and thread-safety.</li><li>In the first method with @GetMapping(&quot;/progress&quot;) annotation I have created an object of SseEmitter with an optional timeout as an argument in the constructor. I have set the timeout to a very large value so that it never times out automatically. <strong>This method generates a random UUID, creates an object of SseEmitter, and stores it in the map, with key as the random UUID and value as the object of the SseEmitter. </strong>This UUID is used to identify each client uniquely. You will understand how it is done as you read further.</li><li>The second method with @PostMapping(&quot;upload/local annotation is the one that listens to the POST request for uploading the files. It receives the file as a Multipart request and a unique UUID as a string. It then retrieves the SseEmitter object from the map(defined in step 1) and passes the object to the FileStorageService .</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e110cc49535c970b814dcc45a394e60d/href">https://medium.com/media/e110cc49535c970b814dcc45a394e60d/href</a></iframe><p>4. The FileStorageService reads the file line by line and runs some internal logic to calculate the percentage. It is here where you will have to write your logic to calculate the percentage and emit it using the object of SseEmitter that was passed to it. For demo purposes, I have written a simple logic to calculate the percentage while the file is being read line by line.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb03d4ad7a7b30f086ea6694eefffb66/href">https://medium.com/media/fb03d4ad7a7b30f086ea6694eefffb66/href</a></iframe><p>You can define the maximum file size that can be uploaded by writing these two properties in the application.properties file.</p><p>– spring.servlet.multipart.max-file-size: max file size for each request.<br>– spring.servlet.multipart.max-request-size: max request size for a multipart/form-data.</p><p>In case of error, you can send a special event with a complete error<strong> </strong>method. This will instruct the client about the error.</p><p>Finally, after sending all the messages, you have to complete the emitter by calling a <strong>complete</strong> method to close the connection, and then remove it from the map using the UUID key.</p><h3>Client-Side Implementation in React.js</h3><p>Events can be handled in any javascript library or framework like react, angular, etc. I have used <strong>React </strong>for this demo.</p><h4>Project Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*VaL2lLk5FtiQFdrCLerW2A.png" /></figure><p>I have simply created a react project with create-react-app and used the EventSource interface to subscribe to the endpoint as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05a547eb01d974ff3e71fcdbe0f7da5d/href">https://medium.com/media/05a547eb01d974ff3e71fcdbe0f7da5d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3gUz_VugItaHpcca84lKxw.png" /><figcaption>UI</figcaption></figure><p>When the user chooses a file and clicks the upload button, the client opens a connection with the EventSource object with the URL of the server API.</p><pre>const eventSource = new EventSource(&quot;http://localhost:8080/progress&quot;);</pre><p>It also registers an EventListener for an event named GUID to handle events returned from the server. Meanwhile, the server sends an event named GUID with data as a unique UUID. This UUID is used to uniquely identify a client. The client captures this UUID and sets up another EventListener of the type of that unique UUID.</p><p><em>For all the successful events from the server, the callback method which is passed as the second argument while registering the event listener will be called with one argument as an event object. Message sent from the server can be retrieved from event object by using property ‘data’, so </em><strong><em>event.data</em></strong><em> will hold the message sent by the server. This event.data can be a simple string or a JSON string. If it is a JSON string you have to parse it:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68b0b1f88f0aa5497475510b577374e0/href">https://medium.com/media/68b0b1f88f0aa5497475510b577374e0/href</a></iframe><p>Now, as the file is being read, the percentage is calculated with some logic and that is sent as data to the event of type unique UUID, that was generated when the client first opened the connection.</p><p>If during an upload process another client calls the upload API, a new unique UUID is generated, a new SseEmitter object is created and is put in the map. Now, the percentage values are calculated freshly for this call and do not affect the previous ongoing progress bar.</p><p>There are two other built-in events, one is ‘<strong>open</strong>’ which will be called once 200 status is received from the server. Another event is ‘<strong>error</strong>’, this will be called whenever there is a network error and also when the server closes the connection by calling a ‘<strong>complete</strong>’ or ‘<strong>completeWithError</strong>’ method on the emitter. You can close the connection at client-side by calling <strong>event.target.close</strong>(); , otherwise, the client will keep on retrying the connection in case of error, if you have used .reconnectTime(1000) while creating the SseEmitters.</p><blockquote>I have used the<a href="https://ant.design/components/progress/#header"> Ant Design Progress Component</a> for the progress indicator.</blockquote><p>So, that is how the live percentages are shown on file upload using server-sent events.</p><p>Here is the demo of the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ato7dGklnwxuupvApQbOQ.gif" /><figcaption>Live Demo</figcaption></figure><p>The complete code can be found in my <a href="https://github.com/arpan-banerjee7/sse-progressbar"><strong>GitHub </strong></a>repo.</p><p>That is all for this blog. Do follow me on <a href="https://arpan-banerjee7.medium.com/">Medium</a>, <a href="https://www.linkedin.com/in/banerjee-arpan7/">Linkedin</a>, and <a href="https://github.com/arpan-banerjee7">GitHub </a>for more blogs like this!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=723596f35225" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/implementation-of-server-sent-events-and-eventsource-live-progress-indicator-using-react-and-723596f35225">Implementation of Server-Sent Events and EventSource- Live Progress Indicator using React and…</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Server-Sent Events and understanding when to use Polling, WebSockets, and SSE]]></title>
            <link>https://medium.com/codex/getting-started-with-server-sent-events-and-understanding-when-to-use-polling-websockets-and-sse-87465f3bcf63?source=rss-adeb5e42707------2</link>
            <guid isPermaLink="false">https://medium.com/p/87465f3bcf63</guid>
            <category><![CDATA[server-sent-events]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[data-sharing]]></category>
            <dc:creator><![CDATA[Arpan Banerjee]]></dc:creator>
            <pubDate>Sat, 03 Jul 2021 02:31:30 GMT</pubDate>
            <atom:updated>2021-08-02T06:19:38.999Z</atom:updated>
            <content:encoded><![CDATA[<h4>A brief history of how data sharing over the internet evolved with real-time use cases for HTTP polling, WebSockets, and SSE.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uhyy4ibIFZFFXBib" /><figcaption>Photo by <a href="https://unsplash.com/@ptrikutam?utm_source=medium&amp;utm_medium=referral">Pavan Trikutam</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, I will describe a bit of the backstory of how data sharing over the internet evolved over time with emerging demands. I will introduce you to SSE and explain in which use cases you should go for SSE and avoid the overhead of web sockets.</p><p>In an upcoming article, I will explain to you, a use case in my Project where I needed to use SSE and, I will walk you through a POC developed using<strong> Spring Boot </strong>and<strong> React</strong> to demonstrate the idea.</p><p><strong>Here is the use case that I was talking about: “ On file upload, display a real-time progress bar that shows how much the server has processed so far, without hitting endpoints repeatedly in the progress bar.”</strong></p><h3>A Brief History of Data Sharing over the Internet</h3><p>It all started with the HTTP one of requests and responses. One entity opens a connection and requests a resource or service, then the other response, either with the requested resource or an error response if it isn’t available. After each request-response cycle, the connection is closed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*flQFi39mZQVfKDyrc-Db-A.png" /><figcaption>HTTP request-response cycles</figcaption></figure><p><em>With HTTP a stateless protocol, if the same two entities need to communicate again, it occurs over a new connection.</em></p><blockquote>This is one of the drawbacks of this kind of communication.<em> </em>For event-driven applications, HTTP — in its natural form — doesn’t quite cut it.</blockquote><p>Take Stock pricing as an example. The application would request current share pricing from a data provider and display it on the webpage in the HTTP scenario. <em>However, the concept of ‘updates’ is non-existent in HTTP land.</em> If the app requires more recent data, the logical step is to refresh the page and send out a new HTTP request. While it vaguely does the job, frequently sending out requests is not ideal for implementing this and is also energy-intensive.</p><p><strong>To enable these real-time communications let&#39;s see what options do we have.</strong></p><h4>HTTP Polling/ Short Polling</h4><p><em>Short polling</em> is an AJAX-based timer that calls at fixed delays. Here using the REST endpoints constant requests are made to the server to see if new information has arrived. So, basically, the client makes requests on a set frequency, it results in a lot of requests and often the server comes back with the same “stale” response. So, it is not that beneficial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*7ynUzCOGdx2uN2v4984yhA.png" /><figcaption>HTTP Polling</figcaption></figure><p><em>Here is how you would go about this in JavaScript.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3dc47b32c42802231d85a7bfedbc5330/href">https://medium.com/media/3dc47b32c42802231d85a7bfedbc5330/href</a></iframe><h4>HTTP Long Polling</h4><p>An improvement to HTTP-Polling is HTTP Long Polling. Here response to a request is returned only when new data appears, made possible by persisting the connection.</p><p>The only difference to basic polling, as far as the client is concerned, is that a client performing basic polling may deliberately leave a small time window between each request to reduce its load on the server, and it may respond to timeouts with different assumptions than it would for a server that does not support long polling. With long polling, the client may be configured to allow for a longer timeout period (via a Keep-Alive header) when listening for a response – something that would usually be avoided seeing as the timeout period is generally used to indicate problems communicating with the server.</p><p>So it’s almost the same thing, we have to open new HTTP requests every time for fetching new data, it is not bi-directional at all.</p><p>For more details on its limitations visit- <a href="https://stackoverflow.com/questions/21676324/hard-downsides-of-long-polling">https://stackoverflow.com/questions/21676324/hard-downsides-of-long-polling</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SydrgWJaX5F_7i_d3efjOA.png" /><figcaption>HTTP Long Polling</figcaption></figure><h4>HTTP Streaming</h4><p>HTTP Streaming is a push-style data transfer technique that allows a web server to continuously send data to a client over a single HTTP connection that remains open indefinitely. Technically, this goes against HTTP convention, but HTTP Streaming is an efficient method to transfer all kinds of dynamic or otherwise streamable data between the server and client without reinventing HTTP.</p><p>SSE builds on top of HTTP Streaming which is the standardization of what was before ‘loosely defined’ in terms of HTTP Streaming. It also introduced easier browser APIs to handle this. It uses the JavaScript<a href="https://developer.mozilla.org/en-US/docs/Web/API/EventSource"> EventSource API</a> in order to subscribe to a stream of data in any popular browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*BZiuYoLQ9IsglYfjcrQ7YA.png" /><figcaption>HTTP Streaming</figcaption></figure><h4>Web Sockets</h4><p>WebSocket connections employ TCP/IP in the transport layer to provide a full-duplex connection. Both communicating parties can now send messages in both directions — simultaneously. The connection is persistent, meaning that it is kept open for as long as the application runs. The connection is also stateful — the server can initiate a message or vice-versa.</p><p><strong>Use cases-</strong></p><ul><li>Messaging App</li><li>Multiplayer Games</li><li>Collaborative editing/coding</li><li>Location-based apps</li></ul><p>I encourage you to go through the <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API">MDN</a> doc, it explains WebSocket in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*7R0vfZaiDe8HOQUlA45xjA.png" /><figcaption>WebSockets</figcaption></figure><h3>Introduction To Server-Sent Events</h3><p>While WebSockets solves most of the real-time use cases out there, but sometimes it might well be overkill. Like in scenarios where we do not need bi-directional communication, SSE might be the way to go.</p><blockquote>SSE is a lightweight protocol on top of HHTP Streaming that allows super light-weight subscribe-only capabilities to clients. Unlike WebSockets, SSE does not provide the capability of two way communication, but can be used by the server to push data to the clients in real-time.</blockquote><p>Server-Sent Events (SSE) is a server push technology enabling a client to receive automatic updates from a server via an HTTP connection. The Server-Sent Events EventSource API is standardized as part of HTML5 by the W3C.</p><p>It provides a memory-efficient implementation of XHR streaming. Unlike a raw XHR connection, which buffers the full received response until the connection is dropped, an SSE connection can discard processed messages without accumulating all of them in memory.</p><p>SSE is designed to use the JavaScript EventSource API in order to subscribe to a stream of data in any popular browser. Through this interface, a client requests a particular URL to receive an event stream. SSE is commonly used to send message updates or continuous data streams to a browser client.</p><p>In a nutshell, a server-sent event is when updates are pushed (rather than pulled, or requested) from a server to a browser.</p><h4><strong>Use Cases:</strong></h4><p>SSE can be particularly used when the client is just interested in subscribing to a stream of data without needing to communicate back to the server in the same connection.</p><ul><li>Subscribing to a feed of cryptocurrency or stock prices</li><li>Subscribing to a Twitter feed</li><li>Receiving live sports scores</li><li>News updates or alerts</li></ul><p>For more details please visit this <a href="https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events">MDN article</a> on SSE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*IpawgiAl7RQpcD47HqEu4w.png" /><figcaption>Server-Sent Events</figcaption></figure><p>That’s all for this blog. Thanks for reading!</p><p>Here is the demo of the POC, which I mentioned earlier.</p><blockquote><a href="https://medium.com/codex/implementation-of-server-sent-events-and-eventsource-live-progress-indicator-using-react-and-723596f35225">Implementation of Server-Sent Events and EventSource- Live Progress Indicator using React and Spring Boot</a>, explains the POC in detail with a code walk-through.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ato7dGklnwxuupvApQbOQ.gif" /></figure><p>If you liked this blog, follow me on <a href="https://arpan-banerjee7.medium.com/">Medium</a>, <a href="https://www.linkedin.com/in/banerjee-arpan7/">Linkedin</a>, and <a href="https://github.com/arpan-banerjee7">GitHub </a>for more blogs like this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87465f3bcf63" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/getting-started-with-server-sent-events-and-understanding-when-to-use-polling-websockets-and-sse-87465f3bcf63">Getting Started with Server-Sent Events and understanding when to use Polling, WebSockets, and SSE</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concept of String Pool And String Object Creation In Java]]></title>
            <link>https://arpan-banerjee7.medium.com/concept-of-string-pool-and-string-object-creation-in-java-27ed2b3089f5?source=rss-adeb5e42707------2</link>
            <guid isPermaLink="false">https://medium.com/p/27ed2b3089f5</guid>
            <category><![CDATA[string-pool]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[string]]></category>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[jvm]]></category>
            <dc:creator><![CDATA[Arpan Banerjee]]></dc:creator>
            <pubDate>Sat, 15 May 2021 19:48:44 GMT</pubDate>
            <atom:updated>2021-07-04T18:19:23.281Z</atom:updated>
            <content:encoded><![CDATA[<p>A detailed explanation of how many objects are created while using <strong>“string literals”</strong> vs using the<strong> “new” </strong>keyword and JVM allocates memory when it comes to the String class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6DrZ-GTkZzzY8qJT" /><figcaption>Photo by <a href="https://unsplash.com/@nopizzanocry?utm_source=medium&amp;utm_medium=referral">john labelette</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello! Welcome to a new blog. Today I am going to talk about a very common yet very important concept. In interviews, you will get a lot of questions centered around this topic.</p><blockquote>Why is String immutable? What is String constant pool? How many objects are created when you write this piece of code String s1 = new String(&quot;Guess&quot;); ? What are the benefits of having a String Pool? What does String.intern() method do? etc.</blockquote><p>Let’s find the answers to all of the questions by exploring what happens behind the scenes when you create a String Object using different approaches</p><h3>What is String Pool in Java?</h3><p>String Pool is a place in the HEAP memory of Java to store string literal.</p><p>String allocation, like all object allocation, proves to be a costly affair in both the cases of time and memory. The JVM performs some steps while initializing string literals to increase performance and decrease memory overhead. To decrease the number of String objects created in the JVM, the String class keeps a pool of strings.</p><p>Each time a string literal is created, the JVM checks the string literal pool first. If the string already exists in the string pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object initializes and is placed in the pool.</p><p>String Pool is possible only because<em> String is immutable</em> in Java and its implementation of <em>String interning</em> concept.</p><h3>String Immutability and Advantages</h3><p>If you look at the String <em>class </em>definition, it has been declared as <em>final</em>. <strong>So once the String object is created, it cannot be modified.</strong></p><p>Strings are immutable in java because String objects are cached in String Pool. Since cached String literals are shared between multiple objects, so there is always a risk, where changes made by an object affect others.</p><h4>Advantages</h4><ol><li>Strings are very popular candidates for the HashMap key, they need to be immutable to retrieve the value object stored in HashMap. Since HashMap works in the principle of hashing, which requires the same has value to function properly. Since String is immutable, its hashcode is cached at the time of creation and doesn’t need to be calculated again. If Strings were mutable, it would produce two different hashcodes at the time of insertion and retrieval if contents of String were modified after insertion, which is not at all ideal.</li><li>Another reason is, it helps JVM save a lot of heap space, by caching the String literals in the pool.</li><li>In Java, security parameters are typically represented as String, for example, in-network connections, database connection URLs, usernames/passwords, etc. If it were mutable, these parameters could be easily changed. It’s also used extensively by JVM class loaders while loading classes.</li><li>Making String immutable automatically makes them thread-safe, thereby solving synchronization issues.</li></ol><p><em>Enough of theory! Let’s see some code snippets and understand the above concepts.</em></p><h3>Basic Concept With An Example</h3><h4>String objects are created in two ways :</h4><h4>1. Using double quotes(“ ”) [when String literals are used ]</h4><p>Whenever we use this approach to create Strig objects it makes use of the string pool concept and thus is efficient.</p><pre><strong>String s1= “Arpan”;</strong></pre><p>The above statement first searches for the string <strong>“Arpan”</strong> in the string pool, if found it just gives it a reference s1. If not found it creates a string object and places it in the string pooland then gives it a reference s1.</p><blockquote>In this case, <strong>only one object is created: </strong><em>in the </em><em>string pool.</em></blockquote><h4>2. Using the ‘new’ keyword :</h4><pre><strong>String s2= new String(“Banerjee”);</strong></pre><p>The above statement creates a string object in heap memory and checks whether it is present in the string poolor not. If the string <strong><em>“</em>Banerjee<em>”</em> </strong>is not present in the string poolthen it will place this string in the string pool else it will skip it.</p><blockquote><strong>Case 1:</strong> Two objects are created: one in theheap memory and the other in the string pool.</blockquote><blockquote><strong>Case 2:</strong> Only one object is created: in theheap memory .</blockquote><blockquote>Now you might have this question</blockquote><p>Let’s say we create a String using the above approach. So, a string object will be created In the heap memory having the value<strong> “Banerjee” </strong>and s1 will point to it. Now, if <strong>“Banerjee”</strong> is not present in the string pool, I just said that it will create an object in the string pool as well.</p><p><strong>But, have you ever thought of this, who will point to this object? </strong><strong>s1?</strong></p><blockquote>No, JVM will point to that object.</blockquote><p>Therefore, in the interest of speed and optimization, it is always advisable to use string literals way of creating strings, unless we specifically want a new object to be created for the string.</p><h3>Understanding Immutability With An Example</h3><p>Let’s create a string with <em>string literals notation.</em></p><pre>String s1= &quot;java&quot;;</pre><p>This, as usual, creates a string containing &quot;java&quot; and assigns it a reference s1. Simple enough? Okay.</p><p>Let’s see what happens when we modify the string:</p><pre>s1= s1.concat(&quot; code&quot;);</pre><p>This appends a string &quot; code&quot; to s1. Now what do you get when you try to print the value of s1 .</p><pre>System.out.print(s1);<br>-&gt; java code</pre><p>But, we just learned that strings are immutable, right? But the console says something else, is it?</p><p><strong>Well no</strong>, the above operation did not modify s1 . JVM created a new String object gave it a value &quot;java code&quot;, and gave it a reference str.</p><blockquote>Here we have 3 objects: java, code and java code . s1 points to java code.</blockquote><h4>A code sample to make the concepts more clear.</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/372b70c2a4ca65d02b87a1eb0d9b1bfe/href">https://medium.com/media/372b70c2a4ca65d02b87a1eb0d9b1bfe/href</a></iframe><p>So, can you tell me how many objects are created in the above program? Think about whatever we learned till now….</p><blockquote>4 objects will be created in the above program.</blockquote><ol><li><strong>Two </strong>in the heap: <strong>“Arpan” </strong>pointed by st1and <strong>“Banerjee” </strong>by st2, because of the new keywords.</li><li><strong>Two </strong>in the string pool : <strong>“Banerjee” </strong>pointed by JVM and <strong>“Arpan” </strong>pointed by<strong> </strong>s1, s2 and s3.</li></ol><h4>Here is the diagram of the objects and memory allocation:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*6l_-GfhR-d0YZgOMSZK8Ag.png" /></figure><h3>Advanced examples</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77fb80bf96e8153f3ba6fab3128a8d74/href">https://medium.com/media/77fb80bf96e8153f3ba6fab3128a8d74/href</a></iframe><p>How many objects are created in the above example?</p><blockquote>6 objects are created. By now you must know why and how.</blockquote><p>See the diagram below if you have any confusion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*9baizw0gZsPWF_Ul5sswBQ.png" /></figure><h3>One Last Thing: String.intern() Method</h3><p>The<strong> intern() </strong>method of the String method returns a canonical representation for the string object.</p><p>It creates an exact copy of a <em>String</em> object in the heap memory and stores it in the <em>String</em> constant pool.</p><p>When the intern method is invoked, if the string pool already contains a string equal to this newly created String object using String.intern() method, then the string from the pool is returned. Otherwise, this String object is added to the pool, and a reference to it is returned.</p><h4>Here is a java code demonstrating the above-mentioned concept.</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/639612566c996b66de4c0d3c1414a66f/href">https://medium.com/media/639612566c996b66de4c0d3c1414a66f/href</a></iframe><blockquote>For this example, <strong>3 objects</strong> will be created, one in heap , other two in the string <em>pool .</em></blockquote><p>Here is the diagram showing the objects and it’s references.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*SIvJhJ3sji7XyqngjM6M2g.png" /></figure><p>Okay, that&#39;s all for this article. I am sure by now you understand the concept of string pool in java and you know how objects are created in heap and string pool , using string literals notation and new keyword.</p><p>Let me know if you have any questions or suggestions in the comment section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27ed2b3089f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Run React and SpringBoot on the same port and Package them as a single artifact !!]]></title>
            <link>https://medium.com/codex/run-react-frontend-and-springboot-backend-on-the-same-port-and-package-them-as-a-single-artifact-a790c9e10ac1?source=rss-adeb5e42707------2</link>
            <guid isPermaLink="false">https://medium.com/p/a790c9e10ac1</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Arpan Banerjee]]></dc:creator>
            <pubDate>Sun, 11 Apr 2021 15:43:11 GMT</pubDate>
            <atom:updated>2021-07-24T18:27:26.671Z</atom:updated>
            <content:encoded><![CDATA[<h3>Run React and SpringBoot on the same port and Package them as a single artifact !!</h3><h4>It requires frontend-maven-plugin, maven-resources-plugin and thymleaf.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TYzuIblN_HWxIavr" /><figcaption>Photo by <a href="https://unsplash.com/@sapegin?utm_source=medium&amp;utm_medium=referral">Artem Sapegin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hey there! I am a full stack developer with 3+ years of experience based out of West Bengal, India. <em>Today I will walk you through a setup trick to prepare your project structure for running react and spring boot app on the same port, and package them as a single artifact.</em> You will see how easy this can make development when dealing with both of these game-changing technologies.</p><blockquote><a href="https://github.com/arpan-banerjee7/demo-spring-react-maven-plugin"><strong>Here is the GitHub link to the demo that I am going to explain here.</strong></a></blockquote><h3>Advantages of this setup</h3><p>1. Combines the ease of development of both <a href="https://reactjs.org/docs/create-a-new-react-app.html">create-react-app</a> and Spring Boot.</p><p>2. You can use the hot reload feature of <a href="https://reactjs.org/docs/create-a-new-react-app.html">create-react-app</a> while developing the frontend, save the page after making changes and it will reflect immediately on the browser.</p><p>3. Using Spring Boot you can easily manage your development versions (using SNAPSHOTs) and release versions in production. You can detect build version and time at runtime in Spring Boot using <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-features.html">Spring Actuator</a> or Spring Admin, which can provide the build metadata functionality plus a lot more.</p><p>4. Package Frontend and Backend in a single war/jar file with optimized production build.</p><p><strong>I learned this in one of my recent projects. It has several spring boot microservices with react frontend packaged and deployed as single artifacts of their own.</strong></p><p><em>So, here is a quick guide how to run a react frontend and a spring boot backend on the same port and how to package them as a single jar file.</em></p><p><strong>First</strong>, <strong>create a spring boot project</strong> with<a href="https://start.spring.io/"> https://start.spring.io</a>. Add the Web dependency. Set the groupidand artifactidto whatever you want. Generate the project and unzip it into your project directory.</p><p>Or, if you are using Spring Tools Suite you can simply click File-&gt;new-&gt;Spring Starter Project mention the required details to create a spring boot project.</p><p>Your initial <strong>pom.xml </strong>should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uqTcns6UBatjCnXzcSy9FQ.png" /><figcaption>pom.xml</figcaption></figure><p>The project structure should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*eRp5j4OudsHzhfTAjKgTHg.png" /></figure><p>You can run the app now and see if it runs without any errors.<br>Though you won’t see anything if you hit http://localhost:8080/ .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*HwKcpVMWVOZr2aY9-Mx5Nw.png" /><figcaption><a href="http://localhost:8080/">http://localhost:8080/</a></figcaption></figure><p>Now, go to src/main/resources, create a static folder. Inside it create a test.html file with some text in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*VBDcae-5NFr6BJAMptRorQ.png" /></figure><p>Now, if you restart the application and hit http://localhost:8080/test.html you will see it spins up your html page in port 8080. You can see the contents of your file in the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vBmMMzatpKVxfSVVn6QkHQ.png" /><figcaption><a href="http://localhost:8080/test.html">http://localhost:8080/test.html</a></figcaption></figure><h3>Serving the React App from Spring Boot on port 8080 and Packaging them together</h3><blockquote>We will exploit the above mentioned feature of Spring Boot to serve the single page of the react project. We will serve a html page from the `static` folder in the `target` directory, not in the source directory.</blockquote><p>Now let’s create a react app, using <a href="https://reactjs.org/docs/create-a-new-react-app.html">create-react-app</a>. Navigate to your folder till src/main in a terminal.</p><p>D:\Codes_projects\srpingboot_react_maven_plugin\Spring_React_maven-plugin\src\main and run npx create-react-app frontend.</p><p>This should create a react app inside src/main. Now if you look at your folder structure it should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*4NCQWkwgSM5r5SemqhKQtA.png" /></figure><p>You can run the react app, by doing cd frontendand then yarn start or npm start. It should spin up the react app on http://localhost:3000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QKbzizZjiQdLxwjVjTxU-g.png" /><figcaption><a href="http://localhost:3000/">http://localhost:3000</a></figcaption></figure><p>You can create a production build of the frontend by running yarn build. Your folder structure after running the build command will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*vrO7LXwsZ1mkqIkek1ymEQ.png" /></figure><blockquote>You need to copy this production build place it inside the `target/classes` directory of your project to enable Spring Boot to serve this `index.html` when you start your project</blockquote><p>So, there are two steps-</p><p><strong>1. create a production build of the frontend<br>2. copy the production build into ${target/classes/}</strong></p><p>Of course you are not going to do that manually.<br>We we will use two `maven plugins` for that.</p><p><strong>1. </strong><a href="https://github.com/eirslett/frontend-maven-plugin"><strong>frontend-maven-plugin</strong></a><strong> for step <br>2. </strong><a href="https://maven.apache.org/plugins/maven-resources-plugin/"><strong>maven-resources-plugin</strong></a><strong> for step 2.</strong></p><p>Add the following to your pom.xml under the plugins section and update the propertiessection as shown.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39321d555c32c40b090795bd1968f336/href">https://medium.com/media/39321d555c32c40b090795bd1968f336/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ed412438fcbb13594d5feb57d7a1617/href">https://medium.com/media/2ed412438fcbb13594d5feb57d7a1617/href</a></iframe><p>Now if you run mvn clean installfrom D:\Codes_projects\springboot_react_maven_plugin\Spring_React_maven-plugin maven will install npm, yarnand nodelocally and run npm buildin the frontend directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k9VkCqU4_ubNqJoKv5nfyw.png" /><figcaption>Console</figcaption></figure><p>The folder structure would look like this-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*K4kxRVPTPiUHef61aeThQQ.png" /></figure><p>Now, add the second plugin to your pom.xml.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efd5ae854458a63fa892ff77512c596a/href">https://medium.com/media/efd5ae854458a63fa892ff77512c596a/href</a></iframe><p>Add the following dependency in the dependencies section.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcdb059e766bc4aca07f7f87992862f6/href">https://medium.com/media/fcdb059e766bc4aca07f7f87992862f6/href</a></iframe><p>Modify the spring-boot-maven-plugin to include a configuration section.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a91086959cccf5ecfd2765b17bf7428e/href">https://medium.com/media/a91086959cccf5ecfd2765b17bf7428e/href</a></iframe><p>This will ensure that the frontend build files are copied after they have been generated by yarn build.<br>Now, run mvn clean installagain and inspect the target/classes/static directory from your file manager.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bid0cQ787ayyKUEuC2Wa8w.png" /><figcaption>File Manager</figcaption></figure><p>It will have the frontend production build files in there.</p><blockquote>Now you are ready to go! Run the project and go to http://localhost:8080/index.html VOILA!! You have run your React app via Spring Boot.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D0BSJ74u44u6vS75GyOmTw.png" /><figcaption><a href="http://localhost:8080/index.html"><em>http://localhost:8080/index.html</em></a></figcaption></figure><h4><strong>Final Pom.xml</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/def9164f5c7326258c61349d20fbc7e6/href">https://medium.com/media/def9164f5c7326258c61349d20fbc7e6/href</a></iframe><h3>Taking a step further</h3><p>You can add rest controllersand expose an endpoint to be the starting point of the application. Like an Index Controller, whenever the application loads, spring boot will spin up the index.htmlfile having the static contents from the optimized build of the frontend project from the `target directory`. So that you can simply visit http://localhost:8080and not hardcode the index.htmlfile name.</p><p>Let’s do that.<br>Add a controller, in the following folder structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*tA-ihPQLKokvg4U-dwn4fg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e69e3763b787e475440cd224834fedd/href">https://medium.com/media/7e69e3763b787e475440cd224834fedd/href</a></iframe><blockquote>Run your application and hit http://localhost:8080/.<br>Did you see anything? No, right!</blockquote><p><strong>You have to add another dependency for this to work.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a58e2cf47019601175b0108b0880a625/href">https://medium.com/media/a58e2cf47019601175b0108b0880a625/href</a></iframe><p>Now, by default Thymleaf looks for our templates in src/main/resources/templates. We can put our templates there and organize them in sub-directories and have no issues.</p><p>So, let’s try that. Add a html file inside src/main/resources/templates named index.html and put some content in it.</p><p>Run the application and visit http://localhost:8080You will see the index.hymlfrom src/main/resources/templatesbeing served in port 8080.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lky-1avVtcCAJjW0CNFuxQ.png" /><figcaption><a href="http://localhost:8080/">http://localhost:8080</a></figcaption></figure><p>Now, to change this default behaviour and make Thymleaf serve static content from another location, you need to add an entry to the application.propertiesfile.</p><pre>spring.thymeleaf.prefix=file:///D:///Codes_projects//springboot_react_maven_plugin//Spring_React_maven-plugin//target//classes//static/</pre><p>Here, I have hardcoded the path.</p><p>Finally, now if you `update` your project and start it. You can see the react app being served directly on port 8080.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_R4AU_a3IsLRZtpGH8TNg.png" /><figcaption><a href="http://localhost:8080/">http://localhost:8080</a></figcaption></figure><h3>Conclusion</h3><p>You have learned how to use spring boot to run a react app. You can run both your frontend and backend on the same port. I have explained what you need to do to get the setup done. You can now create a meaningful application, and see how easy and quick it is to develop with this setup. You can now run the frontend application using React-scripts by running cd frontedn; yarn start, and develop using the hot reload feature of <a href="https://reactjs.org/docs/create-a-new-react-app.html">create-react-app</a> and have meaningful error messages, while being able to deploy the application to test and production environments as a single artifact.</p><p>Thanks for reading!</p><p>Please leave a comment if you find this helpful. Any feedback or suggestions are welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a790c9e10ac1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/run-react-frontend-and-springboot-backend-on-the-same-port-and-package-them-as-a-single-artifact-a790c9e10ac1">Run React and SpringBoot on the same port and Package them as a single artifact !!</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>