<?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 Emre Demircan on Medium]]></title>
        <description><![CDATA[Stories by Emre Demircan on Medium]]></description>
        <link>https://medium.com/@edemircan?source=rss-752e89de810d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*40iWf4zIAdG52Ebb</url>
            <title>Stories by Emre Demircan on Medium</title>
            <link>https://medium.com/@edemircan?source=rss-752e89de810d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 14:28:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@edemircan/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[So what is a Forward Deployed Engineer (FDE), anyway?]]></title>
            <link>https://medium.com/@edemircan/so-what-is-a-forward-deployed-engineer-fde-anyway-8a230da6a8b4?source=rss-752e89de810d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a230da6a8b4</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Emre Demircan]]></dc:creator>
            <pubDate>Tue, 04 Aug 2026 15:16:24 GMT</pubDate>
            <atom:updated>2026-08-04T15:16:24.823Z</atom:updated>
            <content:encoded><![CDATA[<p>I keep seeing this term pop up everywhere lately: <strong>Forward Deployed Engineer</strong>, or <strong>FDE</strong>. It’s got this weirdly militaristic ring to it, and honestly that’s part of why it caught my attention in the first place. So I dug into where it came from and why suddenly every AI startup wants one.</p><h3>It started with Palantir</h3><p>Turns out the term comes from Palantir. If you know anything about that company, you know it doesn’t sell software the normal way. Most enterprise software companies build a product, put it in a box (metaphorically), and let a sales team pitch it to whoever will buy. Palantir did something different. They took engineers and physically sent them to the client — a military base, a hospital, wherever the actual work was happening — and had them build software right there, on the spot, around whatever mess the client was dealing with.</p><p>That’s the job. Not writing docs about how the client could theoretically use your API. Actually sitting next to the analyst or the doctor or the soldier, watching them struggle with something, and rewriting the tool that afternoon so it stops being a problem.</p><h3>Part engineer, part consultant, part product manager</h3><p>I think what makes this role interesting is that it doesn’t fit neatly into the boxes we usually put engineers in. You’re writing code, sure, but you’re also half consultant and half product manager. Nobody hands you a roadmap. You figure out what to build by watching someone else’s actual workday and noticing where it breaks down.</p><h3>Why now?</h3><p>Why is this suddenly a thing everyone’s talking about? A couple of reasons, I think.</p><p><strong>Palantir’s rise made people pay attention.</strong> Its stock has been on a tear, and people love reverse-engineering success. That whole “no traditional sales team, just send in the engineers” approach has become one of those case studies everyone in tech wants to dissect.</p><p><strong>AI companies hit a wall.</strong> This is probably the bigger driver. You can build the best model in the world, but the moment it meets a real company’s fifteen-year-old legacy systems and undocumented spreadsheets, things fall apart. A generic chatbot wrapper doesn’t cut it. Someone has to actually go in, understand the mess, and wire the thing together by hand. That someone is increasingly an FDE.</p><p><strong>It just sounds like a more interesting job.</strong> If you’re the type of person who gets bored writing the same CRUD endpoints for six months, being dropped into a new client’s chaos every few weeks is appealing. You get to see how real organizations actually run (badly, usually), and you get paid well for the privilege.</p><h3>The part nobody puts on the recruiting slide</h3><p>There’s a real cost to this too. It means travel. It means your schedule isn’t really yours. It means you have to be the engineer <em>and</em> the diplomat at the same time, in front of a client who might be skeptical you can help at all. That’s not for everyone, and I don’t think it should be romanticized as some universally better way to be an engineer.</p><h3>The takeaway</h3><p>I get why it’s having a moment, though. It’s a pretty honest answer to a problem a lot of companies are quietly facing: building the product was never actually the hard part. Getting it to work inside one specific, messy, human organization — that’s the hard part. FDEs are the people who go do that, one client at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SFSWXHsukaLGfhU2LTHP-Q.png" /></figure><h3>Join the Conversation and Let’s Chat!</h3><p>Hey there, fellow developers and curious minds! 🚀</p><blockquote>Guess what? Your thoughts, experiences, and brilliant ideas matter to me!</blockquote><p>We’re all about building a community of thinkers and problem solvers, and your contribution is like a treasure trove of insights waiting to be discovered. So go ahead, drop a comment, share your experiences, and let’s learn and grow together! 💬</p><p><strong>Support the Journey: Consider Contributing</strong></p><p>If you’ve found this tutorial helpful and wish to express your appreciation, you can support my work by contributing via the “Buy Me A Coffee” platform. Your gesture fuels the creation of more tutorials and resources to help you and others in the developer community.</p><figure><a href="http://buymeacoffee.com/edemircan"><img alt="" src="https://cdn-images-1.medium.com/max/170/1*Dpw8-hNGI2fDmosV4E8DVQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a230da6a8b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The “Double” Trouble: Why Computers are Bad at Math]]></title>
            <link>https://medium.com/@edemircan/the-double-trouble-why-computers-are-bad-at-math-458b6cd6432e?source=rss-752e89de810d------2</link>
            <guid isPermaLink="false">https://medium.com/p/458b6cd6432e</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming-tips]]></category>
            <dc:creator><![CDATA[Emre Demircan]]></dc:creator>
            <pubDate>Wed, 28 Jan 2026 16:28:09 GMT</pubDate>
            <atom:updated>2026-01-28T16:28:09.871Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever felt like your code was gaslighting you? You write a simple calculation, something a second-grader could do, and Java looks you in the eye and says: 0.1 + 0.2 = 0.30000000000000004.</p><p>It feels like a glitch in the matrix, but it’s actually by design. Whether you’re using double or float, you’re dancing with <strong>Floating Point</strong> numbers—and they have a very strange way of seeing the world.</p><h3>1. The Language Barrier: Binary vs. Decimal</h3><p>We live in a Base-10 world (0–9). Computers live in a Base-2 world (0–1).</p><p>Think of it like trying to write the fraction 1/3 in decimal. You get 0.3333… and no matter how many 3s you write, you never <em>quite</em> reach the exact value of 1/3.</p><p>In the computer’s binary world, simple numbers like 0.1 or 0.025 are the equivalent of 1/3. They become infinite repeating fractions in binary. Since the computer doesn’t have infinite memory, it simply “chops it off” at a certain point.</p><h3>2. The “Invisible Noise”</h3><p>When you write double value = 52.825;, the computer cannot store exactly 52.825. It stores the closest possible binary representation, which looks like this internally:</p><blockquote><strong><em>Actual stored value:</em></strong><em> </em><em>52.8250000000000028421709430404007434844970703125</em></blockquote><p>Because that “invisible noise” at the end makes the number <strong>slightly larger</strong> than the mathematical 52.825, the rounding logic thinks: <em>“Oh, this is more than halfway, I must round UP.”</em></p><p>Meanwhile, another number like 3.825 might be stored as 3.824999999999999..., causing it to round <strong>DOWN</strong>.</p><h3>3. The “Classic” Broken Example</h3><p>Want to see this in action? Try running this single line of code in Java:</p><pre>System.out.println(0.1 + 0.2 == 0.3); // Results in: FALSE<br>System.out.println(0.1 + 0.2);        // Results in: 0.30000000000000004</pre><p>To a human, 0.1 + 0.2 is 0.3. To a computer, it’s 0.30000000000000004. In a financial app, this isn’t just a quirk — it’s a liability. Over a million transactions, those “invisible” fractions turn into real-world dollars that go missing.</p><h3>The Golden Rules for Our Team</h3><p>To avoid these bugs, we should follow these two principles for any financial or precision-critical code:</p><h3>Rule #1: Use BigDecimal (And use it right!)</h3><p>BigDecimal is the &quot;adult in the room.&quot; It treats numbers as strings and performs math just like we did in grade school.</p><p><strong>The Trap:</strong> Never pass a double into a BigDecimal constructor.</p><ul><li><strong>Bad:</strong> new BigDecimal(0.1) → You are just bringing the “binary noise” into a bigger room.</li><li><strong>Good:</strong> new BigDecimal(&quot;0.1&quot;) or BigDecimal.valueOf(0.1)</li></ul><p>In Java, BigDecimal.valueOf() uses Double.toString() internally, which gives you the shortest decimal representation of that double—effectively filtering out the binary approximation errors and giving you the clean decimal you expected.</p><h3>Rule #2: Be the Boss of Rounding</h3><p>Java’s DecimalFormat often defaults to HALF_EVEN (also known as <strong>Banker’s Rounding</strong>). It rounds to the nearest even number to reduce cumulative error in large datasets. It’s smart, but if your boss expects &quot;standard&quot; rounding (where .5 always goes up), you’ll get a stern email.</p><p><strong>The Correct Way:</strong></p><ol><li>Convert safely to BigDecimal</li><li>Set your scale and Rounding mode</li><li>Keep it as a BigDecimal as long as possible ;)</li></ol><pre>double inputFromLegacySystem = 52.825;<br><br>// 1. Convert safely using valueOf()<br>BigDecimal amount = BigDecimal.valueOf(inputFromLegacySystem);<br><br>// 2. Set your scale and rounding mode explicitly<br>BigDecimal rounded = amount.setScale(2, RoundingMode.HALF_UP);<br><br>// 3. Keep it as a BigDecimal for as long as possible!<br>System.out.println(&quot;The precise result: &quot; + rounded);</pre><h3>When NOT to Use BigDecimal</h3><p>Don’t reach for BigDecimal in every situation. For <strong>gaming, graphics, scientific simulations, or machine learning</strong>, where you&#39;re doing millions of calculations per second and small rounding errors are acceptable, stick with double or float. The performance difference is massive -BigDecimal can be 100x slower.</p><p><strong>Rule of thumb:</strong> If you’re dealing with money, measurements that matter legally, or values that will be displayed to users as exact figures, use BigDecimal. If you&#39;re calculating physics, rendering graphics, or doing statistical analysis, double is your friend.</p><h3>Summary Table: Which one should you use?</h3><figure><img alt="A technical comparison infographic between Java Double/Float and BigDecimal. The chart evaluates five categories: Speed: Double is ‘Blazing Fast’ (hardware-native), while BigDecimal is ‘Slower’ (software-based object creation). Precision: Double is ‘Approximate’ (binary floating-point), while BigDecimal is ‘Exact’ (user-defined scale). Best For: Double is recommended for Graphics, Physics, and Big Data; BigDecimal is recommended for Financial, Taxes, and Legal Metrics. Memory: Double uses ‘" src="https://cdn-images-1.medium.com/max/1024/1*jMzSEByM0sPylR59WV9qdw.png" /><figcaption>The trade-offs between performance and precision in Java</figcaption></figure><h3>The Bottom Line</h3><p>Floating-point math isn’t broken — it’s just optimized for a different world than ours. When precision matters more than speed, treat numbers as what they really are: decimal values, not binary approximations. Your users’ bank accounts will thank you.</p><h3>Join the Conversation and Let’s Chat!</h3><p>Hey there, fellow developers and curious minds! 🚀</p><blockquote>Guess what? Your thoughts, experiences, and brilliant ideas matter to me!</blockquote><p>We’re all about building a community of thinkers and problem solvers, and your contribution is like a treasure trove of insights waiting to be discovered. So go ahead, drop a comment, share your experiences, and let’s learn and grow together! 💬</p><p><strong>Support the Journey: Consider Contributing</strong></p><p>If you’ve found this tutorial helpful and wish to express your appreciation, you can support my work by contributing via the “Buy Me A Coffee” platform. Your gesture fuels the creation of more tutorials and resources to help you and others in the developer community.</p><figure><a href="http://buymeacoffee.com/edemircan"><img alt="" src="https://cdn-images-1.medium.com/max/170/1*Dpw8-hNGI2fDmosV4E8DVQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=458b6cd6432e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make It Work, Make It Right, Make It Fast: The Three Steps to Quality Code]]></title>
            <link>https://medium.com/@edemircan/make-it-work-make-it-right-make-it-fast-the-three-steps-to-quality-code-e452160595c9?source=rss-752e89de810d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e452160595c9</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[coding-best-practices]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Emre Demircan]]></dc:creator>
            <pubDate>Thu, 13 Feb 2025 16:31:36 GMT</pubDate>
            <atom:updated>2025-02-13T16:31:36.560Z</atom:updated>
            <content:encoded><![CDATA[<p>Every developer has been there — facing a complex problem, racing against deadlines, and trying to get the code up and running. In the rush, cutting corners or optimizing too early might be tempting. That’s where I’d like to introduce a principle to save you from pulling your hair out:</p><blockquote><strong><em>Make it work</em></strong>, <strong><em>make it right</em></strong>, and <strong><em>make it fast</em></strong>.</blockquote><p>This simple yet powerful principle (coined by Kent Beck) helps developers write high-quality, maintainable code without getting lost in premature optimization or messy quick fixes. Let’s break it down:</p><figure><img alt="Beck’s Principle" src="https://cdn-images-1.medium.com/max/1024/1*8-MSSdiz1hMuojO3e3et0w.png" /></figure><h3>Step 1: Make It Work</h3><p>Think of this as building your minimum viable product (MVP). Your first goal is simply to solve the problem at hand. It’s like sketching out a rough draft — it might not be pretty, but it gets the job done. During this phase, don’t worry too much about optimization or elegant solutions. Focus on writing code that produces the correct output.</p><p>This doesn’t mean writing careless, sloppy code. It means focusing on solving the problem before worrying about structure or speed. Let’s not forget that if your feature isn’t working, it doesn’t matter how optimized or beautiful your code is.</p><p><strong>Tip:</strong> Write tests early to validate that your solution works. Even basic unit tests can save you from unexpected issues down the line.</p><h3>Step 2: Make It Right</h3><p>Now comes the fun part — refactoring! This is where we roll up our sleeves and transform our working code into something we’d be proud to show other developers. We’re talking about:</p><ul><li>Is the code easy to understand?</li><li>Are there unnecessary complexities that could be simplified?</li><li>Does it follow the project’s coding standards?</li></ul><p>Good code is like a good book, others should be able to read and understand it without struggling.</p><h3>Step 3: Make It Fast</h3><p>Optimization comes last. Now that the code is both functional and clean, you can focus on performance improvements if needed. Profile your code, identify bottlenecks, and optimize only where it truly matters.</p><p>A common mistake is trying to make things fast before making them right. This often leads to overcomplicated, hard-to-maintain code that sacrifices clarity for minor performance gains.</p><p><strong>Tip:</strong> Measure before optimizing. Use tools like profilers and benchmarks to ensure you’re improving actual bottlenecks instead of guessing.</p><h3>Real-world Example</h3><p>Let’s say you’re building a customer data processing system. In step one, you might write a simple loop that processes records sequentially. During the “<em>make it right</em>” phase, you’d reorganize the code into cleaner functions and add proper validation. Finally, in the “<em>make it fast</em>” stage, you might implement batch processing or parallelization — but only if performance testing shows it’s necessary.</p><h3>Wrapping Up</h3><p>Remember, this approach isn’t about perfectionism, it’s about pragmatism. Each step builds upon the previous one, creating a solid foundation for maintainable code.</p><p>By following these steps in order, we avoid the common trap of over-engineering solutions before we even know if they work. It’s like building a house — you need the foundation before you can worry about the crown molding!</p><p>What’s your experience with this approach? Have you found yourself trying to optimize code before it even works? We’ve all been there, and learning to follow this progression is part of growing as a developer.</p><h3>Join the Conversation and Let’s Chat!</h3><p>Hey there, fellow developers and curious minds! 🚀</p><blockquote>Guess what? Your thoughts, experiences, and brilliant ideas matter to me!</blockquote><p>We’re all about building a community of thinkers and problem solvers, and your contribution is like a treasure trove of insights waiting to be discovered. So go ahead, drop a comment, share your experiences, and let’s learn and grow together! 💬</p><p><strong>Support the Journey: Consider Contributing</strong></p><p>If you’ve found this tutorial helpful and wish to express your appreciation, you can support my work by contributing via the “Buy Me A Coffee” platform. Your gesture fuels the creation of more tutorials and resources to help you and others in the developer community.</p><figure><a href="http://buymeacoffee.com/edemircan"><img alt="" src="https://cdn-images-1.medium.com/max/170/1*Dpw8-hNGI2fDmosV4E8DVQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e452160595c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Basics: Mastering Advanced Java Enum Techniques]]></title>
            <link>https://medium.com/@edemircan/beyond-the-basics-mastering-advanced-java-enum-techniques-a24d148f3a78?source=rss-752e89de810d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a24d148f3a78</guid>
            <category><![CDATA[advanced-java-techniques]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[coding-best-practices]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Emre Demircan]]></dc:creator>
            <pubDate>Thu, 05 Sep 2024 07:53:17 GMT</pubDate>
            <atom:updated>2024-09-05T07:53:17.376Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Diagram showing the main characteristics of Java enums: Fixed Values, Type Safety, Custom Data, Methods Support, Singleton Pattern, and Interface Use." src="https://cdn-images-1.medium.com/max/1024/1*0do7QPwoTq0qY1tjbHp8Cg.png" /></figure><h3>Table Of Contents</h3><p>· <a href="#f4b5">Introduction</a><br>· <a href="#eccb">Custom Enum Constructors: Initializing with Purpose</a><br>· <a href="#b11a">Enum Collections: Optimizing with EnumSet and EnumMap</a><br>· <a href="#8333">Implementing Interfaces and Extending Enums: Enabling Polymorphic Behavior</a><br>· <a href="#406d">Enum Singleton Pattern: Thread-Safe with Ease</a><br>· <a href="#e0a9">Advanced Enum Switching: Making Your Switch Statements More Flexible</a><br>· <a href="#f3f4">Reflection and Enums: Navigating the Possibilities</a><br>· <a href="#9d57">Conclusion</a><br>· <a href="#5494">Join the Conversation and Let’s Chat!</a></p><h3>Introduction</h3><p>If you’ve been using Java for a while, you’ve probably worked with enums to represent a set of constants. But what if I told you there’s much more to enums than meets the eye? Beyond their basic functionality, enums in Java offer a whole suite of advanced techniques that can take your code from good to great. In this article, we will try to explore some of these hidden features and best practices, showing you how to make the most of enums and turn them into powerful tools for our projects.</p><h3>Custom Enum Constructors: Initializing with Purpose</h3><p>At first glance, enums look like simple constants, but they’re capable of so much more. One of the coolest tricks is using custom constructors to pass additional data into your enum constants. Imagine you’re building an app that handles various shipping methods, each with its own cost and delivery time. You could create an enum for that, but to make it truly dynamic, you’d pass the cost and delivery time into each enum constant.</p><pre>public enum ShippingMethod {<br>    STANDARD(5, 7),<br>    EXPRESS(10, 3),<br>    OVERNIGHT(20, 1);<br><br>    private final int cost;<br>    private final int deliveryDays;<br><br>    ShippingMethod(int cost, int deliveryDays) {<br>        this.cost = cost;<br>        this.deliveryDays = deliveryDays;<br>    }<br> ...<br>}</pre><p>With this, each enum now has its own specific properties. It’s a simple yet powerful way to make your enums more flexible and meaningful.</p><h3>Enum Collections: Optimizing with EnumSet and EnumMap</h3><p>Did you know that Java has special collection classes built specifically for enums? Enter <a href="http://ocs/api/java.base/java/util/class-use/EnumSet.html">EnumSet</a> and <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/class-use/EnumMap.html">EnumMap</a>. These classes are optimized for enums and offer much better performance and memory efficiency compared to traditional collections.</p><p>For example, if you need a set of enum constants that represent specific permissions in an app, EnumSet is your go-to:</p><pre>EnumSet&lt;Permission&gt; permissions = EnumSet.of(Permission.READ, Permission.WRITE);</pre><p>Similarly, EnumMap pairs enums with values. This could come in handy for something like mapping error codes to user-friendly messages:</p><pre>EnumMap&lt;ErrorCode, String&gt; errorMessages = new EnumMap&lt;&gt;(ErrorCode.class);<br>errorMessages.put(ErrorCode.NOT_FOUND, &quot;The requested resource was not found.&quot;);<br>errorMessages.put(ErrorCode.SERVER_ERROR, &quot;An internal server error occurred.&quot;);</pre><p>By using these specialized collections, your code becomes cleaner, faster, and more memory-efficient.</p><h3>Implementing Interfaces and Extending Enums: Enabling Polymorphic Behavior</h3><p>Did you know that enums can implement interfaces? This means they can behave polymorphically, just like any other class in Java. It opens up some exciting possibilities when you need to handle different behaviors in your enums.</p><p>Let’s say you’re building a payment system with different methods like credit cards, PayPal, and bank transfers. Each payment method needs to implement a PaymentProcessor interface with a processPayment method. With enums, this is straightforward:</p><pre>public enum PaymentMethod implements PaymentProcessor {<br>    CREDIT_CARD {<br>        @Override<br>        public void processPayment() {<br>            System.out.println(&quot;Processing credit card payment&quot;);<br>        }<br>    },<br>    PAYPAL {<br>        @Override<br>        public void processPayment() {<br>            System.out.println(&quot;Processing PayPal payment&quot;);<br>        }<br>    },<br>    BANK_TRANSFER {<br>        @Override<br>        public void processPayment() {<br>            System.out.println(&quot;Processing bank transfer&quot;);<br>        }<br>    };<br>}</pre><p>With this setup, each enum constant behaves like a unique class, yet everything remains neatly organized in one place.</p><h3>Enum Singleton Pattern: Thread-Safe with Ease</h3><p>You’ve probably encountered the singleton pattern, where a class is designed to have only one instance. It’s a popular design pattern, but what if I told you enums could do also this? Using enums for singletons is both concise and inherently thread-safe.</p><pre>public enum Logger {<br>    INSTANCE;<br><br>    public void log(String message) {<br>        System.out.println(message);<br>    }<br>}</pre><p>By using an enum, you avoid issues related to lazy initialization, synchronization, or cloning. It’s an elegant solution, and it’s a good fit for scenarios where you need a guaranteed single instance.</p><h3>Advanced Enum Switching: Making Your Switch Statements More Flexible</h3><p>Switching on enums is something most Java developers do. But what if you need something more dynamic? With Java streams and mapping techniques, you can enhance flexibility and make your switch statements cleaner and more maintainable.</p><p>For instance, instead of a standard switch, you could use streams to map each enum to a corresponding action:</p><pre>Map&lt;ShippingMethod, Runnable&gt; actions = new EnumMap&lt;&gt;(ShippingMethod.class);<br>actions.put(ShippingMethod.STANDARD, () -&gt; System.out.println(&quot;Standard shipping selected&quot;));<br>actions.put(ShippingMethod.EXPRESS, () -&gt; System.out.println(&quot;Express shipping selected&quot;));<br><br>ShippingMethod method = ShippingMethod.EXPRESS;<br>actions.getOrDefault(method, () -&gt; System.out.println(&quot;Unknown method&quot;)).run();</pre><p>This approach makes it easier to extend or modify your logic, especially in larger projects.</p><h3>Reflection and Enums: Navigating the Possibilities</h3><p>Reflection is a powerful tool in Java, and when combined with enums, it opens the door to even more dynamic behavior. You can use reflection to inspect or manipulate enum constants, which can be useful in certain scenarios like deserialization or dynamic code generation.</p><p>Here’s a quick look at how you can access all enum constants using reflection:</p><pre>Class&lt;ShippingMethod&gt; enumClass = ShippingMethod.class;<br>for (ShippingMethod method : enumClass.getEnumConstants()) {<br>    System.out.println(method.name() + &quot; costs $&quot; + method.getCost());<br>}</pre><p>While reflection can be incredibly powerful, it’s important to use it judiciously. Overuse can make your code harder to maintain and understand, so be sure to weigh the trade-offs.</p><h3><strong>Conclusion</strong></h3><p>Java enums are far more than just simple constants. They’re versatile, dynamic, and capable of solving complex problems elegantly. By mastering these advanced techniques, you can unlock a whole new level of sophistication in your code. Whether you’re optimizing performance with EnumSet, implementing polymorphic behavior, or even crafting thread-safe singletons, enums offer an incredible amount of flexibility and power. So next time you reach for an enum, remember—they’re capable of much more than you might think!</p><h3>Join the Conversation and Let’s Chat!</h3><p>Hey there, fellow developers and curious minds! 🚀</p><blockquote>Guess what? Your thoughts, experiences, and brilliant ideas matter to me!</blockquote><p>We’re all about building a community of thinkers and problem solvers, and your contribution is like a treasure trove of insights waiting to be discovered. So go ahead, drop a comment, share your experiences, and let’s learn and grow together! 💬</p><p><strong>Support the Journey: Consider Contributing</strong></p><p>If you’ve found this article helpful and wish to express your appreciation, you can support my work by contributing via the “Buy Me A Coffee” platform. Your gesture fuels the creation of more tutorials and resources to help you and others in the developer community.</p><figure><a href="http://buymeacoffee.com/edemircan"><img alt="" src="https://cdn-images-1.medium.com/max/170/1*Dpw8-hNGI2fDmosV4E8DVQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a24d148f3a78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Development: Spring Boot 3.1 and Testcontainers Desktop]]></title>
            <link>https://medium.com/@edemircan/simplifying-development-spring-boot-3-1-and-testcontainers-desktop-9b2ea465f21b?source=rss-752e89de810d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b2ea465f21b</guid>
            <category><![CDATA[testcontainer]]></category>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Emre Demircan]]></dc:creator>
            <pubDate>Thu, 24 Aug 2023 17:19:38 GMT</pubDate>
            <atom:updated>2023-08-24T17:19:38.658Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kTrTI3Dt5WO1tg7qGLkJjw.png" /></figure><h3>Table Of Contents</h3><p>· <a href="#cffa">Introduction</a><br>· <a href="#55fe">The Importance of Testing with Real Dependencies</a><br>· <a href="#6e87">Introducing Testcontainers: A Game-Changer for Integration Testing</a><br>· <a href="#3247">Testcontainers Desktop: Revolutionizing Dev and Testing</a><br> ∘ — <a href="#e408">Switching Container Runtimes</a><br> ∘ — <a href="#139e">Using Fixed Ports for Development Services</a><br> ∘ — <a href="#c46b">Reusable Containers for Speeding up Development</a><br> ∘ — <a href="#1ed4">Testcontainers Cloud Integration</a><br>· <a href="#3c01">Testcontainers Evolution in Spring Boot 3.1</a><br> ∘ — <a href="#c01d">The New @ServiceConnection Annotation</a><br> ∘ — <a href="#21a7">Leveraging Testcontainers at Development Time</a><br>· <a href="#2994">Conclusion</a><br> ∘ — <a href="#e8d2">Join the Testcontainers Desktop Live Stream</a>🚀</p><h3>Introduction</h3><p>In the fast-paced world of software development, the ability to release new features quickly is crucial to staying ahead of the competition. To achieve this, having a robust CI/CD infrastructure that can automatically build, test, and release software with minimal human intervention is essential. At the heart of a comprehensive automated test suite lies the key to releasing software with confidence: integration testing with real dependencies. This is where Testcontainers comes into play, revolutionizing the way we write integration tests by providing a seamless experience similar to writing unit tests. In this article, we will delve into the enhancements brought by Spring 3.1.0 and the significant advantages of Testcontainers Desktop, shedding light on the next chapter in integration testing and local development.</p><h3>The Importance of Testing with Real Dependencies</h3><p>When writing integration tests, it is crucial to test with the same type of real dependencies that your software product would use in production. While it may be tempting to use mocks or in-memory variations of these services, they often fail to capture the true behavior and potential issues that can arise when interacting with the actual dependencies.</p><p>Imagine you’re developing a software application reliant on a Kafka message broker for real-time data processing and Elasticsearch for search capabilities. While testing, you might be tempted to use simplified in-memory alternatives for convenience. However, this approach can introduce two significant issues:</p><p><strong>False Negatives:</strong> In the case of Kafka, the simplified in-memory queue lacks advanced features like partitioning and replication. This can make your code appear functional during testing but vulnerable to Kafka’s complexities in production. Similar issues can arise when testing with Elasticsearch.</p><p><strong>False Positives:</strong> On the flip side, code that functions seamlessly with the in-memory queue might falter when dealing with Kafka, causing hidden problems that only surface when your software is deployed live. Conversely, code that works with the in-memory substitute may also stumble with Elasticsearch, leading to unnoticed issues until the production stage.</p><p>To mitigate these issues and ensure comprehensive testing, it is imperative to test with the same type of dependencies that will be used in production. This is where Testcontainers shines, enabling you to test your application with real dependencies effortlessly.</p><h3>Introducing Testcontainers: A Game-Changer for Integration Testing</h3><p><a href="https://testcontainers.com/">Testcontainers</a> is a powerful library that empowers developers to write integration tests using real dependencies, simulating the production environment. By seamlessly integrating with Docker, Testcontainers simplifies the process of setting up and managing the necessary containers for your tests. Instead of relying on mocks or in-memory variations, Testcontainers allows you to test against the actual services your application will interact with, ensuring reliable and accurate results.</p><p>To give you a taste of how Testcontainers enables you to write tests that instill confidence in your software, let’s take a closer look at a simple example using Spring Boot and Kafka.</p><pre>@SpringBootTest<br>@Import(ContainerConfig.class)<br>public class ContainerTest {<br><br>    @Autowired<br>    KafkaContainer kafkaContainer;<br><br>    // Test methods<br>}</pre><pre>@TestConfiguration(proxyBeanMethods = false)<br>public class ContainerConfig {<br>    private static final String KAFKA_VERSION = &quot;7.2.6&quot;;<br><br>    @Bean<br>    @ServiceConnection<br>    KafkaContainer kafkaContainer() {<br>        return new KafkaContainer(DockerImageName.parse(&quot;confluentinc/cp-kafka&quot;)<br>            .withTag(KAFKA_VERSION));<br>    }<br>}</pre><p>This code represents an integration test class called ContainerTest. It&#39;s configured with Spring Boot&#39;s @SpringBootTest annotation, which sets up a Spring Boot application context for testing, and it imports the ContainerConfig class, which contains the configuration for Testcontainers. Within this test class, we can easily inject our kafkaContainer.</p><h3>Testcontainers Desktop: Revolutionizing Dev and Testing</h3><p>While Testcontainers provides a robust command-line interface for managing containers, the recently introduced Testcontainers Desktop takes the experience to a whole new level. Testcontainers Desktop is a free companion app that simplifies local development and testing with real dependencies. Let’s explore some of its key features and how they enhance the development workflow.</p><h4>Switching Container Runtimes</h4><p>One of the standout features of Testcontainers Desktop is its ability to automatically detect and utilize your locally installed Docker runtime. It ensures a smooth experience without any additional configuration. Moreover, Testcontainers Desktop allows you to switch between different Docker runtimes, enabling you to choose the most suitable one for your development environment. You can switch containers by clicking <em>Containers running locally -&gt; [Desired container]</em></p><h4>Using Fixed Ports for Development Services</h4><p>During development, it is often necessary to connect to application dependencies such as databases and message brokers using client tools to verify data or debug issues. By default, Testcontainers maps container ports to random available ports on the host machine to avoid port conflicts. However, this can make it cumbersome to determine which port is assigned to a specific container and establish a connection to it, especially during the development phase.</p><p>Testcontainers Desktop simplifies this process by introducing fixed ports for container services. With fixed ports, you can always connect to your application dependencies through the same configured port, ensuring a consistent experience. You can define fixed ports in the config file: <em>Testcontainers Desktop → Services → Open config location</em></p><p>For example, if you use Elasticsearch as your search engine and have configured Testcontainers Desktop to use port 9200 for Elasticsearch, you can configure Elasticsearch URI inapplication.propertieswithout worrying about randomness.</p><pre>spring.elasticsearch.uris=http://localhost:9200</pre><p>This feature greatly streamlines the development process, allowing you to connect to your containers and interact with them using familiar tools, all without the hassle of determining randomly assigned ports. This level of consistency and ease of use can significantly enhance your development workflow.</p><h4><strong>Reusable Containers for Speeding up Development</strong></h4><p>One of the challenges developers face during development is the need to frequently modify code and quickly verify the behavior of their application. However, recreating containers for every code change can slow down the feedback cycle and hinder productivity. To address this challenge, Testcontainers introduced the concept of reusable containers.</p><p>When using Testcontainers Desktop, the reusable containers feature is enabled by default in your development environment. This feature allows you to configure containers to be reusable, meaning that if a container with the same configuration already exists, it will be reused instead of creating a new one. This can significantly speed up testing and local development by eliminating the need to recreate containers for every code change. If you want to change the default behavior: <em>Preferences -&gt; Enable reusable containers</em></p><p>To enable reusable containers with Testcontainers for Java, you can simply add the .withReuse(true) configuration when spinning up a container. For example:</p><pre>KafkaContainer kafkaContainer() {<br>    return new KafkaContainer(DockerImageName.parse(&quot;confluentinc/cp-kafka&quot;)<br>        .withTag(&quot;7.2.6&quot;))<br>        .withReuse(true);<br>}</pre><p>With this configuration, Testcontainers will calculate a hash based on the container’s configuration. If another container with the same configuration is requested, Testcontainers will reuse the existing container, saving time and resources.</p><h4>Testcontainers Cloud Integration</h4><p>In addition to its local development capabilities, Testcontainers Desktop seamlessly integrates with Testcontainers Cloud, a cloud-based service that allows you to run containers in the cloud instead of on your local machine. By creating a free Testcontainers Cloud account, you can leverage the power of cloud computing to save local resources and execute your integration tests in a distributed environment. This integration enables you to scale your testing infrastructure effortlessly and run tests in parallel, further enhancing the speed and efficiency of your development workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eW0XXeaYzLZagUifrqoEKA.png" /></figure><h3>Testcontainers Evolution in Spring Boot 3.1</h3><p>Spring Boot 3.1 has brought significant enhancements to its Testcontainers support, making it even more versatile and user-friendly. In the following sections, we’ll delve into these improvements and set up a small stage using Kafka and Elasticsearch containers.</p><h4>The New @ServiceConnection Annotation</h4><p>In order to make the picture clear, let’s start with how we could define a Kafkacontainer before Spring 3.1:</p><pre>@Testcontainers<br>@SpringBootTest<br>class KafkaTestcontainersTest {<br><br>    @Container<br>    static KafkaContainer kafkaContainer = new KafkaContainer(DockerImageName.parse(&quot;confluentinc/cp-kafka:latest&quot;));<br><br>    @DynamicPropertySource<br>    static void kafkaProperties(DynamicPropertyRegistry registry) {<br>        registry.add(&quot;spring.kafka.bootstrap-servers&quot;, kafkaContainer::getBootstrapServers);<br>    }<br>}</pre><p>Newly introduced @ServiceConnection annotation simplifies integration testing even further. This annotation can be applied to the container instance fields in your tests.</p><pre>@Testcontainers<br>@SpringBootTest<br>class KafkaTestcontainersTest {<br><br>    @Container<br>    @ServiceConnection<br>    static KafkaContainer kafkaContainer = new KafkaContainer(DockerImageName.parse(&quot;confluentinc/cp-kafka:latest&quot;));<br><br>}</pre><p>By using @ServiceConnection, you can eliminate the need for the @DynamicPropertySource code, streamlining your tests. This annotation automatically discovers the type of container being used and creates a corresponding ConnectionDetails bean.</p><h4>Leveraging Testcontainers at Development Time</h4><p>One of the exciting additions in Spring Boot 3.1 is the ability to use Testcontainers during development, not just for integration tests. Typically, external services like PostgreSQL, Kafka, or Elasticsearch are set up manually before code development or using tools like Docker Compose.</p><p>Now, you can leverage Testcontainers for these services during development as well. This approach streamlines your development workflow by ensuring that the services your application depends on are always available.</p><p>To use Testcontainers at development time, keep the Testcontainers dependency in the test scope and create a test-specific main method:</p><pre>public class TestMyApplication {<br><br>    public static void main(String[] args) {<br>        SpringApplication.from(MyApplication::main)<br>            .with(ContainerConfig.class)<br>            .run(args);<br>    }<br>}</pre><p>This test-main method delegates to your actual production main method using SpringApplication.from. With this setup, you can define beans for the Testcontainers you need in a @TestConfiguration:</p><pre>@TestConfiguration(proxyBeanMethods = false)<br>public class ContainerConfig {<br>    private static final String ELASTICSEARCH_VERSION = &quot;8.9.0&quot;;<br>    private static final String KAFKA_VERSION = &quot;7.2.6.arm64&quot;;<br><br>    @Bean<br>    @ServiceConnection<br>    KafkaContainer kafkaContainer() {<br>        return new KafkaContainer(DockerImageName.parse(&quot;confluentinc/cp-kafka&quot;)<br>            .withTag(KAFKA_VERSION))<br>            .withReuse(true);<br>    }<br><br>    @Bean<br>    @ServiceConnection<br>    ElasticsearchContainer elasticsearchContainer() {<br>        ElasticsearchContainer elasticsearchContainer = new ElasticsearchContainer(DockerImageName.parse(&quot;docker.elastic.co/elasticsearch/elasticsearch&quot;)<br>            .withTag(ELASTICSEARCH_VERSION))<br>            .withReuse(true);<br>        return elasticsearchContainer;<br>    }<br>}</pre><p>Note the use of @ServiceConnection to instruct Spring Boot to automatically establish a connection to the service running in the container. Spring Boot takes care of starting and shutting down these containers in sync with your application.</p><p>Now, when you start the test-main method from your integrated development environment (IDE), the containers will start automatically, and Spring Boot will establish connections to them. No additional configuration properties are needed, and Spring Boot ensures the containers are gracefully shut down when your application stops.</p><h3>Conclusion</h3><p>The combination of Spring 3.1.0 and Testcontainers Desktop has opened up a new chapter in integration testing and local development. Testcontainers has redefined integration testing, blending real dependencies into the development process. With Spring Boot 3.1, these capabilities are even more robust. As we move forward, this combination empowers us to build more reliable, efficient, and confident software.</p><h4>Join the Testcontainers Desktop Live Stream</h4><p>Mark your calendars for an exciting event! On August 30, 2023, there will be a <a href="https://www.youtube.com/watch?v=PcSWI4W5jWY"><em>live streaming session</em></a> on Testcontainers Desktop. Oleg Selajev will be there to provide demos and answer your questions in real-time. If you can’t make it to the live event, don’t worry. You can still participate by submitting your questions in the <a href="https://slack.testcontainers.org/"><strong><em>Slack</em></strong></a> community, and the recording of the event will be available for you to watch at your convenience.</p><h3>Join the Conversation and Let’s Chat!</h3><p>Hey there, fellow developers and curious minds! 🚀</p><blockquote>Guess what? Your thoughts, experiences, and brilliant ideas matter to me!</blockquote><p>We’re all about building a community of thinkers and problem solvers, and your contribution is like a treasure trove of insights waiting to be discovered. So go ahead, drop a comment, share your experiences, and let’s learn and grow together! 💬🚀</p><p><strong>Support the Journey: Consider Contributing</strong></p><p>If you’ve found this tutorial helpful and wish to express your appreciation, you can support my work by contributing via the “Buy Me A Coffee” platform. Your gesture fuels the creation of more tutorials and resources to help you and others in the developer community.</p><figure><a href="http://buymeacoffee.com/edemircan"><img alt="" src="https://cdn-images-1.medium.com/max/170/1*Dpw8-hNGI2fDmosV4E8DVQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b2ea465f21b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Empowering Spring Boot: OpenAI-Driven Error Management]]></title>
            <link>https://pub.aimind.so/empowering-spring-boot-openai-driven-error-management-41afc929fc21?source=rss-752e89de810d------2</link>
            <guid isPermaLink="false">https://medium.com/p/41afc929fc21</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[error-management]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[error-handling]]></category>
            <dc:creator><![CDATA[Emre Demircan]]></dc:creator>
            <pubDate>Wed, 16 Aug 2023 06:07:03 GMT</pubDate>
            <atom:updated>2023-08-18T14:44:09.408Z</atom:updated>
            <content:encoded><![CDATA[<h3>Table Of Contents</h3><p>· <a href="#0a46">Introduction</a><br>· <a href="#dfbb">Understanding Error Handling in Spring Boot</a><br>· <a href="#597c">Integrating OpenAI for Enhanced Error Responses</a><br>· <a href="#e61a">Implementing Error Handling with OpenAI</a><br>· <a href="#49c8">Running the Tutorial Application and Experimenting</a></p><h3>Introduction</h3><p>Handling errors and providing meaningful feedback are essential aspects of building robust and user-friendly applications, be it web applications, microservices, or beyond. Spring Boot equips developers with powerful tools and frameworks for effective error handling, resulting in smoother user experiences and more resilient systems. In this article, we’ll dive into the relatively complex world of error handling with Spring Boot. We’ll analyze concepts like global error handling, custom exception classes, and tailored error responses, and break them down into easily digestible steps. But that’s not all: get ready to improve your error-handling strategies by harnessing the intelligence of OpenAI.</p><p>By partnering with OpenAI, we’re able to turn everyday error messages into insightful solutions. From configuring OpenAI features to managing responses, I’m prepared to walk you through every facet. So if you’re ready to learn, let’s decipher the complexities of error management and ensure your applications remain resilient in the face of adversity.</p><h3>Understanding Error Handling in Spring Boot</h3><p>In the context of Spring Boot, exceptions are mainly categorized into two types: client errors 4xx (e.g., invalid input) and server errors 5xx (e.g., server malfunction). Let’s give three examples for each to get familiar with the context:</p><p><strong>Client Errors (4xx):</strong></p><p><em>400 Bad Request</em><strong><em>:</em></strong> This error occurs when the client’s request is malformed or contains invalid data, such as missing parameters or incorrect formatting. <strong>Ex</strong>: Sending a request with missing required fields.</p><p><em>401 Unauthorized:</em> When the client tries to access a resource that requires authentication or lacks proper authentication credentials. <strong>Ex</strong>: Accessing a protected API without providing valid authentication credentials.</p><p><em>403 Forbidden:</em> This error occurs when the client’s request is valid, but the server refuses to fulfill it due to insufficient permissions. <strong>Ex</strong>: Attempting to access a resource that the user doesn’t have permission to access.</p><p><strong>Server Errors (5xx):</strong></p><p><em>500 Internal Server Error:</em> A generic error message indicating that the server encountered an unexpected condition that prevented it from fulfilling the request. <strong>Ex</strong>: A runtime error occurred on the server while processing the request.</p><p><em>501 Not Implemented:</em> This error is returned when the server does not support the functionality required to fulfill the request. <strong>Ex</strong>: Accessing an API endpoint that has not been implemented yet.</p><p><em>503 Service Unavailable:</em> The server is not ready to handle the request temporarily due to overloading or maintenance. <strong>Ex</strong>: The server is undergoing maintenance and is not accepting requests.</p><p>Sometimes (more often than we imagine), our app gets a little finicky with such kinds of errors. In Spring Boot, we’ve got these handy annotations called @ExceptionHandler and @ControllerAdvice to help us deal with these situations smoothly.</p><h4>Global Error Handling with @ExceptionHandler and @ControllerAdvice</h4><p>@ExceptionHandler is like your personal error assistant. It allows you to define methods inside your controller classes to catch specific exceptions. This way, when that exception occurs, your custom method can respond with a user-friendly error message or a specific action.</p><p>And then there’s @ControllerAdvice – it&#39;s like the watchful eye over all your controllers. It’s ready to jump in whenever an error pops up. It&#39;s the safety net that keeps users from seeing all the techie stuff when things go wrong. It centralizes your error-handling logic and promotes consistency.</p><p>Through a simple example, let’s take a look at how these annotations work together:</p><pre>@ControllerAdvice<br>public class GlobalExceptionHandler {<br><br>    @ExceptionHandler(ResourceNotFoundException.class)<br>    public ResponseEntity&lt;ErrorResponse&gt; handle(ResourceNotFoundException ex) {<br>        return new ResponseEntity&lt;&gt;(ex.getMessage(), HttpStatus.BAD_REQUEST);<br>    }<br>}</pre><p>In this code snippet, we define a GlobalExceptionHandler class with an @ExceptionHandler method that&#39;s ready to tackle a ResourceNotFoundException. When such an exception occurs, the method steps in and responds with an appropriate error message and status code. This way, you’re not only improving the user experience by providing meaningful error messages but also maintaining cleaner, more organized code.</p><p>However, if you were to paste this snippet directly into your Integrated Development Environment (IDE), you’d likely encounter an error message along the lines of “<em>Cannot resolve symbol ResourceNotFoundException</em>”. This is because ResourceNotFoundException is not an out-of-the-box exception class within Spring Boot. We&#39;ve custom-crafted this exception class ourselves. Now, you might be wondering, why go through the trouble of creating a custom exception class?</p><h4>Custom Exception Classes</h4><p>Creating custom exception classes offers you the ability to capture and encapsulate domain-specific errors that might not be covered by the standard set of exceptions. These exceptions can be tailored to your application’s unique needs, providing a clear and structured way to handle specialized error scenarios. Moreover, this practice enhances the readability of your code and simplifies debugging, as you can pinpoint specific issues more easily.</p><p>To create your own exception class, you’ll typically extend existing exception classes or implement the Throwable interface. By doing so, you&#39;re essentially crafting a dedicated tool to manage exceptional situations that arise within your application.</p><p>Let’s take the example of a ResourceNotFoundException. This custom exception class could be designed to handle situations where a requested resource is not found within the application&#39;s context.</p><pre>public class ResourceNotFoundException extends RuntimeException{<br>    public ResourceNotFoundException(String message) {<br>        super(message);<br>    }<br>}<br><br>// And in our code base, we can raise<br>throw new ResourceNotFoundException(&quot;Resource with ID 35 not found&quot;);</pre><p>The key to effective error handling is to provide descriptive and user-friendly error messages. These messages should guide users on what went wrong and how to proceed. For instance, if a requested resource is not found, the error message should clearly communicate this to the user.</p><p>Now, here’s where the cool part comes in: In order to achieve the level of clarity and user support, I would like to introduce you to something called ErrorResponse. It&#39;s like a special box that holds all the important info about the error.</p><h4>Custom Error Response: Making things clear for the user</h4><p>The ErrorResponse class encapsulates the following crucial pieces of information:</p><ul><li>timestamp: This is the exact time when the error happened.</li><li>status: It is the HTTP status code that tells what kind of error it is.</li><li>error: This is a short description of the error.</li><li>message: A friendly message that people can actually understand.</li><li>path: This is where the error showed up, like an end-point or URL.</li><li>fieldErrors: If there are issues with specific parts, they get listed here.</li></ul><p>When we put all these bits and pieces together in the ErrorResponse box, it&#39;s like a full picture of what went wrong and how to make it right. It&#39;s not just about helping users – it&#39;s also a lifesaver for us developers when we&#39;re trying to fix things.</p><p>And here’s what the box looks like in code:</p><pre>public class ErrorResponse {<br>    private LocalDateTime timestamp;<br>    private int status;<br>    private String error;<br>    private String message;<br>    private String path;<br>    private List&lt;FieldError&gt; fieldErrors;<br>}<br><br>public class FieldError {<br>    private String field;<br>    private String message;<br>}</pre><p>Using the ErrorResponse box in your app&#39;s error strategy is like having a clear conversation with your users. It&#39;s a smart move that raises the bar for how we deal with errors, making everything more understandable when the unexpected happens.</p><p>Now we have an idea of the error management components of Spring Framework, let us illustrate them as a flow. However, before we delve into the flowchart, here’s a quick tip: you’ll notice an additional element in the flowchart that we haven’t discussed yet. We’ve integrated the OpenAI API to enhance our error management strategy, and we’ll be covering the details in the upcoming sections. So, as you explore the flowchart, keep an eye out for this intriguing addition.</p><figure><img alt="Spring Framework’s Error Management leveraging by the power of OpenAI" src="https://cdn-images-1.medium.com/max/1024/1*rZB7i5esLOQnIMYB-quKuw.png" /><figcaption>Spring Framework’s Error Management leveraging by the power of OpenAI</figcaption></figure><h3>Integrating OpenAI for Enhanced Error Responses</h3><p>Now that we have a solid understanding of error handling in Spring Boot, let’s explore how we can harness the capabilities of OpenAI to elevate our error management strategy. By integrating OpenAI into our system, we can unlock a range of benefits that enhance both development and user experiences:</p><ol><li><strong>Enhance User Experience:</strong> By tapping into OpenAI’s capabilities, we can provide more meaningful and user-friendly error messages.</li><li><strong>Rapid Problem Identification:</strong> During the development phase, OpenAI can assist in quickly identifying errors, allowing us to spot issues early on and address them promptly.</li><li><strong>Smoother Development Phase</strong>: During the development stage, we have the opportunity to provide detailed error messages to anyone who interacts with our service. This proactive approach not only saves valuable time but also minimizes the need for extensive back-and-forth communication.</li><li><strong>Multilingual Support:</strong> OpenAI’s versatility extends to supporting different languages. This can be a game-changer for applications with global user bases, ensuring consistent and understandable error messages across languages.</li><li><strong>Support for Complex Scenarios:</strong> OpenAI is capable of handling complex error scenarios making it a versatile tool for our applications.</li><li><strong>Efficient Ticketing:</strong> Integrating OpenAI into your ticketing system can enhance issue categorization and management. Errors can be automatically categorized, streamlining the resolution process.</li><li><strong>Adaptability to User Needs:</strong> OpenAI’s dynamic responses allow us to tailor error messages based on the user’s familiarity with the application, ensuring both novices and experts receive relevant guidance.</li></ol><p>By incorporating OpenAI&#39;s intelligence, your error management strategy gains depth and finesse, and changes the way errors are understood and addressed. Now let&#39;s dive into the implementation details and see how these ideas are put into action. The core concept behind this integration is to send the stack trace of an error to the OpenAI API and receive a meaningful explanation and suggested solution in response.se.</p><blockquote><strong>Important Consideration: Protecting Your Application’s Integrity</strong></blockquote><blockquote>Still, caution is warranted, especially in the production phase. While OpenAI provides powerful insights, revealing every detail risks exposing internal application information and potentially leading to security vulnerabilities. Therefore, in a production environment, it’s important to carefully control what information is exposed and ensure a secure implementation of OpenAI capabilities.</blockquote><h4>Setting up the OpenAIClient</h4><p>To communicate with the OpenAI API, we create a dedicated client (OpenAIClient)class in our Spring Boot application. This class manages communication with the API and processes responses.</p><h4>Sending the Stack Trace to OpenAI</h4><p>When a Spring Boot error occurs, we capture the stack trace and send it to the OpenAIClient for processing. The client makes a request to the OpenAI API, passing the stack trace as a prompt. The API generates a response containing an explanation, proposed solution, criticality level, and user-friendly message based on the error.</p><h4>Handling the OpenAI Response</h4><p>Once we receive the response from the API, we can handle it in our OpenAIClient. We can parse the response and extract the relevant information, such as the explanation and proposed solution. Depending on the severity of the error, we can choose to display the response directly to the user or log it for further analysis.</p><h3>Implementing Error Handling with OpenAI</h3><p>With the theoretical foundation in place, let’s dive into the implementation details of error handling with OpenAI in a Spring Boot application. We will walk through the step-by-step process of setting up the OpenAIClient, capturing and sending the stack trace, and handling the response.</p><h4>Step 1: Setting up the OpenAIClient</h4><p>To set up the OpenAIClient, we first need to obtain an API key from the OpenAI platform. Once we have the API key, we can create an instance of the OpenAIClient in our Spring Boot application. This client will handle the authentication and communication with the OpenAI API. Here’s a basic outline of the process:</p><ol><li>Acquire an API key from the OpenAI platform.</li><li>Create an instance of the OpenAIClient in your Spring Boot application.</li><li>Configure the OpenAIClient by providing your API key and other required settings.</li></ol><p>You can include your API key in the <em>application.properties</em> file or use it as an environment variable. Consider the following configuration:</p><pre>openai.model=gpt-3.5-turbo<br>openai.api_key=${OPENAI_API_KEY:ADD_YOUR_OPENAI_API_KEY}<br>openai.chat_completions.api_url=https://api.openai.com/v1/chat/completions</pre><pre>@Component<br>public class OpenAIClient {<br>    @Value(&quot;${openai.api_key}&quot;)<br>    private String apiKey;<br><br>    @Value(&quot;${openai.chat_completions.api_url}&quot;)<br>    private String apiUrl;<br><br>    private RestTemplate restTemplate;<br>       <br>    public String generateResponse(String stackTrace) {<br>        // Logic to send the stack trace to the OpenAI API and receive the response<br>    }<br>}</pre><h4>Step 2: Capturing and Sending the Stack Trace</h4><p>To capture the stack trace when an error occurs, we can leverage Spring Boot’s exception-handling capabilities. Here’s an overview of the process:</p><ol><li>Create a custom exception handler class using @ControllerAdvice.</li><li>Implement the logic to intercept exceptions and capture the stack trace.</li><li>Construct an OpenAI Request using the ChatCompletionRequest class. This request should include the logical prompt along with the captured stack trace. This step sets the stage for generating an insightful response from the OpenAI API.</li><li>Pass the constructed request object to the OpenAIClient’s generateResponse method. This interaction initiates communication with the OpenAI API, which in turn generates a comprehensive response.</li></ol><pre>@ControllerAdvice<br>public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {<br>    <br>    private final OpenAIClient openAIClient;<br>       <br>    @ExceptionHandler(Exception.class)<br>    public ResponseEntity&lt;ErrorResponse&gt; handleException(Exception ex, HttpServletRequest request) {<br>        <br>        ChatCompletionRequest request = new ChatCompletionRequest(<br>            &quot;Providing the following StackTrace, &quot;<br>                + &quot;I would like you to return an explanation, possible_solution, criticality_level, and user_friendly_message in JSON format. &quot;<br>                + stackTrace);<br><br>        ChatCompletionResponse response = openAIClient.generateResponse(request);<br>        <br>        // Handle the API response    <br>    }<br>}</pre><pre>public class ChatCompletionRequest {<br><br>    private String model;<br>    private List&lt;Message&gt; messages = new ArrayList&lt;&gt;(1);<br>    private int max_tokens = 150;<br>    private double temperature = 0.2;<br><br>    // Constructor, getters, setters<br>}<br><br>public class Message {<br><br>    private String role;<br>    private String content;<br>}</pre><p>Before we proceed to the next step, I would like you to understand the details of ChatCompletionRequest that stands as the pivotal link connecting our application with the OpenAI API. It plays a critical role in establishing effective communication by crafting a request that encompasses essential elements:</p><ul><li><strong>Model:</strong> ID of the model to use. In our tutorial, we use gpt-3.5-turbo. See the <a href="https://platform.openai.com/docs/models/model-endpoint-compatibility"><strong>model endpoint compatibility</strong></a> table for details on which models work with the Chat API.</li><li><strong>Messages:</strong> A list of messages, which is a vital part of the prompt. These messages encapsulate information about the error’s context and characteristics in our tutorial. The role indicates the author of the message and it can be one of system, user, assistant, or function.</li><li><strong>Max Tokens:</strong> The maximum number of tokens the API should generate in its response. This parameter helps control the length of the generated explanation.</li><li><strong>Temperature:</strong> A value controlling the randomness of the AI’s response. A lower value like 0.2 ensures a more focused and deterministic reply.</li></ul><h4>Step 3: Handling the OpenAI API Response</h4><p>Once we receive the response(ChatCompletionResponse)from the API, we need to handle it appropriately. By parsing the response, we can extract valuable insights that shed light on the error’s origin and potential solutions. This extracted information includes:</p><ul><li><strong>Index:</strong> The index within the list of choices, indicating the relevance of the provided message.</li><li><strong>Message:</strong> The message encapsulates the explanation, suggested solution, criticality level, and user-friendly message pertaining to the error.</li></ul><pre>public class ChatCompletionResponse {<br><br>    private List&lt;Choice&gt; choices;<br><br>    public static class Choice {<br><br>        private int index;<br>        private Message message;<br>    }<br>}</pre><p>Depending on the severity of the error and the nature of the response, we can choose different strategies. For example, we can display the response directly to the user or log it for further analysis.</p><h3>Running the Tutorial Application and Experimenting</h3><p>To experience the implementation firsthand, you can follow these steps:</p><ol><li><strong>Clone the Project:</strong> Begin by cloning the project repository from my GitHub account. You can access it through the following link: <a href="https://github.com/emredmrcan/tutorials/tree/main/error-handling">GitHub Repository Link</a>.</li><li><strong>Setting Up the OpenAIClient:</strong> Follow the instructions provided earlier to set up the OpenAIClient. Obtain an API key from the OpenAI platform and configure it within the application.</li><li><strong>Run the Application:</strong> Launch the Spring Boot application in your local environment by following the guidelines outlined in the <a href="https://github.com/emredmrcan/tutorials/blob/main/error-handling/README.md">README</a>.</li><li><strong>Trigger an Error:</strong> Experience the error-handling process firsthand by intentionally triggering an error within your application. This can be done by making a request to <a href="http://localhost:8080/tutorial/1">http://localhost:8080/tutorial/1</a>. Doing so will activate a CriticalBusinessException, causing the OpenAIErrorInterceptor in the GlobalExceptionHandler to come into play.</li><li><strong>Observe and Learn:</strong> Take the opportunity to observe how the stack trace is captured and transmitted to the OpenAI API. As you trigger the error, you’ll notice the following information displayed on the client side:</li></ol><pre>{<br>  &quot;timestamp&quot;:&quot;2023-08-15T20:20:13.871254&quot;,<br>  &quot;status&quot;:500,<br>  &quot;error&quot;:&quot;Critical Business Exception&quot;,<br>  &quot;message&quot;:&quot;An error occurred while retrieving the resource&quot;,<br>  &quot;path&quot;:&quot;/tutorial/1&quot;,<br>  &quot;fieldErrors&quot;:[]<br>}</pre><p>On the server side, you’ll find a corresponding log message that provides a deeper insight into the nature of the error:</p><pre>{<br>  &quot;explanation&quot; : &quot;The stack trace indicates that an error occurred while retrieving a resource in the DefaultController class at line 25.&quot;,<br>  &quot;possible_solution&quot; : &quot;Check the code at line 25 of the DefaultController class to identify and fix the issue with retrieving the resource.&quot;,<br>  &quot;criticality_level&quot; : &quot;HIGH&quot;,<br>  &quot;user_friendly_message&quot; : &quot;An error occurred while retrieving the resource. Please try again later.&quot;<br>}</pre><p>Take the time to study this log and understand how it provides valuable insights into the nature of the error, suggests a possible solution, and even indicates the criticality level of the error. This holistic approach ensures that not only developers but also other stakeholders gain a comprehensive understanding of the error and its implications.</p><p>By taking these steps and engaging in this hands-on observation, you’ll acquire a practical understanding of how integrating OpenAI enhances error management in your Spring Boot application. This experience will provide you with valuable insights and knowledge that go beyond theoretical concepts.</p><h3>Join the Conversation and Let’s Chat!</h3><p>Hey there, fellow developers and curious minds! 🚀</p><p>Guess what? Your thoughts, experiences, and brilliant ideas matter to me! I’ve put together this tutorial to help you dive into the world of error handling with OpenAI. But I’m not stopping there — I want to hear from you.</p><p>Did you run into any exciting challenges while experimenting with the tutorial? Maybe a tiny hiccup or a big “aha!” moment? Share it with me in the comments section below the tutorial. Don’t worry, we’re all friends here, and there’s no such thing as a silly question.</p><p>But wait, there’s more! If you’ve got a fresh spin on how to enhance the tutorial or a completely new angle on using OpenAI for error management, don’t keep it to yourself. Your creativity could be the spark that ignites awesome discussions and new ideas.</p><p>We’re all about building a community of thinkers and problem solvers, and your contribution is like a treasure trove of insights waiting to be discovered. So go ahead, drop a comment, share your experiences, and let’s learn and grow together! 💬🚀</p><p><strong>Support the Journey: Consider Contributing</strong></p><p>If you’ve found this tutorial helpful and wish to express your appreciation, you can support my work by contributing via the “Buy Me A Coffee” platform. Your gesture fuels the creation of more tutorials and resources to help you and others in the developer community.</p><figure><a href="http://buymeacoffee.com/edemircan"><img alt="" src="https://cdn-images-1.medium.com/max/170/1*Dpw8-hNGI2fDmosV4E8DVQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41afc929fc21" width="1" height="1" alt=""><hr><p><a href="https://pub.aimind.so/empowering-spring-boot-openai-driven-error-management-41afc929fc21">Empowering Spring Boot: OpenAI-Driven Error Management</a> was originally published in <a href="https://pub.aimind.so/">AI Mind</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep Dive into Dockerized Monitoring and Alerting for Spring Boot with Prometheus and Grafana]]></title>
            <link>https://medium.com/@edemircan/a-deep-dive-into-dockerized-monitoring-and-alerting-for-spring-boot-with-prometheus-and-grafana-144fcd209822?source=rss-752e89de810d------2</link>
            <guid isPermaLink="false">https://medium.com/p/144fcd209822</guid>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[alertmanager]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Emre Demircan]]></dc:creator>
            <pubDate>Wed, 09 Aug 2023 20:28:00 GMT</pubDate>
            <atom:updated>2023-08-09T20:28:00.567Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*Fqd6mUMYSi3tmTZwGTm6zA.png" /><figcaption>Architecture Diagram: Dockerized Monitoring and Alerting for Spring Boot with Prometheus and Grafana</figcaption></figure><h3>Introduction</h3><p>As technology continues to advance, the need for efficient monitoring and alerting in software applications becomes increasingly important. <a href="https://www.docker.com/">Docker</a>, a popular containerization platform, offers a powerful solution for managing these processes. In this article, we will explore how Docker can be utilized to streamline monitoring and alerting in <a href="https://spring.io/projects/spring-boot">Spring Boot</a> applications. We will specifically focus on the integration of <a href="https://prometheus.io/">Prometheus</a> and <a href="https://grafana.com/">Grafana</a>, two widely-used tools in the DevOps community, to achieve these goals. While numerous examples of dockerizing these technologies abound, this guide stands out by its comprehensive approach. Each step is meticulously explained, ensuring a deep understanding of the intricacies involved in this integration. By the end of this article, you will have a comprehensive understanding of how to implement Dockerized monitoring and alerting in your Spring Boot applications.</p><h3>Overview of Monitoring and Alerting in Spring Boot Applications</h3><p>Before diving into the details, it is essential to understand the concepts behind these processes. Monitoring focuses on tracking the performance and behavior of an application in real-time. On the other hand, alerting allows for the detection and notification of critical events or anomalies in the application.</p><p>Spring Boot, a widely used Java framework, provides integrated support for monitoring and alerting. Additionally, <a href="https://docs.spring.io/spring-boot/docs/current/actuator-api/htmlsingle/">Spring Boot Actuator</a> provides a set of tools and endpoints for monitoring and managing the application’s health and metrics. While these features are powerful on their own, Docker can further enhance the efficiency and scalability of monitoring and alerting in Spring Boot applications.</p><h3>Understanding Prometheus (with AlertManager) and Grafana for Monitoring and Alerting</h3><p>Prometheus and Grafana are two open-source tools widely used in the DevOps community for monitoring and alerting. Each tool plays a distinct role in the monitoring ecosystem, offering integration to enhance the observability of complex systems.</p><p><strong>Prometheus:</strong> As a monitoring system and time-series database, Prometheus is engineered to collect and store metrics from various sources within an environment. Its robust architecture makes it an invaluable asset for tracking the performance of applications, infrastructure components, and services. With a flexible query language, Prometheus empowers users to perform advanced data analysis, enabling them to identify trends, anomalies, and potential bottlenecks in their systems. Furthermore, Prometheus offers a powerful alerting system, enabling users to define custom rules that trigger notifications when specific conditions are met. This makes Prometheus a versatile choice for monitoring Spring Boot applications, ensuring their health and performance are continuously monitored and maintained.</p><p><strong>Grafana:</strong> Complementing Prometheus, Grafana serves as a dynamic visualization tool that transforms raw data into meaningful insights. Users can design visually compelling dashboards and graphs using a wide array of visualization options. Grafana’s interactive and intuitive interface makes it easy to create informative visualizations that convey essential metrics and performance trends. By connecting directly to the data collected by Prometheus, Grafana provides a real-time snapshot of system behavior, enabling operators to make informed decisions and respond swiftly to changing conditions.</p><p><strong>AlertManager:</strong> An integral part of the Prometheus ecosystem, AlertManager acts as a dedicated component for managing and sending alerts generated by Prometheus. With its seamless integration, AlertManager centralizes the alerting process, ensuring that alerts are handled efficiently and consistently. It enables users to configure routing and grouping of alerts based on severity levels, target recipients, and other criteria. With customizable templates and notification options, AlertManager ensures that crucial alerts are promptly communicated to the right individuals or teams. This simplifies incident response, reduces downtime, and enhances the overall reliability of the monitoring and alerting process.</p><p>In summary, Prometheus, Grafana, and AlertManager together form a comprehensive toolkit for monitoring, visualization, and alerting in the DevOps landscape. Their integration empowers teams to gain deeper insights, make data-driven decisions, and proactively address potential issues, ultimately contributing to the stability and success of their applications and systems.</p><h3>Setting up Docker for Monitoring and Alerting with Prometheus and Grafana</h3><p>Now that we have a clear understanding of the benefits of Docker and the capabilities of Prometheus and Grafana, let’s explore how to set up Docker for monitoring and alerting in Spring Boot applications.</p><h4>Step 1: Install Docker</h4><p>The first step is to install Docker on your machine. Docker provides installation packages for various operating systems, including Windows, macOS, and Linux. Simply download the appropriate package for your operating system and follow <a href="https://docs.docker.com/get-docker/">the installation instructions provided by Docker</a>.</p><h4>Step 2: Unveiling the Structure</h4><p>Before we delve into the specifics, let’s take a moment to familiarize ourselves with the organized structure that lays the foundation for our Docker-powered monitoring environment. Here’s a visual representation of this structure:</p><pre>docker/<br>├─ alert-manager/<br>│ ├─ config/<br>│ │ ├─ alertmanager.yml<br>├─ grafana/<br>│ ├─ grafana.ini<br>├─ prometheus/<br>│ ├─ config/<br>│ │ ├─ alert-rules.yml<br>│ │ ├─ prometheus.yml<br>docker-compose.yaml</pre><h4>Step 3: Create Docker Compose File</h4><p>Next, we need to create a Docker Compose file that defines the services required for monitoring and alerting. The Docker Compose file is written in YAML format and allows us to define multiple services and their configurations.</p><p>Create a new file named docker-compose.yml and add the following contents:</p><pre>services:<br>  prometheus:<br>    image: prom/prometheus:v2.46.0<br>    ports:<br>      - 9090:9090<br>    volumes:<br>      - ./prometheus/tmp:/prometheus<br>      - ./prometheus/config:/etc/prometheus<br>    command: --config.file=/etc/prometheus/prometheus.yml --log.level=debug<br><br>  grafana:<br>    image: grafana/grafana:10.0.3<br>    ports:<br>      - 3000:3000<br>    volumes:<br>      - ./grafana/tmp:/var/lib/grafana<br>      - ./grafana/grafana.ini:/etc/grafana/grafana.ini<br><br>  alertmanager:<br>    image: prom/alertmanager:v0.25.0<br>    ports:<br>      - &quot;9093:9093&quot;<br>    volumes:<br>      - ./alert-manager/tmp:/data<br>      - ./alert-manager/config:/config<br>    command: --config.file=/config/alertmanager.yml --log.level=debug</pre><p>In this example, we define three services: prometheus, grafanaand alertmanager. The prometheus service uses the prom/prometheus Docker image and exposes port 9090 for convenient access to the Prometheus web interface. The grafana service uses the grafana/grafana Docker image and opens port 3000 to provide a gateway to the Grafana web interface. Lastly, the alertmanagerservice, fueled by the prom/alertmanager Docker image and establishes communication through port 9093. We also define volume mappings to preserve the data.</p><h4>Step 4: Configure Prometheus with AlertManager</h4><p>Now that we have our Docker Compose file, let’s configure Prometheus to scrape metrics from our Spring Boot application. Create a new file named prometheus.yml and add the following contents:</p><pre>global:<br>  scrape_interval: 15s<br>  evaluation_interval: 15s<br>scrape_configs:<br>  - job_name: &#39;spring-boot-prometheus&#39;<br>    metrics_path: &#39;/actuator/prometheus&#39;<br>    static_configs:<br>      - targets: [&#39;host.docker.internal:8080&#39;]</pre><p>In this example configuration, we define a spring-boot-prometheus job that scrapes metrics from our Spring Boot application. The metrics_path specifies the endpoint provided by Spring Boot Actuator for exposing metrics, and the targets specify the hostname and port of our Spring Boot application.</p><p><strong>Step 4a: Configure Alerting Rules</strong></p><p>To configure alerting rules, we need to define them in Prometheus. Open the prometheus.yml file and add the following contents:</p><pre>rule_files:<br>  - &#39;alert-rules.yml&#39;<br>alerting:<br>  alertmanagers:<br>    - scheme: http<br>    - static_configs:<br>        - targets: [&#39;host.docker.internal:9093&#39;]</pre><p>rule_filespoints to an external file named alert-rules.yml. This file contains rules that help define when and how Prometheus should trigger alerts. These rules act as guidelines to determine under what conditions an alert should be raised. alertmanagersare like the messengers for alerts. They ensure that when something important happens, like a performance issue or an error, an alert is sent out to the relative target.</p><p><strong>Step 4b: Create Alerting Rules</strong></p><p>Now that we have our Prometheus and Alertmanager configurations set up, let’s create alert-rules.yml file that has some rules to guide Prometheus on when to raise alerts. We’re going to create a set of instructions to let Prometheus know when a critical situation requires our attention.</p><pre>groups:<br>  - name: tutorial-rules<br>    rules:<br>      # Triggers a critical alert if a server is down for more than 1 minute.<br>      - alert: ServerDown<br>        expr: up &lt; 1<br>        for: 1m<br>        labels:<br>          severity: critical<br>        annotations:<br>          summary: &quot;Server {{ $labels.instance }} down&quot;<br>          description: &quot;{{ $labels.instance }} of job {{ $labels.job }} has been down for more than 1 minute.&quot;</pre><p>Inside the alert-rules.yml file, under the groups section, we&#39;ve created a named group called <em>tutorial-rules</em>. This group holds the instructions for our rules. Here’s a breakdown of what’s happening with our example rule:</p><ul><li>alert: ServerDown: This line assigns a name to our alert, &#39;ServerDown&#39;. It&#39;s like a label for the alert, helping us identify what&#39;s going on.</li><li>expr: up &lt; 1: This line is the heart of the rule. It defines the condition for the alert. In simple terms, it checks if the &#39;up&#39; metric (which tells us if a server is running) is less than 1. If it&#39;s less than 1, it means the server is down. You can find more examples of query basics <a href="https://prometheus.io/docs/prometheus/latest/querying/basics/">here</a>.</li><li>for: 1m: This part tells Prometheus to wait for 1 minute before triggering the alert. It gives a little time, just in case the server goes down briefly.</li><li>labels:: These are like tags we attach to the alert. In our case, we&#39;re labeling the severity as &#39;critical&#39;.</li><li>annotations:: These are additional details we add to the alert. The <em>summary</em> and <em>description</em> lines help us understand the situation better. They tell us which server and job are affected and how long the server has been down.</li></ul><p>So, in simple terms, this rule acts as our watchdog. If a server stays down for more than 1 minute, Prometheus will raise a critical alert. The alert will tell us which server and job are affected and give us a heads-up about the situation.</p><p><strong>Step 4c: Configure Alertmanager</strong></p><p>Having set up rules for the AlertManager, the natural question arises: how do we ensure these critical alerts reach the right people at the right time? The answer lies in configuring routes and receivers within the alertmanager.yaml file. Here&#39;s a breakdown of the process:</p><p>Create and open the alertmanager.yaml file to configure how alerts will be directed and who will receive them.</p><pre>route:<br>  receiver: tutorial-alert-manager<br>  repeat_interval: 1m<br>receivers:<br>  - name: &#39;tutorial-alert-manager&#39;<br>    telegram_configs:<br>      - bot_token: tutorial_token<br>        api_url: https://api.telegram.org<br>        chat_id: -12345678<br>        parse_mode: &#39;&#39;<br>    email_configs:<br>      - to: &#39;tutorial.inbox@gmail.com&#39;<br>        from: &#39;tutorial.outbox@gmail.com&#39;<br>        smarthost: &#39;smtp.gmail.com:587&#39;<br>        auth_username: &#39;username&#39;<br>        auth_password: &#39;password&#39;</pre><p>Here, receiver points to the name of the receiver you&#39;re setting up. The repeat_interval specifies how often to send repeat notifications, ensuring crucial alerts aren&#39;t missed. Our example illustrates the use of two distinct receivers.</p><ul><li>The first receiver is configured to send alerts via Telegram. It uses the provided bot token, chat ID, and Telegram API.</li><li>The second receiver is set up for email notifications. In this configuration, we specify an email receiver that sends notifications to a specified email address. You will need to replace the placeholder values (tutorial.inbox@gmail.com, tutorial.outbox@gmail.com, smtp.gmail.com:587, username, password) with your own email and SMTP server details.</li></ul><p>With these configurations in place, your AlertManager is ready to route alerts to both Telegram and email receivers. Keep in mind that while this setup ensures timely alerts, it’s essential to follow security practices, especially when dealing with sensitive information.</p><p><strong>P.S:</strong> If you’re intrigued by this example and wish to receive alerts through Telegram, I’ve thoughtfully prepared a concise <a href="https://github.com/emredmrcan/tutorials/blob/main/monitoring/README.md#guide-to-sending-prometheus-notifications-via-telegram">README</a> detailing how to create a Telegram Channel and integrate it with AlertManager. Please be sure to tailor your configurations for SMTP and Telegram to align with your needs.</p><h4>Step 5: Configure Grafana</h4><p>Let’s configure Grafana to visualize the metrics collected by Prometheus. Create a new file named grafana.ini and add the following contents:</p><pre>[paths]<br>data = /var/lib/grafana/data<br>logs = /var/log/grafana<br>plugins = /var/lib/grafana/plugins<br>[server]<br>http_port = 3000</pre><p>In this configuration, we specify the data, logs, and plugins paths for Grafana. We also set the HTTP port to 3000, which matches the port we exposed in the Docker Compose file.</p><h4>Step 6: Configure Spring Boot Application</h4><p>Add the required dependencies into your project. Open your pom.xml file and insert the following dependencies:</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;io.micrometer&lt;/groupId&gt;<br>  &lt;artifactId&gt;micrometer-registry-prometheus&lt;/artifactId&gt;<br>  &lt;scope&gt;runtime&lt;/scope&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-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-actuator&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>The Micrometer Prometheus registry allows your application to expose metrics in a format that Prometheus can understand. The Spring Boot Starter Web dependency provides the necessary web capabilities for exposing endpoints, and the Spring Boot Starter Actuator dependency offers advanced management and monitoring features, including health checks and metrics.</p><p>Next, open your Spring Boot application’s application.properties file and add the following lines to enable the required management endpoints:</p><pre>management.endpoints.web.exposure.include= *<br>management.endpoint.prometheus.enabled= true<br>management.endpoint.health.show-details= always<br>management.endpoint.metrics.enabled= true<br>management.prometheus.metrics.export.enabled= true</pre><p>These lines are designed to ensure that your application exposes the necessary endpoints for Prometheus, health checks, and metrics.</p><p>A friendly reminder: While this configuration is ideal for experimentation, exercising prudence is crucial when dealing with exposed metrics in a production environment.</p><h3>Visualizing Metrics and Creating Dashboards with Grafana</h3><p>With Docker, Prometheus, and Grafana set up, we can now start visualizing the metrics collected from our Spring Boot application and create customized dashboards in Grafana.</p><h4>Step 1: Run Spring Boot Application</h4><p>Begin by running your Spring Boot application. This step is crucial for monitoring metrics and enabling the creation of meaningful dashboards.</p><h4>Step 2: Access Grafana Web Interface</h4><p>Open your web browser and navigate to http://localhost:3000 to access the Grafana web interface. You will be prompted to log in with the default credentials (username: <em>admin</em>, password: <em>admin</em>). After logging in, you will be prompted to change the password.</p><h4>Step 3: Add Prometheus as a Data Source</h4><p>Once you have logged in, click on the “Connections” icon in the left-hand menu, then click on “Data Sources”. Click on the “Add data source” button and select “Prometheus” as the data source type. Configure the URL to http://prometheus:9090 and click on the &quot;Save &amp; Test&quot; button. If the connection is successful, you will see a green notification confirming that the data source is working.</p><h4>Step 4: Create a Dashboard</h4><p>Now that we have configured Prometheus as the data source, it’s time to create a new dashboard for visualizing the metrics. Grafana offers a wide range of visualization options, including charts, tables, and gauges, allowing you to create custom dashboards. You can discover an assortment of diverse dashboards, curated by countless users, within the <a href="https://grafana.com/grafana/dashboards/">Grafana Dashboards</a> repository. However, for our purpose, we’ll tap into the Spring Boot 2.1 Statistics dashboard (ID: 10280).</p><p>To initiate the process, navigate to the left menu and click on the ‘Dashboards’ icon. Then, proceed by selecting ‘New -&gt; Import.’ Within this interface, you can import dashboards using either a dashboard URL or ID, subsequently adapting them to showcase the metrics relevant to your context. As we’re focusing on the Spring Boot 2.1 Statistics dashboard, input the ID 10280 and import it. When prompted, associate the imported dashboard with the Prometheus data source.</p><h4>Step 5: Fire an Alert</h4><p>Temporarily stop your Spring Boot Application. After a minute, observe the triggering of the ServerDown alert. Notifications will be dıspatched through the specified channels if <em>*_configs</em> are defined correctly.</p><h4>Step 6: Embrace the Journey</h4><ul><li>Explore the realm of Prometheus metrics exposed by your Spring Boot application: <a href="http://localhost:8080/actuator/prometheus">http://localhost:8080/actuator/prometheus</a></li><li>Delve into the Prometheus alert rules at <a href="http://localhost:9090/alerts">http://localhost:9090/alerts</a></li><li>Experiment with your own Prometheus queries/expressions (e.g., up{job=&quot;spring-boot-prometheus&quot;}) and test them at <a href="http://localhost:9090/">http://localhost:9090/</a></li><li>Track fired alerts and receiver configurations at <a href="http://localhost:9093/">http://localhost:9093/</a></li><li>Monitor your application’s health and metrics at <a href="http://localhost:3000/dashboards">http://localhost:3000/dashboards</a></li></ul><p>This entire setup acts as a discovery phase, providing insights into robust monitoring and alerting capabilities. Remember to tailor the configurations to your environment and needs to ensure optimum performance and reliability.</p><h3>Conclusion and Next Steps for Implementing Dockerized Monitoring and Alerting in Spring Boot Applications</h3><p>In conclusion, Docker provides a powerful platform for monitoring and alerting in Spring Boot applications. By integrating Prometheus and Grafana into your Dockerized environment, you can streamline these processes and gain valuable insights into the performance and behavior of your applications. With Docker, Prometheus, and Grafana, you are well-equipped to take your monitoring and alerting to the next level.</p><p>Implementing these mechanisms is a journey that requires continuous learning and improvement. As you become more familiar with Docker, Prometheus, and Grafana, consider exploring advanced features and integrations to further enhance your DevOps practices. Embrace the power of Docker and empower your development team with efficient monitoring and alerting capabilities.</p><p><strong>Connect, Collaborate, Contribute: Your Path Forward</strong></p><p>If you encounter any bumps in the road, just hop over to the <a href="https://github.com/emredmrcan/tutorials/tree/main/monitoring"><strong>GitHub repository</strong></a> I’ve prepared for you. I’m right there to help sort them out.</p><p>Have any questions, run into hiccups, or just want to share a high-five? Let’s meet in the comments section.</p><p><strong>Support the Journey: Consider Contributing</strong></p><p>If you’ve found this tutorial helpful and wish to express your appreciation, you can support my work by contributing via the “Buy Me A Coffee” platform. Your gesture fuels the creation of more tutorials and resources to help you and others in the developer community.</p><figure><a href="http://buymeacoffee.com/edemircan"><img alt="" src="https://cdn-images-1.medium.com/max/170/1*Dpw8-hNGI2fDmosV4E8DVQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=144fcd209822" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>