<?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 harshal on Medium]]></title>
        <description><![CDATA[Stories by harshal on Medium]]></description>
        <link>https://medium.com/@harshzone?source=rss-322afe6d66ea------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WNANt_5UED_aP4uWq8v_uA.jpeg</url>
            <title>Stories by harshal on Medium</title>
            <link>https://medium.com/@harshzone?source=rss-322afe6d66ea------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 21:06:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harshzone/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[Spring Boot Monitoring: Custom Datadog Metrics with Micrometer]]></title>
            <link>https://medium.com/@harshzone/spring-boot-monitoring-custom-datadog-metrics-with-micrometer-809e2aa04e69?source=rss-322afe6d66ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/809e2aa04e69</guid>
            <category><![CDATA[datadog]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[monitoring]]></category>
            <dc:creator><![CDATA[harshal]]></dc:creator>
            <pubDate>Fri, 31 Jan 2025 13:34:17 GMT</pubDate>
            <atom:updated>2025-01-31T13:34:17.856Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8TGcO1AOp7AV87Suuymc5w.png" /></figure><p>In today’s world of microservices and cloud-native applications, keeping track of system health is crucial. <strong>Micrometer</strong> is a simple yet powerful library that helps collect application metrics in <strong>Spring Boot</strong> and integrates well with monitoring tools like <strong>Datadog</strong>.</p><h4>Adding Micrometer to Spring Boot</h4><p>First, add <strong>Micrometer dependencies</strong> to pom.xml:</p><pre>&lt;!-- Micrometer Datadog Registry (To Send Metrics to Datadog) --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.micrometer&lt;/groupId&gt;<br>    &lt;artifactId&gt;micrometer-registry-datadog&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h4>Configuration</h4><p>To send metrics to Datadog, configure application.yml.</p><pre>management:<br>  datadog:<br>    metrics:<br>      export:<br>        uri: &quot;https://datadoghq.eu&quot;<br>        api-key: ${DATADOG_APIKEY}<br><br>monitoring:<br>  metrics:<br>    tags:<br>      env: ${APP_ENV}<br>      service: service_name</pre><ol><li><strong><em>management.datadog.metrics.export</em></strong><em>.</em><strong><em>uri</em></strong><em> : </em>Micrometer sends metrics to Datadog, and this property tells it where to send them.</li><li><strong><em>management.datadog.metrics.export.api-key : </em></strong>${DATADOG_APIKEY}This is an <strong>environment variable</strong>, meaning it’s fetched at runtime.</li></ol><p>In <strong>Enterprise Applications</strong>, ${DATADOG_APIKEY} typically stored in:</p><ul><li><strong>Environment Variables</strong> (export DATADOG_APIKEY=your-key in Linux/Mac or set DATADOG_APIKEY=your-key in Windows).</li><li><strong>Secrets Management Systems</strong> (like AWS Secrets Manager, Azure Key Vault, Kubernetes Secrets).</li></ul><p>3.<strong><em> monitoring.metrics.tags : </em></strong>This tags are visible in datadog. Based on tags you can create monitors for different Env.<br>e.g. ${APP_ENV} -&gt; x-dev, x-pre-production, x-production</p><pre>@ConfigurationProperties(&quot;monitoring.metrics&quot;)<br>@Getter<br>public class MetricsCommonTags {<br>    private final Map&lt;String, String&gt; tags = new LinkedHashMap&lt;&gt;();<br>}</pre><pre>@Bean<br>public MeterFilter metricsCommonTagsBean(MetricsCommonTags metricsCommonTags) {<br>    return MeterFilter.commonTags(<br>        metricsCommonTags.getTags().entrySet().stream()<br>            .map(entry -&gt; Tag.of(entry.getKey(), entry.getValue()))<br>            .collect(Collectors.toList())<br>    );<br>}</pre><h4>Create MeterRegistry Bean</h4><pre>@Configuration<br>public class MetricsConfiguration {<br><br>    @Bean<br>    public MeterRegistry compositeMeterRegistry() {<br>        return new CompositeMeterRegistry();<br>    }<br>}</pre><ul><li><strong>MeterRegistry</strong> is part of <strong>Micrometer</strong>, a library that Spring Boot uses to handle application metrics.</li><li>It provides an interface to register various types of <strong>metrics</strong> (such as counters, gauges, timers) and expose them to monitoring systems (like Prometheus, Graphite, or Datadog).</li></ul><h4>Creating Custom Metrics</h4><p>Micrometer provides different types</p><h4>Counters</h4><p>A counter is a metric that keeps track of a number by increasing or decreasing it. It’s used to count things, like how many times an event happens (e.g., number of requests).</p><p>simple way to use counter</p><pre>@Service<br>@Getter<br>public class MonitorService{<br>   private static final String USER_CREATE_SUCCESS_COUNT = &quot;user.create.success.count&quot;;<br>   private static final String USER_CREATE_FAIL_COUNT = &quot;user.create.fail.count&quot;;<br>  // other counters <br><br>  private final MeterRegistry meterRegistry;<br>  private final Counter userCreateSuccessCount;<br>  private final Counter userCreateFailCount;<br><br>  public MonitorService(MeterRegistry meterRegistry){<br>    this.meterRegistry = meterRegistry;<br>    userCreateSuccessCount = meterRegistry.counter(USER_CREATE_SUCCESS_COUNT);<br>    userCreateFailCount = meterRegistry.counter(USER_CREATE_FAIL_COUNT);<br>  }<br>}</pre><p>use above counter</p><pre>@AllArgsConstructor<br>@Repository<br>public class UserRepository{<br>    private final MonitorService monitorService;<br><br>    public User createUser(User user){<br>      try{<br>        // your code<br>        //...<br>        monitorService.getUserCreateSuccessCount().increment();<br>        <br>      }catch(Exception ex){<br>        //if exception occur means fail<br>        //..handle exception<br>        monitorService.getUserCreateFailCount().increment();<br>      }<br>    }<br>}</pre><p>In datadog to create success count monitor for above you will find “<strong><em>user.create.success.count</em></strong>” in “Graph your data &gt;&gt;<strong>Add Query</strong>” section</p><p>In some scenario we have to create monitor based on type or category wise.<br>e.g . The <strong>USER</strong> can belong to one of two types: 1. <strong>STUDENT</strong> 2. <strong>EMPLOYEE</strong>, and for each type, a distinct monitor/dashboard should be created.</p><pre>public enum UserType {<br>    STUDENT,<br>    EMPLOYEE;<br>}</pre><pre>@Service<br>@Getter<br>public class MonitorService{<br>   private static final String USER_CREATE_SUCCESS_COUNT = &quot;user.create.success.count&quot;;<br>   private static final String USER_CREATE_FAIL_COUNT = &quot;user.create.fail.count&quot;;<br>  // other counters<br><br>  private final MeterRegistry meterRegistry;<br>  private final Counter userCreateSuccessCount;<br>  private final Counter userCreateFailCount;<br><br>  public MonitorService(MeterRegistry meterRegistry){<br>    this.meterRegistry = meterRegistry;<br>    userCreateSuccessCount = meterRegistry.counter(USER_CREATE_SUCCESS_COUNT);<br>    userCreateFailCount = meterRegistry.counter(USER_CREATE_FAIL_COUNT);<br>  }<br><br>  public void incrementUserCreateSuccessCount(UserType userType){<br>     Counter.builder(USER_CREATE_SUCCESS_COUNT)<br>             .tag(&quot;userType&quot;, userType.name())<br>             .register(meterRegistry)<br>             .increment();<br>  }<br>  public void incrementUserCreateFailCount(UserType userType){<br>     Counter.builder(USER_CREATE_FAIL_COUNT)<br>             .tag(&quot;userType&quot;, userType.name())<br>             .register(meterRegistry)<br>             .increment();<br>  }<br>}</pre><pre>@AllArgsConstructor<br>@Repository<br>public class UserRepository{<br>    private final MonitorService monitorService;<br><br>    public User createUser(User user){<br>      try{<br>        // your code<br>        //...<br>        monitorService.incrementUserCreateSuccessCount(user.UserType);<br>        <br>      }catch(Exception ex){<br>        //if exception occur means fail<br>        //..handle exception<br>        monitorService.incrementUserCreateFailCount(user.UserType);<br>      }<br>      <br>    }<br>}</pre><p>In datadog to create success count monitor for <strong>STUDENT</strong> you will find “<strong><em>user.create.success.count</em></strong>” in “Graph your data &gt;&gt;<strong>Add Query</strong>” and to get only STUDENT count, add “<strong>userType:student</strong>” .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=809e2aa04e69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing : Spring Boot with Groovy and Spock]]></title>
            <link>https://medium.com/@harshzone/unit-testing-spring-boot-with-groovy-and-spock-33e6ea2bc04e?source=rss-322afe6d66ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/33e6ea2bc04e</guid>
            <category><![CDATA[spock]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[groovy]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[harshal]]></dc:creator>
            <pubDate>Fri, 17 Jan 2025 11:51:57 GMT</pubDate>
            <atom:updated>2025-01-17T11:51:57.788Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unit Testing : Spring Boot with Groovy and Spock</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_MRpKtPASptSbBeVpHJ-Cw.png" /></figure><p><strong>Here</strong>, we will explore unit testing in Spring Boot using Groovy and Spock. We’ll dive into Spock’s Given-When-Then style, best practices for writing tests and how to reduce dependency on heavy mocking frameworks. Whether you’re a seasoned developer or just starting, this guide will help you write better, cleaner tests while keeping your sanity intact.</p><h3>Why Use Groovy and Spock for Testing?</h3><ul><li><strong>Readable and Maintainable Tests</strong>:<br>Spock’s <strong>Given-When-Then</strong> syntax ensures tests are easy to understand and revisit, even with complex scenarios.</li><li><strong>Encourages Better Code Practices</strong>:<br>Spock discourages reliance on <strong>static methods</strong> and <strong>in-method class instantiations</strong>, promoting better testability and clean design.</li><li><strong>Flexible and Expressive Test Names</strong>:<br>Spock allows <strong>descriptive test names</strong> in strings (e.g., &quot;should return the correct result when adding two numbers&quot;), making test intent clearer than JUnit&#39;s strict method naming conventions.</li><li><strong>One Test Case, Multiple Scenarios</strong>:<br>Spock supports <strong>parameterized tests</strong>, reducing redundancy when testing multiple inputs for the same method or logic block.</li></ul><p><strong>For Maven, add the following to your pom.xml</strong>:</p><pre>&lt;dependencies&gt; <br> &lt;dependency&gt;<br>   &lt;groupId&gt;org.spockframework&lt;/groupId&gt;<br>   &lt;artifactId&gt;spock-spring&lt;/artifactId&gt;<br>   &lt;version&gt;2.3-groovy-4.0&lt;/version&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br> &lt;/dependency&gt;<br>&lt;/dependencies&gt;<br><br>&lt;build&gt;<br>  &lt;plugins&gt;<br>   &lt;plugin&gt;<br>    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>    &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;<br>    &lt;version&gt;3.5.2&lt;/version&gt;<br>    &lt;configuration&gt;<br>     &lt;testSourceDirectory&gt;src/test/groovy&lt;/testSourceDirectory&gt;<br>     &lt;includes&gt;<br>      &lt;include&gt;**/*Spec.*&lt;/include&gt;<br>     &lt;/includes&gt;<br>    &lt;/configuration&gt;<br>   &lt;/plugin&gt;<br>  &lt;/plugins&gt;<br>&lt;/build&gt;</pre><h3><strong>Writing Your First Test:</strong></h3><pre>import lombok.AllArgsConstructor;<br>import org.springframework.stereotype.Component;<br><br>@AllArgsConstructor<br>@Component<br>public class VehicleService {<br>    private final VehicleRepository vehicleRepository;<br><br>    public Vehicle getVehicleInfo(Long id){<br>        return vehicleRepository.findById(id)<br>                .orElseThrow(() -&gt; new RuntimeException(&quot;User not found&quot;));<br>    }<br>}</pre><p>let’s test above VehicleService</p><pre>import spock.lang.Specification;<br><br>class VehicleServiceSpec extends Specification {<br><br>    private VehicleService vehicleService<br>    private VehicleRepository vehicleRepository<br><br>    def setup(){<br>        vehicleRepository = Mock(VehicleRepository)<br>        vehicleService = new VehicleService(vehicleRepository)<br>    }<br><br>    def &quot;given valid vehicleId, when it is processed, return vehicle info&quot;(){<br>        given: &quot;valid vehicle id&quot;<br>        def id = 1234L;<br>        def vehicleResponse = Vehicle.builder().id(1234L).model(&quot;XYZ&quot;).brand(&quot;ABC&quot;).build()<br><br>        and:&quot;mock repository returns data&quot;<br>        vehicleRepository.findById(_) &gt;&gt; Optional.of(vehicleResponse)<br><br>        when:&quot;We call a method that should return a VehicleInfo&quot;<br>        def result = vehicleService.getVehicleInfo(id)<br><br>        then: &quot;The repository method was called exactly once&quot;<br>        1 * vehicleRepository.findById(_)<br><br>        then:&quot;The result is not null&quot;<br>        result != null<br>    }<br>}</pre><p><strong>Explanation</strong> :</p><p><strong>Specification class: </strong>extending Specification to allow Spock framework features.</p><p><strong>Setup: </strong>Perform any setups before running the test case. which is run before each test case to set up necessary objects.</p><p><strong>Mock(VehicleRepository): </strong>allowing you to simulate the repository’s behavior without using an actual database.</p><p><strong>vehicleRepository.findById(_) &gt;&gt; Optional.of(vehicleResponse): </strong>when findById is called with any argument (_), return an Optional containing the vehicleResponse</p><p><strong>1 * vehicleRepository.findById(_): </strong>Asserts that findById was called exactly once with any argument (_).</p><blockquote><strong>given Block</strong>: Use this to define and initialize mock objects or dummy data.</blockquote><blockquote><strong>when Block</strong>: Contains the action or the method invocation you are testing.</blockquote><blockquote><strong>then Block</strong>: Contains assertions and verifications, such as checking method calls on mocks or expected outputs.</blockquote><h3><strong>Writing Data driven test:</strong></h3><p>In Spock, a <strong>data-driven test case</strong> allows you to run the same test with multiple sets of input data, making the test more efficient and reusable.</p><pre>def &quot;should return correct area for different rectangle dimensions&quot;() {<br>    given: &quot;a rectangle instance&quot;<br>    def rectangle = new Rectangle()<br><br>    when: &quot;calculating the area of the rectangle&quot;<br>    def result = rectangle.calculateArea(width, height)<br><br>    then: &quot;the area is correct&quot;<br>    result == expectedArea<br><br>    where:<br>    width     | height     || expectedArea<br>    2         | null       || &quot;Invalid&quot;<br>    null      | 4          || &quot;Invalid&quot;<br>    null      | null       || &quot;Invalid&quot;<br>    10        | 2          || 20<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33e6ea2bc04e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built My First Android App and Earned 2000 rupee]]></title>
            <link>https://medium.com/@harshzone/how-i-built-my-first-android-app-and-earned-2000-rupee-dc21ccd48417?source=rss-322afe6d66ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc21ccd48417</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[app-development]]></category>
            <dc:creator><![CDATA[harshal]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 19:46:05 GMT</pubDate>
            <atom:updated>2025-01-07T18:41:16.114Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9MuF1HnyGW7fFrM3DMThmw.png" /></figure><h4>Introduction</h4><p>They say every challenge hides an opportunity, and the COVID-19 lockdown was no exception. While the world came to a standstill, I decided to make the most of my time. What started as an experiment to learn Android development using React Native turned into a practical app that earned me ₹2000. It wasn’t just about the money — it was about solving a real-world problem and learning something new along the way.</p><h4>The Beginning: Turning Lockdown Time Into Learning</h4><p>During the lockdown, like everyone else, I had a lot of free time and countless questions. “How can I make better use of this time?” “What new skills can I learn?” Since I already had experience in React.js for web development, I thought, “Why not try React Native and explore mobile app development?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*whEajP3DBU1qwObtMUGtFw.png" /></figure><p>I installed Android Studio, excited to create my first Android app. But as soon as I launched it, my laptop’s fans started spinning like a jet engine! To make matters worse, the screen froze so often it felt like my laptop was begging for mercy. I knew this wasn’t going to work, so I ditched Android Studio and switched to Expo. Expo made everything easier — I could preview the app on my mobile device without using heavy emulators.</p><h4>The Opportunity: A Problem Worth Solving</h4><p>One of my friends from my village runs a catering business. He provides services for weddings, family functions, and birthday parties. One day, while casually chatting, I asked him how his business was going.</p><p>He replied, “It’s going well, but there’s so much manual work involved.” Curious, I asked him to explain his process.</p><p>Here’s what he shared: whenever a new order came in, he’d print 6–7 pages of different lists — groceries, dairy products, vegetables, fruits, utensils, and so on. Then, he’d manually mark the required items on each list and hand them over to the respective team members to purchase.</p><p>The problem?</p><ul><li>Printing costs for every order.</li><li>The tedious and time-consuming process of marking items manually.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*Knyelkt2A38sx6ddYHN-_g.png" /></figure><p>This felt like a perfect opportunity to solve a real problem. I immediately said, “What if I create an app for you to simplify all this?” He agreed, and we began discussing his requirements.</p><h4>The Solution: Designing and Building the App</h4><p>I started by understanding his process in detail. Then, I researched different catering app designs online and sketched out how the app would look. Each page was planned meticulously, including features like:</p><ul><li>Categorizing items (groceries, dairy, vegetables, etc.).</li><li>Adding, deleting, and updating items and their prices.</li><li>Searching for items quickly.</li><li>Exporting lists to PDF format.</li><li>Sharing PDFs directly on WhatsApp.</li></ul><p>Once the design was finalized, I began coding the app using React Native with Expo.</p><h4>Challenges I Faced</h4><p>The journey wasn’t without its hurdles:</p><ol><li><strong>State Management Issues</strong>: The app was slowing down due to unnecessary re-renders.</li><li><strong>Performance Optimization</strong>: Managing long lists efficiently was tricky.</li><li><strong>Debugging</strong>: Every bug felt like a puzzle, but I solved most of them with the help of tutorials and, of course, ChatGPT.</li></ol><p>Within a week, I completed the app.</p><h4>Delivering the App and Making an Impact</h4><p>When I handed over the app to my friend, he was thrilled! The app saved him both time and money — it eliminated the need for printing lists and made the process faster and more organized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PyMZtI3AHIf7upFLkKqNWQ.png" /></figure><p>Of course, nothing comes free, so I charged him a modest ₹2000. It wasn’t a big amount, but the satisfaction of solving a real problem and seeing my work in action was priceless.</p><h4>Conclusion</h4><p>This experience taught me the value of solving real-world problems through technology. Building this app not only helped me earn my first income from an Android app but also gave me the confidence to tackle bigger projects in the future.</p><p>So, if you have an idea or see a problem that needs solving, don’t hesitate — start building! You never know where it might lead you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc21ccd48417" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Localstack SQS for Local Testing with Spring Boot]]></title>
            <link>https://medium.com/@harshzone/localstack-sqs-for-local-testing-with-spring-boot-3d307c6d15b3?source=rss-322afe6d66ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d307c6d15b3</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[localstack]]></category>
            <category><![CDATA[sqs]]></category>
            <dc:creator><![CDATA[harshal]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 15:37:58 GMT</pubDate>
            <atom:updated>2024-12-21T09:52:12.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EIiCll7e5JFw47VYkEsmug.png" /></figure><h3>Introduction</h3><p>When building a microservice that integrates with AWS SQS, you need a way to test service. However, connecting to real AWS during development isn’t always ideal — it’s slow, it costs money, and sometimes you don’t want to expose resources unnecessarily.</p><p>This is where Localstack shines. It creates a local environment that mimics AWS services like SQS. Today, we’ll:</p><ol><li>Set up a Spring Boot project with Localstack.</li><li>Create an SQS message consumer.</li><li>Write integration tests for the consumer using Localstack.</li><li>install docker and run.</li></ol><h3>Maven Dependencies</h3><pre> &lt;dependencies&gt;<br>   &lt;dependency&gt;<br>     &lt;groupId&gt;io.awspring.cloud&lt;/groupId&gt;<br>     &lt;artifactId&gt;spring-cloud-aws-starter-sqs&lt;/artifactId&gt;<br>     &lt;version&gt;3.2.0&lt;/version&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-testcontainers&lt;/artifactId&gt;<br>     &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>     &lt;groupId&gt;org.testcontainers&lt;/groupId&gt;<br>     &lt;artifactId&gt;junit-jupiter&lt;/artifactId&gt;<br>     &lt;version&gt;1.20.4&lt;/version&gt;<br>     &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>     &lt;groupId&gt;org.testcontainers&lt;/groupId&gt;<br>     &lt;artifactId&gt;localstack&lt;/artifactId&gt;<br>     &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br> &lt;/dependencies&gt;<br><br> &lt;dependencyManagement&gt;<br>    &lt;dependencies&gt;<br>       &lt;dependency&gt;<br>          &lt;groupId&gt;software.amazon.awssdk&lt;/groupId&gt;<br>          &lt;artifactId&gt;aws-core&lt;/artifactId&gt;<br>          &lt;version&gt;2.28.24&lt;/version&gt;<br>       &lt;/dependency&gt;<br>       &lt;dependency&gt;<br>          &lt;groupId&gt;io.awspring.cloud&lt;/groupId&gt;<br>          &lt;artifactId&gt;spring-cloud-aws-core&lt;/artifactId&gt;<br>          &lt;version&gt;3.2.0&lt;/version&gt;<br>       &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br> &lt;/dependencyManagement&gt;</pre><h3>application.yml</h3><p>Add your queue name in the application.yml</p><pre>spring:<br>  cloud:<br>    aws:<br>      region:<br>        static: us-east-1<br>      credentials:<br>        access-key: test<br>        secret-key: test<br>      sqs:<br>        endpoint: http://localhost:4566<br><br>notification:<br>  sqs:<br>    queue-name: notification-queue</pre><h3>SQS Consumer Class</h3><p>Let’s create a simple SQS consumer that listens to a queue and logs incoming messages.</p><pre>import io.awspring.cloud.sqs.annotation.SqsListener;<br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>@Slf4j<br>public class SqsMessageConsumer {<br><br>    public static String check = &quot;&quot;;<br>    @SqsListener(&quot;${notification.sqs.queue-name}&quot;) // Fetch queue name from application.yml<br>    public String listenToQueue(String message) {<br>        log.warn(&quot;Received invalid message: {}&quot;, message);<br><br>        check = message;<br>        return check;<br>    }<br>}</pre><h3>Integration Test Class</h3><p>Now, let’s write an integration test using Localstack and Testcontainers.</p><pre>import io.awspring.cloud.sqs.operations.SqsTemplate<br>import org.springframework.beans.factory.annotation.Autowired<br>import org.springframework.boot.test.context.SpringBootTest<br>import org.springframework.test.context.ActiveProfiles<br>import org.springframework.test.context.DynamicPropertyRegistry<br>import org.springframework.test.context.DynamicPropertySource<br>import org.testcontainers.containers.localstack.LocalStackContainer<br>import org.testcontainers.junit.jupiter.Testcontainers<br>import org.testcontainers.utility.DockerImageName<br><br>@SpringBootTest<br>@Testcontainers<br>@ActiveProfiles(&quot;test&quot;)<br>class SqsMessageConsumerIT extends Specification{<br><br>    static final String QUEUE_NAME = &quot;notification-queue&quot;<br><br>    @Autowired<br>    SqsTemplate sqsTemplate<br><br>    static LocalStackContainer localStack<br><br>    def setupSpec() {<br>        localStack = new LocalStackContainer(<br>                DockerImageName.parse(&quot;localstack/localstack:3.4.0&quot;))<br>                .withServices(LocalStackContainer.Service.SQS)<br>        localStack.start()<br>        localStack.execInContainer(&quot;awslocal&quot;, &quot;sqs&quot;, &quot;create-queue&quot;, &quot;--queue-name&quot;, QUEUE_NAME)<br>    }<br><br>    @DynamicPropertySource<br>    static void setUpAwsSqsProperties(DynamicPropertyRegistry registry) {<br>        registry.add(&quot;spring.cloud.aws.sqs.endpoint&quot;, () -&gt; localStack.getEndpointOverride(LocalStackContainer.Service.SQS).toString())<br>        registry.add(&quot;spring.cloud.aws.credentials.access-key&quot;, () -&gt; localStack.getAccessKey())<br>        registry.add(&quot;spring.cloud.aws.credentials.secret-key&quot;, () -&gt; localStack.getSecretKey())<br>        registry.add(&quot;spring.cloud.aws.region.static&quot;, () -&gt; localStack.getRegion())<br>    }<br><br>    def cleanupSpec() {<br>        if (localStack != null &amp;&amp; localStack.isRunning()) {<br>            localStack.stop()<br>        }<br>    }<br><br>    def &quot;given a valid message sent to the SQS queue, when it is consumed, it returns the same message&quot;() {<br>        given: &quot;a valid message&quot;<br>        def message = &quot;&quot;&quot;{<br>            &quot;userId&quot;:&quot;ID_420&quot;<br>        }&quot;&quot;&quot;<br><br>        when: &quot;the message is sent to the SQS queue&quot;<br>        sqsTemplate.send(QUEUE_NAME, message)<br><br>        then: &quot;the same message is returned&quot;<br>        assert SqsMessageConsumer.check == message<br>    }<br>}</pre><h4>What’s Happening Here?</h4><ol><li><strong>Queue Setup</strong>: We use LocalStackContainer to spin up a Localstack instance with SQS support. The queue is created using awslocal commands within the container.</li><li><strong>Dynamic Properties</strong>: Using @DynamicPropertySource, we configure Spring Boot properties like the SQS endpoint, access key, secret key, and region.</li><li><strong>Sending and Receiving Messages</strong>: The test sends a mock message to the queue using SqsTemplate and asserts that the consumer processed it correctly.</li></ol><h3>Bonus Tip</h3><p>If your project includes testing Kafka consumers (KafkaConsumerTest.java), you might encounter AWS credential-related errors. To resolve this, annotate your KafkaConsumer test classes with</p><pre>@EnableAutoConfiguration(exclude = [SqsAutoConfiguration.class])<br>class KafkaConsumerTest extends Specification{<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d307c6d15b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[General Docker Commands You Should Know]]></title>
            <link>https://medium.com/@harshzone/general-docker-commands-you-should-know-4ad111fa050b?source=rss-322afe6d66ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ad111fa050b</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[docker-command]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker-container]]></category>
            <dc:creator><![CDATA[harshal]]></dc:creator>
            <pubDate>Thu, 15 Aug 2024 22:23:44 GMT</pubDate>
            <atom:updated>2024-08-15T22:23:44.986Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Docker commands" src="https://cdn-images-1.medium.com/max/1024/1*7_iEjEY6XDCMlTggv3LPCQ.png" /></figure><p>Ok, I’m about to share a list of some common Docker commands. And for all you developers out there, trust me, you’ll definitely want to keep these handy. Let’s get started!</p><h4><strong>&gt;&gt; Commands for managing images</strong></h4><p>1. <strong>Get the list of images</strong>: Lists all images stored on your local machine.</p><pre> $ docker images ls <br> $ docker images </pre><p><strong>2.</strong> <strong>Get the list of Image IDs</strong></p><pre>$ docker images --quiet<br>$ docker images -q </pre><p><strong>3. Pull an image: </strong>Download an image from a Docker registry (like Docker Hub) to your local machine.</p><pre>$ docker image pull &lt;image name&gt;<br>$ docker pull &lt;image name&gt;</pre><p><strong>4. Push an image: </strong>Pushes an image to Docker registry (like Docker Hub)</p><pre>$ docker image push &lt;image name&gt;<br>$ docker push &lt;image name&gt;</pre><p><strong>5. Get information about an image: </strong>Provides detailed information about the image</p><pre>$ docker image inspect &lt;image name&gt;<br>$ docker inspect &lt;image name&gt;</pre><p><strong>6. Create a new image from dockerfile</strong></p><pre> $ docker build &lt;path to docker file&gt;</pre><pre>$ docker build -t myapp .<br> # Builds an image named &#39;myapp&#39; from a Dockerfile in the current directory.<br> # -t: tag (image name)<br> # . here means Dockerfile exists in the current directory</pre><p><strong>7. Remove an image from local storage</strong></p><pre>$ docker rmi &lt;image-id&gt;</pre><p><strong>8. Delete empty/unreferenced images</strong></p><pre>$ docker image prune</pre><h4>&gt;&gt; Container commands</h4><ol><li><strong>Get the list of running containers</strong></li></ol><pre>$ docker ps<br># get the list of all containers (running and stopped)<br>$ docker ps -a    </pre><p><strong>2.</strong> <strong>run a new container</strong></p><pre>$ docker run &lt;image name&gt;<br># starts the container in detached mode meaning it runs in the background.<br>$ docker run -d &lt;image name&gt;                 <br># sets the name to the container<br>$ docker run --name mycontainer &lt;image name&gt;  <br># forward the port 8080: source port (machine),80 : destination port (container)<br>$ docker run -d -p 8080:80 &lt;image name&gt;       </pre><p><strong>3. Stop a running container</strong></p><pre>$ docker stop &lt;container id/ name&gt;</pre><p><strong>4. start a new container</strong></p><pre>$ docker start &lt;container id/ name&gt;</pre><p><strong>5. Removes the container</strong></p><pre># remove a stopped container<br>$ docker rm &lt;container id/name&gt; <br># remove a running container<br>$ docker rm --force &lt;container id/name&gt; </pre><p><strong>6. execute any command inside running container</strong></p><pre> $ docker exec &lt;container id/name&gt; &lt;command&gt;<br> # This command opens a Bash shell inside the &quot;mycontainer&quot; container, <br> # allowing you to run commands in a terminal inside the container.<br> $ docker exec -it mycontainer /bin/bash <br> # run date command inside a container<br> $ docker exec mycontainer date </pre><p><strong>7. Get the details of a container</strong></p><pre>$ docker inspect &lt;container id/name&gt;</pre><p><strong>8. get the logs from container</strong></p><pre>$ docker logs &lt;container id/name&gt;<br># get the logs as generated (continuous)<br>$ docker logs -f &lt;container id/name&gt; </pre><p><strong>9. Kill the container</strong></p><pre>$ docker kill &lt;container id/name&gt;</pre><h4>&gt;&gt; start a mysql container</h4><ul><li><strong>-e MYSQL_ROOT_PASSWORD=root</strong>: Sets an environment variable inside the container. Here, it sets the MySQL root user’s password to ‘root’. This is necessary for MySQL containers as it sets the initial root password for the database.</li><li><strong>- -name: </strong>sets the name to the container.</li></ul><pre>$ docker run -itd -p 3306:3306 --name mydb -e MYSQL_ROOT_PASSWORD=root mysql</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ad111fa050b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>