<?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 Thameem Ansari on Medium]]></title>
        <description><![CDATA[Stories by Thameem Ansari on Medium]]></description>
        <link>https://medium.com/@reachansari?source=rss-5365dede21aa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GRLpgAgrt7EAGO-hB9OImw.jpeg</url>
            <title>Stories by Thameem Ansari on Medium</title>
            <link>https://medium.com/@reachansari?source=rss-5365dede21aa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 09:50:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@reachansari/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[Elasticsearch Example using Spring Boot Reactive]]></title>
            <link>https://medium.com/javarevisited/elasticsearch-example-using-spring-boot-reactive-f237dc7a6391?source=rss-5365dede21aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/f237dc7a6391</guid>
            <category><![CDATA[springboot-2]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[Thameem Ansari]]></dc:creator>
            <pubDate>Wed, 05 Jul 2023 11:26:39 GMT</pubDate>
            <atom:updated>2023-07-06T15:52:30.151Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L7deu1wSplY4ho7hlWjrUA.jpeg" /><figcaption>Elasticsearch Example using Spring Boot Reactive</figcaption></figure><h3>Introduction</h3><p>Elasticsearch is a document-based search engine that is fast and widely used. We can use the Spring boot reactive data libraries to interact with the Elasticsearch server while developing a reactive spring application.</p><p>In this article, we will learn how to interact with the Elasticsearch server from a reactive spring boot application.</p><p><strong><em>Technologies used in the article:</em></strong></p><ul><li>Spring boot: 2.7.3</li><li>Elasticsearch: 7.17.4</li><li>Java: 17</li></ul><h3>Create a spring boot application</h3><p>Create a spring boot application with the required dependencies. Add the dependency <strong>spring-boot-starter-data-elasticsearch</strong> that we can leverage to interact with the Elasticsearch server.</p><p>Since we are creating a reactive style application, we will use the <strong>spring-boot-starter-webflux</strong> starter dependency.</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-webflux&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-data-elasticsearch&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>    &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>    &lt;optional&gt;true&lt;/optional&gt;<br>&lt;/dependency&gt;</pre><h3>Elasticsearch configuration</h3><p>Next step is to create a configuration class, that extends <strong>AbstractReactiveElasticsearchConfiguration</strong> class’s <strong>reactiveElasticsearchClient()</strong> method. Here, we can specify the Elasticsearch connection string and other properties.</p><p>This <strong>ReactiveElasticsearchClient</strong> instance is used by the spring data repositories while performing the CRUD operations.</p><pre>@Configuration<br>public class ReactiveRestClientConfig extends AbstractReactiveElasticsearchConfiguration {<br>    @Override<br>    public ReactiveElasticsearchClient reactiveElasticsearchClient() {<br>        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()<br>                .connectedTo(&quot;localhost:9200&quot;)<br>                .build();<br>        return ReactiveRestClients.create(clientConfiguration);<br>    }<br>}</pre><h3>Creating Elasticsearch documents</h3><p>We will create a document class that stores student details like name, address, subjects, etc.</p><p>First, we will create a <strong>Student</strong> class with details like enrolled subjects and address details, etc.</p><pre>@Document(indexName = &quot;student-details&quot;)<br>@Data<br>public class Student {<br>    @Id<br>    private String id;<br>    @Field(type = FieldType.Text)<br>    private String firstName;<br>    private String lastName;<br>    private int age;<br>    @Field(type = FieldType.Date, format = DateFormat.date)<br>    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = &quot;yyyy-MM-dd&quot;)<br>    private LocalDate joinDate;<br>    private Address address;<br>    @JsonInclude(JsonInclude.Include.NON_NULL)<br>    private List&lt;Subject&gt; subjects;<br>}</pre><ul><li>We can specify the Elasticsearch document by annotating the class with the <strong>@Document</strong> annotation. We can also mention the index name of the Elasticsearch document.</li><li>Every Elasticsearch document needs a unique id field that is specified by annotating it with the <strong>@Id</strong> annotation.</li><li>Elasticsearch supports many document field types, and we can explicitly specify the field type with the help of <strong>@Field</strong> annotation.</li></ul><p>Let’s also create an<strong> Address</strong> class that holds the student’s address details.</p><pre>@Data<br>public class Address {<br>    private String street;<br>    private Integer doorNo;<br>}</pre><p>Also, create a Subject class as shown below.</p><pre>@Data<br>@RequiredArgsConstructor<br>public class Subject {<br>    private String name;<br>}</pre><p>Add the below configuration property into the spring boot application’s <strong>application.yml</strong> file.</p><p>By adding this, Jackson library generates Snake case JSON fields while converting the java classes to JSON.</p><pre>spring:<br>  jackson:<br>    property-naming-strategy: SNAKE_CASE</pre><h3>Adding spring data repository</h3><p>Create a <strong>StudentRepository</strong> interface that extends the<strong> ReactiveElasticsearchRepository</strong> interface. We can use this repository instance to perform CRUD operations on Elasticsearch documents.</p><p>We can also add custom finder methods, as shown below.</p><pre>public interface StudentRepository extends ReactiveElasticsearchRepository&lt;Student, String&gt; {<br>    Flux&lt;Student&gt; findByFirstName(String firstName);<br>}</pre><h3>Adding CRUD service implementation</h3><p>Now let’s create a service layer to add CRUD functionality.</p><p>Create a <strong>StudentService</strong> interface and add the below method signatures.</p><pre>public interface StudentService {<br>    Mono&lt;Student&gt; createStudent(Student student);<br>    Mono&lt;Student&gt; updateStudent(String id, Student student);<br>    Mono&lt;String&gt; deleteStudent(String id);<br>    Flux&lt;Student&gt; getStudentByFirstName(String firstName);<br>    Flux&lt;Student&gt; getAllStudents();<br>}</pre><p>Create an implementation class and implement the methods defined in the service interface.</p><p>We use the Elasticsearch repository to interact with the server and CRUD operations.</p><pre>@RequiredArgsConstructor<br>@Slf4j<br>@Service<br>public class StudentServiceImpl implements StudentService {<br><br>    private final StudentRepository studentRepository;<br><br>    @Override<br>    public Mono&lt;Student&gt; createStudent(Student student) {<br>        return studentRepository.save(student);<br>    }<br><br>    @Override<br>    public Mono&lt;Student&gt; updateStudent(String id, Student student) {<br>        return studentRepository.findById(id).flatMap(std -&gt; {<br>                    log.info(&quot;std-{}&quot;, std);<br>                    std.setFirstName(student.getFirstName());<br>                    std.setLastName(student.getLastName());<br>                    std.setJoinDate(student.getJoinDate());<br>                    std.setSubjects(student.getSubjects());<br>                    std.setAge(student.getAge());<br>                    std.setAddress(student.getAddress());<br>                    return studentRepository.save(std);<br>                })<br>                .doOnError(e -&gt; log.error(String.valueOf(e)));<br>    }<br><br>    @Override<br>    public Mono&lt;String&gt; deleteStudent(String id) {<br>        return studentRepository.deleteById(id)<br>                .thenReturn(&quot;Student deleted successfully!&quot;);<br>    }<br><br>    @Override<br>    public Flux&lt;Student&gt; getStudentByFirstName(String firstName) {<br>        return studentRepository.findByFirstName(firstName);<br>    }<br><br>    @Override<br>    public Flux&lt;Student&gt; getAllStudents() {<br>        return studentRepository.findAll();<br>    }<br>}</pre><h3>Adding Controller class</h3><p>Finally, create the REST endpoints to expose the CRUD APIs, as shown below.</p><pre>@RequiredArgsConstructor<br>@RestController<br>public class StudentController {<br><br>    private final StudentService studentService;<br><br>    @PostMapping(&quot;/students&quot;)<br>    public Mono&lt;Student&gt; createStudent(@RequestBody Student student){<br>        return studentService.createStudent(student);<br>    }<br><br>    @PutMapping(&quot;/students/{id}&quot;)<br>    public Mono&lt;Student&gt; updateStudent(@RequestBody Student student, @PathVariable(&quot;id&quot;) String id) {<br>        return studentService.updateStudent(id, student);<br>    }<br><br>    @DeleteMapping(&quot;/students/{id}&quot;)<br>    public Mono&lt;String&gt; deleteStudent(@PathVariable(&quot;id&quot;)  String id){<br>        return studentService.deleteStudent(id);<br>    }<br><br>    @GetMapping(&quot;/students/{first-name}&quot;)<br>    public Flux&lt;Student&gt; getStudentByFirstname(@PathVariable(&quot;first-name&quot;) String firstName) {<br>        return studentService.getStudentByFirstName(firstName);<br>    }<br><br>    @GetMapping(&quot;/students&quot;)<br>    public Flux&lt;Student&gt; getAllStudents() {<br>        return studentService.getAllStudents();<br>    }<br>}</pre><h3>Testing the CRUD APIs</h3><p>We will use the Postman tool to test our CRUD endpoints. By default, the application starts with port number 8080.</p><h4>Create API</h4><p>Invoke the <strong>POST </strong>API <strong>/students</strong> with the required student request JSON payload, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*JBoFDKC9usNgaRgvppBF9A.png" /><figcaption>Create API</figcaption></figure><h4>Update API</h4><p>To update the saved student document, we can use the <strong>PUT</strong> API: <strong>/students/{id}</strong>.</p><p>Here, the <strong>id</strong> is the unique student id generated during the document creation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*D6UasGe8bKpINFsYISZwfw.png" /><figcaption>Update API</figcaption></figure><h4>Get API</h4><p>We can fetch all the saved student documents by invoking the <strong>GET</strong> API: <strong>/students</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*tFX5AVdaYdMhANPhfoU4BQ.png" /><figcaption>Get API</figcaption></figure><h4>Delete API</h4><p>To delete a particular student document, we can use the <strong>DELETE</strong> API: <strong>/students/{id}</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*MG3a6gkApBmaFGT0D9TYCg.png" /><figcaption>Delete API</figcaption></figure><h3>Conclusion</h3><p>In this post, we learned how easy it is to create a Spring boot reactive application and perform CRUD operations with Elasticsearch documents.</p><p>We also learned how the spring boot framework provides the necessary support for interacting with Elasticsearch by providing the Elasticsearch spring data starter library.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f237dc7a6391" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/elasticsearch-example-using-spring-boot-reactive-f237dc7a6391">Elasticsearch Example using Spring Boot Reactive</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Executing Dependent and Independent tasks in parallel using Java]]></title>
            <link>https://medium.com/javarevisited/executing-dependent-and-independent-tasks-in-parallel-using-java-bd559b85ceec?source=rss-5365dede21aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd559b85ceec</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Thameem Ansari]]></dc:creator>
            <pubDate>Wed, 28 Jun 2023 06:43:10 GMT</pubDate>
            <atom:updated>2023-07-06T15:52:28.146Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*Z4tLydYAoLkupWophmA5qw.png" /><figcaption>Photo by <a href="https://unsplash.com/@redviking509?utm_source=medium&amp;utm_medium=referral">John Anvik</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In this article I am going to show you how to call dependent and independent tasks in parallel using Java CompletableFuture. So basically three tasks will be invoked parallelly and in parallel execution the response time will be very less. I am going to show you how to execute concurrently using Java 8 with CompletableFuture.</p><h3>Problem Statement</h3><p>Lets say Task A, Task B and Task C to execute as dependent and independent tasks in parallel mode with below conditions.</p><ol><li>Task A and Task C can run independently.</li><li>Task B is dependent on the output of Task A.</li></ol><p>In order to achieve we will make use of a simple Barrista making coffee scenario.</p><h3>Use Case</h3><p>Lets take a barrista making coffee. The tasks to do are:</p><ol><li>Grind the required coffee beans (no preceding tasks)</li><li>Heat some water (no preceding tasks)</li><li>Brew an espresso using the ground coffee and the heated water (depends on 1 &amp; 2)</li><li>Froth some milk (no preceding tasks)</li><li>Combine the froth milk and the espresso (depends on 3,4)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fr-NJMmbXHN0UuXuNSP60g.png" /><figcaption>Barrista Scenario</figcaption></figure><h3>Code Sample</h3><pre>package com.demo.myexamples.service;<br><br>import java.util.concurrent.CompletableFuture;<br>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;<br>import java.util.function.BiFunction;<br>import java.util.function.Supplier;<br><br>public class Barrista<br>{<br><br>    // number of threads used in executor<br>    static final int NOTHREADS = 3;<br><br>    // time of each task<br>    static final int HEATWATER = 1000;<br>    static final int GRINDBEANS = 1000;<br>    static final int FROTHMILK = 1000;<br>    static final int BREWING = 1000;<br>    static final int COMBINE = 1000;<br><br>    // method to simulate work (pause current thread without throwing checked exception)<br>    public static void pause(long t)<br>    {<br>        try<br>        {<br>            Thread.sleep(t);<br>        }<br>        catch(Exception e)<br>        {<br>            throw new Error(e.toString());<br>        }<br>    }<br><br>    // task to heat some water<br>    static class HeatWater implements Supplier&lt;String&gt;<br>    {<br>        @Override<br>        public String get()<br>        {<br>            System.out.println(&quot;Heating Water&quot;);<br>            pause(HEATWATER);<br>            return &quot;hot water&quot;;<br>        }<br>    }<br><br>    // task to grind some beans<br>    static class GrindBeans implements Supplier&lt;String&gt;<br>    {<br>        @Override<br>        public String get()<br>        {<br>            System.out.println(&quot;Grinding Beans&quot;);<br>            pause(GRINDBEANS);<br>            return &quot;grinded beans&quot;;<br>        }<br>    }<br><br>    // task to froth some milk<br>    static class FrothMilk implements Supplier&lt;String&gt;<br>    {<br>        @Override<br>        public String get()<br>        {<br>            System.out.println(&quot;Frothing some milk&quot;);<br>            pause(FROTHMILK);<br>            return &quot;some milk&quot;;<br>        }<br>    }<br><br>    // task to brew some coffee<br>    static class Brew implements BiFunction&lt;String,String, String&gt;<br>    {<br>        @Override<br>        public String apply(String groundBeans, String heatedWater)<br>        {<br>            System.out.println(&quot;Brewing coffee with &quot; + groundBeans + &quot; and &quot; + heatedWater);<br>            pause(BREWING);<br>            return &quot;brewed coffee&quot;;<br>        }<br>    }<br><br>    // task to combine brewed coffee and milk<br>    static class Combine implements BiFunction&lt;String,String, String&gt;<br>    {<br>        @Override<br>        public String apply(String frothedMilk, String brewedCoffee)<br>        {<br>            System.out.println(&quot;Combining &quot; + frothedMilk + &quot; &quot;+ brewedCoffee);<br>            pause(COMBINE);<br>            return &quot;Final Coffee&quot;;<br>        }<br>    }<br><br>    public static void main(String[] args)<br>    {<br>        ExecutorService executor = Executors.newFixedThreadPool(NOTHREADS);<br><br>        long startTime = System.currentTimeMillis();<br><br>        try<br>        {<br>            // create all the tasks and let the executor handle the execution order<br>            CompletableFuture&lt;String&gt; frothMilk =       CompletableFuture.supplyAsync(new FrothMilk(), executor);<br>            CompletableFuture&lt;String&gt; heatWaterFuture = CompletableFuture.supplyAsync(new HeatWater(), executor);<br>            CompletableFuture&lt;String&gt; grindBeans =      CompletableFuture.supplyAsync(new GrindBeans(), executor);<br><br>            CompletableFuture&lt;String&gt; brew = heatWaterFuture.thenCombine(grindBeans, new Brew());<br>            CompletableFuture&lt;String&gt; coffee =          brew.thenCombine(frothMilk,  new Combine());<br><br>            // final coffee<br>            System.out.println(&quot;Here is the coffee:&quot; + coffee.get());<br><br>            // analyzing times:<br>            System.out.println(&quot;\n\n&quot;);<br>            System.out.println(&quot;Time taken using multi-threaded:\t\t&quot; + (System.currentTimeMillis() - startTime)/1000.0);<br><br>            // compute the longest possible time:<br>            long longestTime = HEATWATER + GRINDBEANS + FROTHMILK + BREWING + COMBINE;<br>            System.out.println(&quot;Time taken using single-threaded thread:\t&quot; + longestTime/1000.0);<br>        }<br>        catch (Exception e)<br>        {<br>            e.printStackTrace();<br>        }<br>        finally<br>        {<br>            executor.shutdown();<br>        }<br><br>    }<br>}</pre><h3>Code output</h3><pre>Frothing some milk<br>Heating Water<br>Grinding Beans<br>Brewing coffee with hot water and grinded beans<br>Combining brewed coffee some milk<br>Here is the coffee:Final Coffee<br><br><br>Time taken using multi-threaded:  3.027<br>Time taken using single-threaded thread: 5.0</pre><p>In our case, Total time taken by all five tasks called in single-threaded mode is 1000 + 1000 + 1000 + 1000 + 1000 = <strong>5000ms</strong>. In reality if you execute and wait for them to complete, then you have to incur the cost of waiting for the task that takes longest time. However, when we execute the same in mutli-threaded mode the total time taken is <strong>3027ms</strong>.</p><h3>Conclusion</h3><p>In real use cases it makes sense to make multiple calls concurrently or rather it sometimes becomes an unavoidable situation where you need to make some calls to multiple services at the same time. Making concurrent calls are good ideas because it will reduce the time required to complete the whole operation rather than spending the sum of time spent over the span of all calls.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd559b85ceec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/executing-dependent-and-independent-tasks-in-parallel-using-java-bd559b85ceec">Executing Dependent and Independent tasks in parallel using Java</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot 2 + JUnit 5 + Mockito]]></title>
            <link>https://medium.com/javarevisited/spring-boot-2-junit-5-mockito-d8e2e5c8a90d?source=rss-5365dede21aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8e2e5c8a90d</guid>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[mock-mvc]]></category>
            <dc:creator><![CDATA[Thameem Ansari]]></dc:creator>
            <pubDate>Wed, 02 Nov 2022 07:55:58 GMT</pubDate>
            <atom:updated>2022-11-22T15:02:03.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*_EbnYDko_m74_LIjtmYX1Q.png" /><figcaption>Spring Boot 2 + JUnit 5 + Mockito</figcaption></figure><h3>Introduction</h3><p>In this article, we will learn how to create a JUnit 5 test classes with Mockito in Spring Boot application. JUnit is one of the most popular testing frameworks for Java applications. JUnit 5 supports all modern features from Java 8 and allows using many different approaches and styles in testing.</p><p>We are going to use the below three approaches in this article.</p><ul><li>Test using MockMvc to perform REST calls.</li><li>Spring boot test that makes use of TestRestTemplate to call REST API.</li><li>Mockito unit test for HelloController class.</li></ul><h3>Maven dependencies</h3><p>Fortunately, the spring-boot-starter-test dependency from version 2.2.0 already comes with Junit 5 and contains also Hamcrest, and Mockito libraries for testing. That&#39;s good news because we don&#39;t need to add a lot of dependency into our final pom.xml file.</p><p>The JUnit 5 is composed of two components, such as:</p><ul><li>JUnit Jupiter — for writing tests and extensions in JUnit 5,</li><li>JUnit Vintage — provides a TestEngine for running JUnit 3 and JUnit 4 based tests on the platform.</li></ul><p>For our case, we don’t need JUnit 3 and JUnit 4 support that’s why we will exclude this dependency.</p><p>The final pom.xml has the following structure:</p><pre><br>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>         xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;<br>    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br><br>    &lt;groupId&gt;com.demo.springboot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot2-junit5-mockito&lt;/artifactId&gt;<br>    &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;<br><br>    &lt;!-- Inherit defaults from Spring Boot --&gt;<br>    &lt;parent&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;<br>        &lt;version&gt;2.4.1&lt;/version&gt;<br>    &lt;/parent&gt;<br><br>    &lt;properties&gt;<br>        &lt;java.version&gt;1.8&lt;/java.version&gt;<br>    &lt;/properties&gt;<br><br>    <strong>&lt;!-- Add typical dependencies for a web application --&gt;</strong><br>    &lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>            &lt;exclusions&gt;<br>                &lt;exclusion&gt;<br>                    &lt;groupId&gt;org.junit.vintage&lt;/groupId&gt;<br>                    &lt;artifactId&gt;junit-vintage-engine&lt;/artifactId&gt;<br>                &lt;/exclusion&gt;<br>            &lt;/exclusions&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br><br>    <strong>&lt;!-- Package as an executable jar --&gt;</strong><br>    &lt;build&gt;<br>        &lt;plugins&gt;<br>            &lt;plugin&gt;<br>                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>                &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br>            &lt;/plugin&gt;<br>        &lt;/plugins&gt;<br>    &lt;/build&gt;<br>&lt;/project&gt;</pre><p>We have two main dependencies:</p><ul><li>spring-boot-starter-web - web container is used for creating Spring REST API.</li><li>spring-boot-starter-test - main dependencies for unit and integration testing.</li></ul><p>The spring-boot-maven-plugin is used to create an executable jar with the Spring Boot application.</p><h3>Project structure</h3><p>The testing project has the following structure:</p><pre><br>├── pom.xml<br>├── src<br>│   ├── main<br>│   │   ├── java<br>│   │   │   └── com<br>│   │   │       └── demo<br>│   │   │           └── springboot<br>│   │   │               ├── Application.java<br>│   │   │               ├── controller<br>│   │   │               │   └── HelloController.java<br>│   │   │               └── service<br>│   │   │                   └── HelloService.java<br>│   └── test<br>│       └── java<br>│           └── com<br>│               └── demo<br>│                   └── springboot<br>│                       └── controller<br>│                           ├── HelloControllerMockitoTest.java<br>│                           ├── HelloControllerMockMvcTest.java<br>│                           └── HelloControllerRestTemplTest.java</pre><p>We use the following classes:</p><ul><li>Application - The main Spring Boot application class used for starting web container.</li><li>HelloController - Spring Rest Controller for testing purposes.</li><li>HelloService - Spring Service used to check how autowire works in tests.</li><li>HelloControllerMockitoTest - test for HelloController using Mockito,</li><li>HelloControllerMockMvcTest - test for HelloController using MockMvc,</li><li>HelloControllerRestTemplTest - test for HelloController using TestRestTemplate.</li></ul><h3>Spring REST API for JUnit 5 Testing</h3><h4>HelloController</h4><p>Spring REST controller called HelloController will be used as our main class for testing. It uses @Autowired annotation to inject HelloService.</p><p>@GetMapping annotation marks greeting() method that from now will be used to handle all GET requests to the root path /.</p><pre>package com.demo.springboot.controller;<br><br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.ResponseBody;<br>import org.springframework.web.bind.annotation.RestController;<br><br>import com.demo.springboot.service.HelloService;<br><br>@RestController<br>public class HelloController {<br><br>    private final HelloService helloService;<br><br>    @Autowired<br>    public HelloController(HelloService helloService) {<br>        this.helloService = helloService;<br>    }<br><br>    @GetMapping(&quot;/&quot;)<br>    public @ResponseBody String greeting() {<br>        return helloService.getWelcomeMessage();<br>    }<br>}</pre><h4>Hello Service</h4><p>The HelloService is a simple Spring service with method getWelcomeMessage() that will be run in REST controller class.The main purpose of this class is to show how we can mock classes using Mockito in JUnit tests.</p><pre><br>package com.demo.springboot.service;<br><br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class HelloService {<br><br>    public String getWelcomeMessage() {<br>        return &quot;Hello World!&quot;;<br>    }<br>}</pre><h4>Main @SpringBootApplication class</h4><p>Main Spring Boot application class is marked with @SpringBootApplication annotation and contains a single public static void main(String[] args) method that starts web container - Tomcat by default.</p><pre><br>package com.demo.springboot;<br><br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br><br>@SpringBootApplication<br>public class Application {<br><br>    public static void main(String[] args) {<br>        SpringApplication.run(Application.class, args);<br>    }<br>}</pre><h3>Approach 1: Test using MockMvc to perform REST calls</h3><p>Let’s start our testing adventure with a test class that uses MockMvc. In this approach, the Spring Boot application server will not be started but the code will be called exactly in the same way as if it handling an HTTP request.</p><p>The test class looks as follows:</p><pre>package com.demo.springboot.controller;<br><br>import static org.hamcrest.Matchers.containsString;<br>import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;<br>import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;<br>import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;<br>import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;<br><br>import org.junit.jupiter.api.Test;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;<br>import org.springframework.boot.test.context.SpringBootTest;<br>import org.springframework.test.web.servlet.MockMvc;<br><br>@SpringBootTest<br>@AutoConfigureMockMvc<br>public class HelloControllerMockMvcTest {<br><br>    @Autowired<br>    private MockMvc mockMvc;<br><br>    @Test<br>    public void shouldReturnDefaultMessage() throws Exception {<br>        this.mockMvc.perform(get(&quot;/&quot;))<br>                    .andDo(print())<br>                    .andExpect(status().isOk())<br>                    .andExpect(content().string(containsString(&quot;Hello World!&quot;)));<br>    }<br>}</pre><p>We used the MockMvc class and @AutoConfigureMockMvc that will configure it and inject it into the tested class. The MockMvc class is used to perform API calls, but instead of doing HTTP requests, Spring will test only the implementation that handle them in HelloController.</p><h3>Approach 2: Spring boot test that makes use of TestRestTemplate to call REST API</h3><p>In the next approach, we will use the @SpringBootTest annotation that is used to start the Spring application context.</p><pre><br>package com.demo.springboot.controller;<br><br>import static org.assertj.core.api.Assertions.assertThat;<br><br>import org.junit.jupiter.api.BeforeEach;<br>import org.junit.jupiter.api.Test;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.boot.test.context.SpringBootTest;<br>import org.springframework.boot.test.web.client.TestRestTemplate;<br>import org.springframework.boot.web.server.LocalServerPort;<br><br>@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)<br>public class HelloControllerRestTemplTest {<br><br>    @LocalServerPort<br>    private int port;<br><br>    private String url;<br><br>    @Autowired<br>    private TestRestTemplate restTemplate;<br><br>    @BeforeEach<br>    public void setUp() {<br>        url = String.format(&quot;http://localhost:%d/&quot;, port);<br>    }<br><br>    @Test<br>    public void greetingShouldReturnDefaultMessage() {<br>        assertThat(this.restTemplate.getForObject(url, String.class)).contains(&quot;Hello World!&quot;);<br>    }<br>}</pre><p>In this approach, we can use @Autowired annotation just like in runtime applications. Spring will interpret them and do the necessary injections. In @SpringBootTest tests real Spring Boot application server is being started.</p><p>In the test we used:</p><ul><li>webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT - to start the server with a random port in order to avoid any port conflicts,</li><li>@LocalServerPort - this annotation tells Spring to inject a random port to the specific field,</li><li>TestRestTemplate - RestTemplate for tests used to make a real HTTP requests.</li></ul><h3>Approach 3: Mockito unit test for HelloController class</h3><p>In case we want to mock some objects while testing the HelloController class we could use the Mockito framework in a unit test. In this approach, we are simply testing class with JUnit and Mockito without making any HTTP calls. It is possible because our REST controller is an ordinary class like any other.</p><pre><br>package com.demo.springboot.controller;<br><br>import static org.assertj.core.api.Assertions.assertThat;<br>import static org.mockito.Mockito.when;<br><br>import org.junit.jupiter.api.BeforeEach;<br>import org.junit.jupiter.api.Test;<br>import org.junit.jupiter.api.extension.ExtendWith;<br>import org.mockito.InjectMocks;<br>import org.mockito.Mock;<br>import org.mockito.junit.jupiter.MockitoExtension;<br><br>import com.demo.springboot.service.HelloService;<br><br>@ExtendWith(MockitoExtension.class)<br>public class HelloControllerMockitoTest {<br><br>    @Mock<br>    private HelloService helloService;<br><br>    @InjectMocks<br>    private HelloController helloController;<br><br>    @BeforeEach<br>    void setMockOutput() {<br>        when(helloService.getWelcomeMessage()).thenReturn(&quot;Hello Mockito Test&quot;);<br>    }<br><br>    @Test<br>    public void shouldReturnDefaultMessage() {<br>        String response = helloController.greeting();<br>        assertThat(response).isEqualTo(&quot;Hello Mockito Test&quot;);<br>    }<br>}</pre><p>To start using Mockito in JUnit tests we need to annotate a class with @ExtendWith(MockitoExtension.class). In our testing class, we mock HelloService to change the response of getWelcomeMessage() method. The @InjectMocks annotation tells Mockito to inject all mock objects into the test class.</p><h3>Conclusion</h3><p>In this article, we presented several approaches to test the Spring REST controller using JUnit 5 and the Mockito library. It is up to us if we want to start the real Spring Boot server using @SpringBootTest annotation or simply run the implementation that is called on HTTP requests using MockMvc. Mockito could be also used to test the REST controller class if there is a need to mock or spy dependencies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8e2e5c8a90d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/spring-boot-2-junit-5-mockito-d8e2e5c8a90d">Spring Boot 2 + JUnit 5 + Mockito</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use of BigDecimal instead of double in Java for Financial systems]]></title>
            <link>https://medium.com/@reachansari/use-of-bigdecimal-instead-double-in-java-for-financial-systems-591440bdd5f4?source=rss-5365dede21aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/591440bdd5f4</guid>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Thameem Ansari]]></dc:creator>
            <pubDate>Sun, 20 Mar 2022 08:31:59 GMT</pubDate>
            <atom:updated>2022-03-22T07:21:43.172Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*0Fo095w2E28uSNZyx6igBw.png" /></figure><h3>Introduction</h3><p>Most of us use double(or float) as primary floating point data type in java. In this article we will see how to avoid the errors which can arise during calculations in the decimal part of a number.</p><h3>Samples with Explanations</h3><p>Let’s have a look at the few samples. It will be a simple Java class which prints the sum of two numbers in the console.</p><p><strong>ExampleOne</strong></p><pre>import java.math.BigDecimal;</pre><pre>public class <strong>ExampleOne </strong>{<br>  public static void main(String[] args) {<br>      double a =1.1;<br>      double b =1.2;<br>      double c=a+b;<strong>//Expected output : 2.3</strong><br>      System.out.println(&quot;Actual output:&quot;+c);<br>    }<br>}</pre><pre><strong># OUTPUT<br></strong>Actual output: 2.3</pre><p>Well, we got the result as we expected. But will we get the correct answer every time with <strong><em>double</em></strong>? Let’s change the value of <strong><em>a</em></strong> and <strong><em>b.</em></strong></p><p><strong>ExampleTwo</strong></p><pre>import java.math.BigDecimal;</pre><pre>public class <strong>ExampleTwo </strong>{<br>public static void main(String[] args) {<br>        double a =2.1;<br>        double b =2.2;<br>        double c=a+b; <strong>//Expected output : 4.3</strong><br>        System.out.println(&quot;Actual output:&quot;+c);<br>    }<br>}</pre><pre><strong># OUTPUT<br></strong>Actual output:4.300000000000001</pre><p>This time we got an unexpected output with additional digits in decimal part. It is close to the expected answer but not accurate. You also might have come across similar situations before.</p><p>Even though the difference between expected output and actual output is very small, it will make a significant impact in financial and business systems.</p><h3><strong>BigDecimal in Action</strong></h3><p>Currently, <strong>BigDecimal class</strong> is the best solution to avoid the floating point errors during calculations. There are few ways we can initialize a BigDecimal Object like it is shown in <strong>BigDecimal<em>Example</em> </strong>class below.</p><ol><li>Using double constructor.</li><li>Using valueOf(double) static method in BigDecimal class.</li><li>Using String constructor(recommended)</li></ol><pre>import java.math.BigDecimal;</pre><pre>public class BigDecimalExample{<br>    public static void main(String[] args) {</pre><pre>    <strong>//1. Using double constructor</strong><br>        BigDecimal b1=new BigDecimal(1.1);</pre><pre>    <strong>//2. Using valueOf(double) static method in BigDecimal class.</strong><br>        BigDecimal b2=BigDecimal.valueOf(1.1);</pre><pre>    <strong>//3. Using String Constructor.</strong><br>        BigDecimal b3=new BigDecimal(&quot;1.1&quot;);<br>    }<br>}</pre><p>We should avoid using 1st and 2nd way as much as possible. Let’s see why.</p><p><strong>Using Big Decimal Double Constructor:</strong></p><pre>import java.math.BigDecimal;</pre><pre>public class <strong>BigDecimalDoubleConstructor </strong>{<br>     public static void main(String[] args) {<br>        BigDecimal b1=new BigDecimal(2.1);<br>        BigDecimal b2=new BigDecimal(2.2);<br>        BigDecimal b3=b1.add(b2); <strong>//Expected output : 4.3</strong><br>        System.out.println(&quot;Actual output:&quot;+b3);</pre><pre>    }<br>}</pre><pre><strong># OUTPUT</strong><br>Actual output:4.300000000000000266453525910037569701671600341796875</pre><p>This time also we have <strong>received an unexpected output</strong>. Let’s try with <em>valueOf(double)</em> method.</p><p><strong>Using Big Decimal ValueOf:</strong></p><pre>import java.math.BigDecimal;</pre><pre>public class <strong>BigDecimalValueOf </strong>{<br>    public static void main(String[] args) {</pre><pre>       <strong><em>//Sample1</em></strong><br>        BigDecimal b1=BigDecimal.valueOf(2.1);<br>        BigDecimal b2=BigDecimal.valueOf(2.2);<br>        BigDecimal b3=b1.add(b2);<strong>//Expected output : 4.3</strong> <br>        System.out.println(&quot;Actual output Sample1: &quot;+b3);</pre><pre>       <em>//Sample2</em><br>        BigDecimal b4=BigDecimal.valueOf(1.123456789123456789);<strong>//Expected output: 1.123456789123456789</strong><br>        System.out.println(&quot;Actual output Sample2: &quot;+b4);<br>    }<br>}</pre><pre><strong># OUTPUT</strong><br>Actual output Sample1: 4.3<br>Actual output Sample2: 1.1234567891234568</pre><p>As we can see we got the correct output for <strong><em>Sample1</em></strong> which is <strong><em>4.3. </em></strong>But what about <strong>Sample2</strong> ?<strong> we have lost 2 digits!</strong>(from the decimal part).</p><p><strong>Using Big Decimal String constructor:</strong></p><pre>import java.math.BigDecimal;</pre><pre>public class <strong>BigDecimalStringConstructor</strong>{<br>     public static void main(String[] args) {</pre><pre>     <strong><em>//Sample3<br></em></strong>     BigDecimal b1=new BigDecimal(&quot;2.1&quot;);<br>     BigDecimal b2=new BigDecimal(&quot;2.2&quot;);<br>     BigDecimal b3=b1.add(b2);<strong>//Expected output :4.3</strong><br>    System.out.println(&quot;Actual output Sample3: &quot;+b3);</pre><pre><strong><em>   //Sample4<br></em></strong>    BigDecimal b5=new BigDecimal(&quot;1.123456789123456789&quot;);<strong>//Expected output :1.123456789123456789<br>    </strong>System.out.println(&quot;Actual output Sample4: &quot;+b5);<br>   }<br>}</pre><pre><strong># OUTPUT</strong><br>Actual output Sample3: 4.3<br>Actual output Sample4: 1.123456789123456789</pre><p>This time we got <strong>correct outputs for both Sample3 &amp; Sample4</strong>. Hence we should always try to use <strong>String constructor of BigDecimal class </strong>as much as possible where each digit of decimal part are important.</p><p>As it is shown in <strong>BigDecimalStringConstructor </strong>we can use BigDecimal class to overcome the floating point errors. Like double has few disadvantages, BigDecimal class main disadvantage is it slower than double.</p><p>So if we have a system where <strong>low latency</strong> is crucial than the decimal part of a number, we should go for <em>double</em>.</p><p>But in <strong>financial or any other systems where each digit of decimal part are important, BigDecimal</strong> should be chosen over double/float.</p><p>Happy coding..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=591440bdd5f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Memory Management]]></title>
            <link>https://medium.com/@reachansari/java-memory-management-1f68b60ad569?source=rss-5365dede21aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f68b60ad569</guid>
            <category><![CDATA[heap-vs-stack]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Thameem Ansari]]></dc:creator>
            <pubDate>Sun, 20 Mar 2022 04:47:17 GMT</pubDate>
            <atom:updated>2022-03-20T08:32:58.860Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*2IVlo7iy_AUddt1GE8jJUQ.png" /><figcaption>Java Memory Management</figcaption></figure><h3>Introduction</h3><p>In this article we will be discussing about Heap and Stack memory in java and what is the life of Objects in our application with examples.</p><p>To run an application in an optimal way, JVM divides memory into stack and heap memory. Whenever we declare new variables and objects, call a new method, declare a <em>String,</em> or perform similar operations, JVM designates memory to these operations from either Stack or Heap Memory.</p><h3>Heap Memory</h3><p>There are two parts inside the Heap area called <strong>Young</strong> <strong>Generation </strong>and <strong>Old Generation</strong>. There are 3 parts inside the Young generation area called Eden and two survivor( Survivor1, Survivor2 ) memories.</p><p>In the heap area <strong>objects, JRE Classes </strong>will be stored. The Garbage Collector will run only on Heap Memory. ( GC will destroy objects which don’t has references and frees memories )</p><p><strong>Memory Pool</strong> — This stays in the Heap area. In the memory pool <strong>immutable objects, </strong>the <strong>String pool</strong> will be stored.</p><ol><li>When Eden memory completes( full ), Minor Garbage Collector( Minor GC ) will perform and Minor GC will move old memory parts(variables) to Survivor memories.</li><li>Then after some time, the Young generation may be filled, Then Old objects will be moved to the Old Generation.</li><li>Then Old Generation will be filled and there is no space available in the Heap area. Then Major Garbage Collector( Major GC ) will be performed. This Major GC will take some longer time than Minor GC.</li></ol><p>Minor GC always performs in the Young Generation and the major GC always performs in the Old Generation.</p><h3>Stack Memory</h3><p>This is used to execute the threads. This contains methods-specific values l<strong>ocal variables </strong>,<strong> object references and method blocks</strong>. This uses the Last In First Out( LIFO ) way to free the memory(which means the newest/latest memory locations will be destroyed).</p><ul><li><strong>Local variables</strong> — local variables are variables that define in a method, including method parameters. Java Stack memory only contains the byte, short, char, int, long, float and double(primitives) local variables. If we create an object ( Ex: String ) as a local variable that object is stored in the Heap memory area, but the object reference stays in the Stack memory area.</li><li><strong>Object Reference</strong> — variable names which point to objects in the Heap Memory. In the below example “my” is an object reference.</li></ul><pre>MyClass my = new MyClass();</pre><ul><li><strong>Method Block</strong>— This is just a name for methods when talking about Java Memory Management. In the below example “myMethod” will be a method block. When after executing a method that memory location will be freed and may be located for another method block.</li></ul><pre>public void myMethod() {<br>  int i = 0;<br>}</pre><h3>Explanation with an example</h3><pre>public class Test {<br>  int a, b;<br>}</pre><pre>public class MyClass{<br>  Test t1 = new Test();</pre><pre>  public int testMethod(int x){<br>    int i = x + 3;<br>    String str= &quot;ABC&quot;;</pre><pre>    //some stuff<br>  }<br>}</pre><ul><li><strong>t1 ( reference )</strong> — Stack memory</li><li><strong>Test object ( new Test() )</strong> — Heap memory</li><li><strong>int a, b</strong> — Heap memory ( inside the object. Because these are bound to the object )</li><li><strong>testMethod </strong>— Stack Memory ( this is also a reference — for a method )</li><li><strong>int x</strong> — Stack Memory ( this is a method parameter hence it is a local variable )</li><li><strong>int i </strong>— Stack Memory ( local variable. This is not bound to the object )</li><li><strong>String str </strong>— A string is created and it goes in the String Pool in the heap space and a reference is created in the testMethod() stack space for it.</li></ul><h3>Difference between Stack memory and Heap memory</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*rW7_bnYIEd40j6j7QVzZVg.png" /></figure><p>Based on the above explanations, we can easily conclude the following differences between Heap and Stack memory.</p><ol><li>Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.</li><li>Stack memory is short-lived whereas heap memory lives from the start till the end of application execution.</li><li>We can use -Xms and -Xmx JVM option to define the startup size and maximum size of heap memory. We can use -Xss to define the stack memory size.</li><li>When stack memory is full, Java runtime throws java.lang.StackOverFlowError whereas if heap memory is full, it throws java.lang.OutOfMemoryError: Java Heap Space error.</li><li>Stack memory size is very less when compared to Heap memory. Because of simplicity in memory allocation (LIFO), stack memory is very fast when compared to heap memory.</li></ol><h3>How long does an object alive?</h3><p>The Object life is dependent on references referring to it, if the references are dead then Object will die too.</p><h3>What is a task for garbage collection (GC)?</h3><p>This is the task of garbage collection (GC) in the Java virtual machine (JVM) to automatically determine what memory is no longer being used by a Java application and to recycle this memory for other uses.</p><p>That’s all for this topic Memory Management in Java with examples.</p><p>Happy coding..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f68b60ad569" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Rolling Updates & Rollbacks — Chapter 11]]></title>
            <link>https://medium.com/@reachansari/kubernetes-rolling-updates-rollbacks-chapter-11-3f162b3f415e?source=rss-5365dede21aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f162b3f415e</guid>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Thameem Ansari]]></dc:creator>
            <pubDate>Wed, 16 Mar 2022 14:08:31 GMT</pubDate>
            <atom:updated>2022-03-16T14:10:31.766Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kubernetes Rolling Updates &amp; Rollbacks — Chapter 12</h3><p>Rolling updates provide a mechanism for updating containers in a cluster without downtime. This powerful Kubernetes feature allows you to update containers while maintaining high availability.</p><p>To see this in action we’ll create a Deployment consisting of 3 <strong>nginx Pods </strong>using the definition below. Note that the container image we’re going to run is <strong>library/nginx:1.20.0</strong>.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: demo-rolling-update-deployment<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: nginx<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx<br>    spec:<br>      containers:<br>        - name: nginx<br>          image: library/nginx:1.20.0<br>          imagePullPolicy: IfNotPresent</pre><p>Run <strong>kubectl apply -f demo-rolling-update-deployment.yaml</strong> to create the Deployment. A quick listing will show 3 Pods running as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*LCjy8hTz1kEG-1jhyxWVlw.png" /></figure><h3>Rolling Update</h3><p>Now we’re going to use the kubectl set image command to perform a rolling update that will replace the 3 Pods running <strong>library/nginx:1.20.0</strong>, with 3 new Pods running <strong>library/nginx:1.21.0</strong>. Kubernetes will perform these updates incrementally to ensure service availability is maintained.</p><p>The full command is</p><p><strong>kubectl set image deployment/demo-rolling-update-deployment nginx=nginx:1.21.0 — record</strong></p><ul><li><strong>deployment/demo-rolling-update-deployment</strong> is the name of the Deployment we want to update.</li><li><strong>nginx=nginx:1.21.0</strong> is the name of the container followed by the new image we want to run</li><li><strong>— record</strong> tells Kubernetes to record the update information so that it can be used to roll back the update later, if needs be</li></ul><p>After running the above command you can run <strong>kubectl get pods -w</strong> to tail the Pod activity in the default namespace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*glpGFhnaUS8qsynwmdk5Wg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*r1LgXs5NoiGIaLsZ3vR2nA.png" /></figure><p>The screenshot above shows new Pods being stood up and the existing Pods being terminated. Note that existing Pods aren’t terminated until a replacement is running.</p><h3>Rollbacks</h3><p>Rollbacks allow you to revert changes by rolling back to a previous cluster state.</p><ul><li>The rollout history command displays a list of previous updates. USE <strong>kubectl rollout history deployment/demo-rolling-update-deployment</strong>.</li><li>To see detail for a specific deployment use the — revision flag as follows. <strong>kubectl rollout history deployment/demo-rolling-update-deployment — revision 2</strong> displays detail associated with revision 2.</li><li>To undo the last revision use the kubectl rollout undo command. Use, <strong>kubectl rollout undo deployment/demo-rolling-update-deployment</strong> . If you want to roll back to a specific revision you can use the <strong>— to-revision=&lt;revision_number&gt;</strong> , for example, <strong>kubectl rollout undo deployment/demo-rolling-update-deployment — to-revision=2</strong></li></ul><h3>Rolling Update Strategy</h3><p>Kubernetes allows you to control the minimum and maximum number of pods that will run as part of a rolling update or roll back, using <strong>strategy.rollingUpdate</strong>. The <strong>maxSurge </strong>attribute indicates the maximum number of Pods that should be created. In the <strong>Deployment </strong>below, <strong>maxSurge </strong>is set at 50% which means that Kubernetes will not create more than 50% additional Pods as part of a rolling update. The <strong>Deployment </strong>specifies 4 Pod replicas by default, so no more than 6 Pods will ever run as part of a rolling update.</p><p>Similarly <strong>maxUnavailable </strong>tells Kubernetes the maximum number of Pods that can be unavailable during a rolling update. In the <strong>Deployment </strong>below <strong>maxUnavailable </strong>is set at 50% which means that Kubernetes will not allow the maximum unavailable Pods to fall below 50% of the specified number of replicas. Given that the <strong>Deployment </strong>specifies 4 Pod replicas, no more than 2 Pods will ever be unavailable as part of a rolling update.</p><p>Note that both <strong>maxSurge </strong>and <strong>maxUnavailable </strong>can be specified as a percentage of the number of Pod replicas, or as an absolute value.</p><pre><br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: demo-rolling-update-deployment-strategy<br>spec:<br>  replicas: 4<br>  selector:<br>    matchLabels:<br>      app: nginx<br>  strategy:<br>    rollingUpdate:<br>      maxSurge: 50%<br>      maxUnavailable: 50%<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx<br>    spec:<br>      containers:<br>        - name: nginx<br>          image: library/nginx:1.20.0<br>          imagePullPolicy: IfNotPresent</pre><p>The sample code for this post is available <a href="https://github.com/reachansari/kubernetes-examples/tree/main/Rolling%20Updates%20-%20Chapter%2012">here</a>.</p><p>Happy coding..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f162b3f415e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Deployments — Chapter 11]]></title>
            <link>https://medium.com/@reachansari/kubernetes-deployments-chapter-11-147b5a989f84?source=rss-5365dede21aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/147b5a989f84</guid>
            <category><![CDATA[kubenetes]]></category>
            <dc:creator><![CDATA[Thameem Ansari]]></dc:creator>
            <pubDate>Sun, 13 Mar 2022 03:59:31 GMT</pubDate>
            <atom:updated>2022-03-13T03:59:31.695Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kubernetes Deployments — Chapter 11</h3><h3>Kubernetes Deployments</h3><p>A Kubernetes Deployment object provides a means of managing a group of Pod instances, known as replicas. The Deployment tells Kubernetes the type of Pod you want to run and the number of Pod instances. This is known as the desired state.</p><p>Kubernetes will actively monitor the number of active Pod replicas and take action to ensure it is the same as the desired state. For example, if your Deployment specifies that there should be three Pod replicas for a microservice, and one of those Pods die, Kubernetes will take corrective action and spin up a new Pod to replace the one that failed.</p><h3>Defining a Deployment</h3><p>The Deployment below creates 3 nginx Pod replicas.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx-deployment<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: nginx<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx<br>    spec:<br>      containers:<br>        - name: nginx<br>          image: nginx<br>          imagePullPolicy: Always</pre><p><strong>spec.replicas </strong>= specifies the number of Pods to create.<br><strong>selector.matchLabels=</strong> tells Kubernetes that this <strong>Deployment </strong>will manage <strong>Pods </strong>with the label <strong>app: nginx.</strong><br><strong>template= </strong>provides a template for the Pod instances that this Deployment will create.<br><strong>template.metadata.labels=</strong> defines the label that will match this Pod definition to the parent <strong>Deployment</strong>.<br><strong>spec.containers=</strong> defines the containers that will run in the Pod instances that are created.</p><p>After creating this <strong>Deployment </strong>object we should see 3 Pods created as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*Xw8tqhhxQX0ZEHPJMPpf4A.png" /></figure><h3>Updating a Deployment</h3><p>We can update a Deployment to change the state of our Pod replicas. For example, we can increase the number of replicas from 3 to 5 as follows.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx-deployment<br>spec:<br>  replicas: 5<br>  selector:<br>    matchLabels:<br>      app: nginx<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx<br>    spec:<br>      containers:<br>        - name: nginx<br>          image: nginx<br>          imagePullPolicy: Always</pre><p>Remember that we currently have 3 Pod replicas running in the cluster. When we apply this update, Kubernetes will see the updated replicas: 5 and take corrective action to create an additional 2 Pods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*8AV_9SbFyvSWxNDXaEim4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*GYOEkBmErgQx3RHVwukP9w.png" /></figure><p>The sample code for this post is available <a href="https://github.com/reachansari/kubernetes-examples/tree/main/Deployments%20-%20Chapter%2011">here</a>.</p><p>Happy coding..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=147b5a989f84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Labels, Selectors & Annotations — Chapter 10]]></title>
            <link>https://medium.com/@reachansari/kubernetes-labels-selectors-annotations-chapter-10-1b6c74adadb9?source=rss-5365dede21aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b6c74adadb9</guid>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Thameem Ansari]]></dc:creator>
            <pubDate>Mon, 07 Mar 2022 16:03:40 GMT</pubDate>
            <atom:updated>2022-03-07T16:03:40.196Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kubernetes Labels, Selectors &amp; Annotations — Chapter 10</h3><h3>Labels</h3><p>Labels are key/value pairs that are used to add metadata to Kubernetes objects. They can be used to select and group subsets of objects in the cluster. Labels are added to an object in the <strong>metadata.labels</strong> section of the object descriptor as shown in the two Pod definitions below.</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br> name: demo-dev-pod<br> labels:<br>   app: my-service<br>   environment: dev<br>spec:<br>  containers:<br>    - name: nginx-container<br>      image: nginx<br>      imagePullPolicy: Always</pre><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br> name: demo-prod-pod<br> labels:<br>   app: my-service<br>   environment: prod<br>spec:<br>  containers:<br>    - name: nginx-container<br>      image: nginx<br>      imagePullPolicy: Always</pre><p>After creating the above Pods run <strong>kubectl get pods — show-labels</strong> to see the labels associated with each.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*ujAt6trYRD82kk6riTt4Ow.png" /></figure><h3>Selectors</h3><p>Selectors are used to identify and select a set of objects based on their labels.</p><h4>Equality &amp; Inequality Selectors</h4><p>Running <strong>kubectl get pods -l environment=dev</strong> will output Pods where label environment is dev.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*tb0Bn8VL1_JyjxpwmLzKvg.png" /></figure><p>You can also use negation to list Pods not matching a selector. For example <strong>kubectl get pods -l environment!=dev</strong> will output Pods where label environment is not dev.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*PtseTMr15z5WtjBdSzYIuw.png" /></figure><h4>Chained Selectors</h4><p>Chained selectors allow you to aggregate the results of multiple selectors using a comma separated list like this <strong>kubectl get pods -l app=my-service,environment=dev — show-labels.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M6DabKTJutSNZHm5zwbvPg.png" /></figure><h3>Annotations</h3><p>Annotations are similar to selectors in that they allow you to associate metadata with a Kubernetes object. Unlike Selectors though, annotations can’t be used to select or group objects. Some sample use cases for annotations are specifying contact info for the object maintainer or the Git commit hash of the object.</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: demo-annotation-pod<br>  annotations:<br>    contact: <a href="/service/mailto:test@oncall.com">test@oncall.com</a><br>spec:<br>  containers:<br>    - name: nginx<br>      image: nginx<br>      imagePullPolicy: Always</pre><p>Annotations are added to an object in the <strong>metadata.annotations</strong> section of the object descriptor and are visible in the Pod metadata when you run a describe like this <strong>kubectl describe pod demo-annotation-pod</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TKIwu1CLrpl98p4nHwnYPg.png" /></figure><p>The sample code for this post is available <a href="https://github.com/reachansari/kubernetes-examples/tree/main/Labels%26Selectors%26Annotations-%E2%80%8AChapter%2010">here</a>.</p><p>Happy coding..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b6c74adadb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Spring Boot App To AWS Elastic Beanstalk]]></title>
            <link>https://medium.com/javarevisited/deploy-spring-boot-app-to-aws-elastic-beanstalk-fa42b8b4bfa0?source=rss-5365dede21aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa42b8b4bfa0</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[elastic-beanstalk]]></category>
            <dc:creator><![CDATA[Thameem Ansari]]></dc:creator>
            <pubDate>Mon, 07 Mar 2022 08:24:29 GMT</pubDate>
            <atom:updated>2022-03-08T15:21:21.110Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="https://javarevisited.blogspot.com/2018/02/top-5-spring-microservices-courses-with-spring-boot-and-spring-cloud.html"><img alt="" src="https://cdn-images-1.medium.com/max/802/1*eCeIiz__QJPfjcvG31yjaw.jpeg" /></a><figcaption>Spring Boot App To AWS Elastic Beanstalk</figcaption></figure><h3>Introduction</h3><p>In this article, we learn how to create a simple spring boot web application and deploy it on the AWS Elastic Beanstalk.</p><p>Deploying a Spring boot application on <a href="https://aws.amazon.com/"><strong>AWS</strong></a> Elastic Beanstalk is a simple process.</p><p>We can use the <a href="https://aws.amazon.com/elasticbeanstalk/"><strong>AWS Elastic Beanstalk</strong></a> service to deploy web applications and services and scale them.</p><blockquote><strong>Prerequisites: </strong>We need to have an AWS account to use AWS services.</blockquote><h3>Creating the Spring boot application</h3><p>Create a simple spring boot application with the <strong>spring-boot-starter-web</strong> starter dependency. We can use the <a href="https://start.spring.io/"><strong>Spring Initializer</strong></a> to create the spring boot application template and download the application.</p><h4><strong><em>Adding a Rest controller</em></strong></h4><p>Create a new package <strong>com.example.demo.controller</strong> and create a <strong>HelloWorldController</strong> controller class.</p><p>We have created a REST endpoint which prints a “Hello” message</p><pre><strong>package</strong> com.example.demo.controller;</pre><pre><strong>import</strong> org.springframework.web.bind.annotation.GetMapping;</pre><pre><strong>import</strong> org.springframework.web.bind.annotation.PathVariable;</pre><pre><strong>import</strong> org.springframework.web.bind.annotation.RestController;</pre><pre>@RestController</pre><pre><strong>public</strong> <strong>class</strong> HelloWorldController {</pre><pre>@GetMapping(&quot;/&quot;)</pre><pre><strong>public</strong> String helloWorld() {</pre><pre><strong>return</strong> &quot;hello &quot;;</pre><pre>}</pre><pre>}</pre><h4>Update the server port</h4><p>Also, add the below configuration property to the <strong>application.properties</strong> file of the spring boot application under the <strong>src/main/resources</strong> folder.</p><p>server.port=5000</p><p>AWS Elastic Beanstalk expects our app to listen on port 5000.</p><p>We need to set this property to configure our spring boot application to listen on port number <strong>5000</strong>.</p><p>Below is the final project structure of the spring boot application.</p><figure><a href="https://www.java67.com/2018/06/5-best-courses-to-learn-spring-boot-in.html"><img alt="" src="https://cdn-images-1.medium.com/max/323/1*3ep_Pom4F5ah5G8vnJUxCg.png" /></a><figcaption>Project Structure</figcaption></figure><p>Now the application is ready. We can test it locally by running it.</p><h4>Testing locally</h4><p>We can start the application locally by <strong>Right-click on the project &gt; Run as &gt; Spring boot app </strong>using our IDE.</p><p>The application starts locally and, we can access our REST APIs at <a href="http://localhost:500/"><strong>http://localhost:5000/</strong></a></p><figure><a href="https://javarevisited.blogspot.com/2018/02/top-20-spring-rest-interview-questions-answers-java.html"><img alt="" src="https://cdn-images-1.medium.com/max/259/1*f6oCAaR6cKC_s3ChyMMv8A.png" /></a><figcaption>Local testing</figcaption></figure><h3>Deploy Spring boot app to AWS Elastic Beanstalk</h3><p>We need to build the spring boot jar file that contains the embedded tomcat server bundled into it.</p><p>Using STS or <a href="https://medium.com/javarevisited/6-free-best-eclipse-ide-courses-for-java-programmers-1229ee9e5d87">Eclipse IDE</a>, we can run the maven build by <strong>Right-click on project &gt; Run as &gt; Maven install</strong>.</p><p>The maven build tool will build our application as a jar file inside the <strong>target/</strong> folder of the project.</p><figure><a href="https://javarevisited.blogspot.com/2019/03/top-5-course-to-learn-apache-maven-for.html#axzz6ccm5KWKs"><img alt="" src="https://cdn-images-1.medium.com/max/326/1*a5ZxT8asnRkshmVdHqlbuA.png" /></a></figure><p>To deploy our application, we have to navigate on the Elastic Beanstalk service, as shown below.</p><figure><a href="https://javarevisited.blogspot.com/2020/02/top-5-courses-to-crack-aws-certified-cloud-practitioner-exam-certification-clf-c01.html"><img alt="" src="https://cdn-images-1.medium.com/max/574/1*ABN3WwxfPtvgTt7Mtc84qg.png" /></a><figcaption>Navigate AWS Services</figcaption></figure><p>Then, on the Amazon elastic Beanstalk home page, click on the <strong>Create Application</strong> button to create a new application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*rPSwaWD2er-lKxHPZrdBlg.png" /><figcaption>Create an application</figcaption></figure><p>Enter a name on the application name field. Here, we will name our application as <strong>my-spring-app</strong>.</p><figure><a href="https://javarevisited.blogspot.com/2019/08/how-to-crack-aws-certified-solution-architect-exam.html"><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Lzs9mHmJ_ZpShWqeZM6x6g.png" /></a><figcaption>Create application name</figcaption></figure><p>Then select the platform details under the platform section. We have selected the platform to <strong>Java</strong> as we are going to deploy a java application.</p><p>Also under the <strong>Application code</strong> section, select the <strong>Upload your code</strong> option.</p><figure><a href="https://www.java67.com/2020/08/top-5-free-courses-to-pass-aws-cloud.html"><img alt="" src="https://cdn-images-1.medium.com/max/923/1*TFmR0Kno6oiifbLZuQ4Qfg.png" /></a><figcaption>Upload the code</figcaption></figure><p>Finally, select the spring boot application jar file generated from the maven build, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*kRmkeGuOp4ksC3_1uey3qA.png" /><figcaption>Choose and upload the application JAR</figcaption></figure><p>Click on the <strong>Create application</strong> button, and the application starts to get deployed into the AWS elastic beanstalk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*CzDk1-tgw6SEaRsc7ONusw.png" /><figcaption>Create the application</figcaption></figure><p>Once the application deployment is successful, we can see an entry under <strong>Environments,</strong> as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*uamQtHtxSQxKSOVmS8vTxg.jpeg" /><figcaption>Application listed with environment</figcaption></figure><p>We can also see that the application health is <strong>Ok,</strong> and the Recent events on the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*al74bKjQ4TBgkLuyhiZtDQ.jpeg" /><figcaption>Application health check</figcaption></figure><h3>Testing the application</h3><p>The AWS elastic beanstalk handles our application. We can access our application from the application URL generated by the <a href="https://medium.com/javarevisited/5-best-aws-courses-for-beginners-and-experienced-developers-to-learn-in-2021-563212409fbd">AWS beanstalk</a>.</p><p>The URL can be found on the application instance screen, as shown in the previous image.</p><p>Open the application URL to access the spring boot application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*X_KtGAZ-K9LW_OkA_k9ygg.png" /><figcaption>Test the endpoint</figcaption></figure><h3>Deleting the application</h3><p>We can delete the application instance by simply selecting the <strong>Delete application</strong> option under the <strong>Actions</strong> menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*DePjv1N7FYXV5RnN445sZQ.png" /><figcaption>Delete the application</figcaption></figure><p>It may take some time for AWS to complete the delete operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*dTMgq5upzqm1W7GKJFeGOw.png" /><figcaption>Deleted successfully</figcaption></figure><h3>Conclusion</h3><p>In this article, we learned how to create a simple spring boot web application.</p><p>We also learned how to test the application locally and generate the application jar file.</p><p>Finally, we learned how to deploy the spring boot jar file to the AWS Elastic Beanstalk.</p><p>Happy coding..</p><ul><li><a href="https://medium.com/javarevisited/10-free-spring-boot-tutorials-and-courses-for-java-developers-53dfe084587e">10 Best Free Courses to Learn Spring and Microservices for Java Programmers in 2023</a></li><li><a href="https://medium.com/javarevisited/top-22-skills-professional-java-programmers-can-learn-in-2022-to-upgrade-themselves-bc3da73d7491">Top 25 Tech Skill Java Developers Can Learn in 2023</a></li><li><a href="https://medium.com/javarevisited/13-topics-you-should-prepare-for-your-next-spring-boot-interview-5f2993a04ff5">13 Topics You Should Prepare for Your Next Spring Boot Interview in 2024</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa42b8b4bfa0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/deploy-spring-boot-app-to-aws-elastic-beanstalk-fa42b8b4bfa0">Deploy Spring Boot App To AWS Elastic Beanstalk</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST API Load performance testing using Apache JMeter]]></title>
            <link>https://medium.com/javarevisited/rest-api-load-performance-testing-using-apache-jmeter-63605572e862?source=rss-5365dede21aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/63605572e862</guid>
            <category><![CDATA[jmeter]]></category>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[rest-api-testing]]></category>
            <category><![CDATA[performance-testing]]></category>
            <dc:creator><![CDATA[Thameem Ansari]]></dc:creator>
            <pubDate>Sat, 05 Mar 2022 13:42:57 GMT</pubDate>
            <atom:updated>2022-03-08T15:25:36.132Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="https://javarevisited.blogspot.com/2018/02/top-5-restful-web-services-with-spring-courses-for-experienced-java-programmers.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zl2d_hmgFud0Y2KsZx4hOA.png" /></a><figcaption>REST API Load performance testing with Apache JMeter</figcaption></figure><h3>Introduction</h3><p>In this article, we are going to do a basic load testing with <strong>Apache JMeter </strong>which is an open source software and It can be used to simulate loads of various scenarios and output performance data in several ways, including CSV and XML files and graphs. Since it is an 100% pure Java Application, It is <a href="https://www.java67.com/2012/08/how-java-achieves-platform-independence.html">platform-independent</a> (able to run on every OS ).</p><p>According to the documentation, this tool comes with a bunch of features. Such as;</p><ul><li>Ability to load and performance test many different applications/server/protocol types.</li><li>Easy correlation through the ability to extract data from most popular response formats, <a href="https://jmeter.apache.org/usermanual/component_reference.html#CSS/JQuery_Extractor"><strong>HTML</strong></a><strong>, JSON, </strong><a href="https://jmeter.apache.org/usermanual/component_reference.html#XPath_Extractor"><strong>XML</strong></a><strong> or </strong><a href="https://jmeter.apache.org/usermanual/component_reference.html#Regular_Expression_Extractor"><strong>any textual format</strong></a></li><li>Complete portability and <strong>100% Java purity</strong>.</li><li><strong>The full </strong><a href="https://medium.com/javarevisited/8-best-multithreading-and-concurrency-courses-for-experienced-java-developers-8acfd3b25094"><strong>multithreading</strong> framework</a> allows concurrent sampling by many threads and simultaneous sampling of different functions by separate thread groups.</li><li>Caching and offline analysis/replaying of test results.</li></ul><h3>Installation</h3><p>First, you need to download the JMeter from the <a href="https://jmeter.apache.org/download_jmeter.cgi">Apache JMeter website</a>. Once after you download the zip file then extract it to a location where you want to work with it. Then move to the /bin folder inside that extracted folder and hit the following command- <strong>jmeter.sh</strong> to open the Apache JMeter with GUI, please note it is advised not to load the GUI when running load tests, only advised to use GUI for Test creation and Test <a href="https://javarevisited.blogspot.com/2011/02/how-to-setup-remote-debugging-in.html">debugging </a>purposes.</p><p>If the installation was successful you should see below screen.</p><figure><a href="https://javarevisited.blogspot.com/2018/09/top-5-courses-to-learn-intellij-idea-java-and-android-development.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3ylRUtfNFvpgy_6t.png" /></a></figure><h3>Test Plan</h3><p>Before writing a test plan let’s see what it is, A <strong><em>Test Plan </em></strong>can be viewed as a container for running tests. It defines what to test and how to go about it. A proper test plan will have some of the elements such as;</p><ul><li>Thread groups</li><li>Logic controllers</li><li>Timers</li><li>Pre and Post Processors</li><li>Configuration Elements etc.</li></ul><p><em>Please note that, In a test plan, it is a must to have at least </em><strong><em>one thread group</em></strong><em>.</em></p><p>You can simply <strong><em>add</em></strong> or <strong><em>remove</em></strong> above elements to a <strong>T<em>est Plan </em></strong>by right-clicking on the name of the <strong>T<em>est Plan</em></strong> (i.e in my case it is the Test Plan as shown below) and then select add from the menu and, chose whatever the element you want to add.</p><figure><a href="https://javarevisited.blogspot.com/2019/04/top-5-junit-and-unit-testing-courses-java-programmers.html#axzz6iYmMFnsA"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uQhnaf0VVk9byTzH.png" /></a></figure><h3>Configuring the Test Plan</h3><p>As we learned we need to have at least <strong><em>one Thread Group</em></strong> for the test plan in order to run the load test. So let’s first add a thread group to the <strong><em>Test Plan.</em></strong></p><p>To add a T<strong><em>hread Group </em></strong>right click on the Test Plan and then add -&gt; Threads -&gt; Thread Groups</p><figure><a href="https://javarevisited.blogspot.com/2021/12/top-5-courses-to-learn-rest-assured-for.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w6EBS7qnrlih7aDL.png" /></a><figcaption>Adding a Thread Group</figcaption></figure><p>If you are successful then you will see <strong>Thread Group</strong> has been added to your <strong>Test Plan </strong>as follows.</p><figure><a href="https://javarevisited.blogspot.com/2022/01/top-5-courses-to-learn-swagger-or-open.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LPGl34W7HmqixSoQ.png" /></a><figcaption>Thread Group has been added to the Test Plan.</figcaption></figure><p>Then what you need to do is add another element under <strong><em>Thread Group</em></strong> for <strong><em>HTTP Request</em></strong>, as we did before we can add a new <strong><em>HTTP Request </em></strong>element to <strong><em>Thread Group</em></strong> by right-clicking on that and select the menu items as shown in the below picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yGUYSAxirq-gwSS-.png" /><figcaption>Adding a HTTP Request element to the Thread Group.</figcaption></figure><p>If you are successful then you will see your <strong><em>HTTP Request </em></strong>element listed under the <strong><em>Thread Group </em></strong>element as follows.</p><figure><a href="https://javarevisited.blogspot.com/2021/04/top-5-tools-to-test-rest-apis-in-java.html#axzz7CGBoUS1n"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8Ie2i_cLsCEIB0pp.png" /></a><figcaption>Configured HTTP Request element</figcaption></figure><p>Let’s configure our <strong><em>HTTP Request </em></strong>element with relevant values for <em>Protocol, Server Name, Port Number, Http Request Method </em>and<em> </em><em>Path </em>as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MY2Jy76H_TrUqJnO.png" /><figcaption>HTTP Get Request config</figcaption></figure><p>Now we have successfully configured our <strong><em>HTTP Request </em></strong>element. Then we need to configure a Listener to see the result of the HTTP Request.</p><p><strong>If you want to Configure a Test Plan for a POST API endpoint</strong></p><p>If you want to load test a POST endpoint with a payload then you need to configure your <strong><em>HTTP Request </em></strong>to have a different configuration than the above, You will have to pass a payload under the <strong>Body Data</strong> section and the relevant port number and the Path value.</p><figure><a href="https://javarevisited.blogspot.com/2020/02/top-5-postman-tutorials-and-courses-for-web-developers.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*navRPQqadeOMU1v7.png" /></a><figcaption>Configured HTTP Request for POST API endpoint.</figcaption></figure><h3>Adding a Listener</h3><p>In JMeter, listeners are used for outputting the results of a load test. There are several types of listeners available in JMeter but for this test we will use <strong><em>View Results in Tree </em></strong>listener, which is a more simple one.</p><p>To add a <strong><em>View Results in Tree </em></strong>element to the <strong><em>Thread Group </em></strong>element right-click on the <strong><em>Thread Group </em></strong>element and select the menu items as shown in the picture as we did before.</p><figure><a href="https://javarevisited.blogspot.com/2016/05/what-are-idempotent-and-safe-methods-of-HTTP-and-REST.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8n5-lRJ37L7pXnCs.png" /></a><figcaption>Adding View Results Tree to the Thread Group element.</figcaption></figure><p><strong>Saving the File before Running the Listener</strong></p><p>We will have to save the file in order to view the outputting results of the load test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hzgffXi_qnVnGez5.png" /><figcaption>Saving the file</figcaption></figure><p>The file will get saved in .jmx format as shown above.</p><p>If you have added the element correctly to the <strong><em>Thread Group </em></strong>element, then our setup would look similar to the below Screenshot</p><figure><a href="https://javarevisited.blogspot.com/2021/11/top-5-courses-to-learn-soapui-online-in.html#axzz7CANam4JD"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QesDhJ3bnHdI4OlV.png" /></a><figcaption>Configured View Results in Tree listener.</figcaption></figure><h3>Running the Test Plan</h3><p>Now we have configured the test plan correctly. Then let’s run the test and see results.</p><p>Select on <strong><em>View Results Tree</em></strong> element in the left pane, then click <strong><em>Run</em></strong> from the main menu then click <em>Start</em> (or just click the green Start arrow below the main menu) as shown in the below screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tcxH2wBDUnbzsQSf.png" /></figure><p>If you have followed the steps correctly then you should see the output as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lrXqvfEuKKXGjbjl.png" /><figcaption>HTTP Request Test response</figcaption></figure><p>We have got a 200 success response with response data since it is a Get request.</p><h3>Load Testing</h3><p>Okay, cool now we have everything set up correctly. Now it’s time to run the load test. In order to do so, we need to reconfigure our <strong><em>Thread Group</em></strong> element in our <strong><em>Test Plan</em></strong> to have several Thread related properties. To do that click on the <strong><em>Thread Group </em></strong>and add the following properties to it. Because to be a load test we should provide some heavy load to the API’s endpoint. By changing the following parameters in <strong><em>Thread Group </em></strong>it allows JMeters to perform a proper load test with a number of users specified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yCBX8lgPOVWmLjsn.png" /><figcaption>Updated Thread Group</figcaption></figure><p>Those changed values are the three particularly important properties which influence a load test:</p><ul><li><strong>Number of Threads (users):</strong> The number of users that JMeter will attempt to simulate.</li><li><strong>Ramp-Up Period (in seconds):</strong> The duration of time that JMeter will distribute the start of the threads over.</li><li><strong>Loop Count:</strong> The number of times to execute the test.</li></ul><p>Then again save the <strong>Test Plan </strong>and then run the test again by following the above mentioned steps and you would see something similar to below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S8o1bPdgxqV0yGGs.png" /><figcaption>Load Test</figcaption></figure><h3>Understanding the Result</h3><p>We can see that the <strong><em>Status</em></strong> of all the requests in the above screenshot is “Success” (indicated by a green shield with a tick in it). After that, the <strong>Sample Time (ms)</strong>and <strong><em>Latency</em></strong> columns are probably the most interests columns in the result set.</p><ul><li><strong><em>Latency:</em></strong> The number of milliseconds that elapsed between when JMeter sent the request and when an initial response was received</li><li><strong><em>Sample Time:</em></strong> The number of milliseconds that the server took to fully serve the request (response + latency)</li></ul><p>According to the <strong><em>View Results in Tree </em></strong>output, the <strong>load<em> Time</em></strong> is 144. This is fairly a high value for a simple <a href="https://medium.com/javarevisited/10-best-java-web-services-rest-soap-and-api-courses-for-beginners-724a8f51298d">Rest API</a>, but in my case, this endpoint does few heavy tasks and that is acceptable for me. You might be having different results than me based on what your REST API endpoint does and based on other factors, such as; geographical distance (which generally increases latency), the size of the requested item (which increases transfer time) etc.. So don’t worry about the result, if you have different values than mine.</p><p>So, basically what we did was we simulated 50 users accessing one API endpoint over 10 seconds (5 every second).</p><p>As you can see it is pretty clear that its very easy to test the API with the number of virtual users with just a simple change in Thread Group configuration.</p><p>With JMeter user can do testing other than load testing for example Stress Test, Functional Test, Distributed Test.</p><p>Happy coding..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63605572e862" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/rest-api-load-performance-testing-using-apache-jmeter-63605572e862">REST API Load performance testing using Apache JMeter</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>