<?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 Daniel Angel on Medium]]></title>
        <description><![CDATA[Stories by Daniel Angel on Medium]]></description>
        <link>https://medium.com/@danielangel22?source=rss-a93aad8008b0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*epLXIiUFb-RbsaD3</url>
            <title>Stories by Daniel Angel on Medium</title>
            <link>https://medium.com/@danielangel22?source=rss-a93aad8008b0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 02:06:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danielangel22/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[Java Performance Optimization: Techniques Every Developer Should Know]]></title>
            <link>https://danielangel22.medium.com/java-performance-optimization-techniques-every-developer-should-know-9089a0e70de5?source=rss-a93aad8008b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9089a0e70de5</guid>
            <category><![CDATA[stream]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[optimization-algorithms]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Daniel Angel]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 14:27:11 GMT</pubDate>
            <atom:updated>2025-03-07T14:27:11.025Z</atom:updated>
            <content:encoded><![CDATA[<p>Performance optimization is a crucial aspect of Java development, especially for applications handling high loads. In this article, we’ll explore key techniques to optimize Java applications and improve their efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kkVbnXy4-ZPPAVKN" /><figcaption>Photo by <a href="https://unsplash.com/@chrisliverani?utm_source=medium&amp;utm_medium=referral">Chris Liverani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Use Efficient Data Structures</h3><p>Choosing the right data structure can significantly impact performance.</p><h3>Example: Use ArrayList Instead of LinkedList</h3><pre>List&lt;String&gt; list = new ArrayList&lt;&gt;(); // Faster random access<br>list.add(&quot;Apple&quot;);<br>list.add(&quot;Banana&quot;);<br>System.out.println(list.get(1)); // O(1) operation</pre><p>ArrayList is generally more performant than LinkedList for most use cases due to better cache locality and lower overhead.</p><h3>Example: Use HashMap for Fast Lookups</h3><pre>Map&lt;String, Integer&gt; ageMap = new HashMap&lt;&gt;();<br>ageMap.put(&quot;Alice&quot;, 30);<br>ageMap.put(&quot;Bob&quot;, 25);<br>System.out.println(ageMap.get(&quot;Alice&quot;)); // O(1) lookup</pre><h3>2. Optimize String Handling</h3><p>Strings are immutable in Java, so improper usage can lead to excessive memory allocation.</p><h3>Solution: Use StringBuilder</h3><pre>StringBuilder sb = new StringBuilder();<br>sb.append(&quot;Hello&quot;).append(&quot; World&quot;);<br>System.out.println(sb.toString());</pre><p>Instead of String concatenation (+), which creates multiple objects, StringBuilder is more memory efficient.</p><h3>Example: Use join() Instead of Loops for Concatenation</h3><pre>List&lt;String&gt; words = Arrays.asList(&quot;Java&quot;, &quot;Optimization&quot;, &quot;Techniques&quot;);<br>String result = String.join(&quot; &quot;, words);<br>System.out.println(result);</pre><h3>3. Avoid Unnecessary Object Creation</h3><p>Creating unnecessary objects increases memory usage and garbage collection overhead.</p><h3>Example: Use static Constants</h3><pre>private static final Pattern EMAIL_PATTERN = Pattern.compile(&quot;^[A-Za-z0-9+_.-]+@(.+)$&quot;);</pre><p>Instead of re-compiling a regex every time, reuse a static constant.</p><h3>Example: Reuse Objects When Possible</h3><pre>Integer cachedNumber = Integer.valueOf(42);</pre><p>This prevents creating new instances unnecessarily.</p><h3>4. Leverage Lazy Initialization</h3><p>Only initialize objects when needed to save resources.</p><h3>Example:</h3><pre>private HeavyObject heavyObject;<br><br>public HeavyObject getHeavyObject() {<br>    if (heavyObject == null) {<br>        heavyObject = new HeavyObject();<br>    }<br>    return heavyObject;<br>}</pre><h3>5. Optimize Loops</h3><p>Loops are performance-critical, so reducing iterations can significantly improve speed.</p><h3>Example: Use forEach and Streams</h3><pre>List&lt;String&gt; names = Arrays.asList(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;);<br>names.forEach(System.out::println);</pre><p>This improves readability and can be optimized internally by the JVM.</p><h3>Example: Avoid Redundant Computations in Loops</h3><pre>for (int i = 0, size = list.size(); i &lt; size; i++) {<br>    process(list.get(i));<br>}</pre><p>Storing list.size() in a variable prevents redundant method calls in each iteration.</p><h3>6. Use Caching</h3><p>Caching prevents redundant calculations and database queries.</p><h3>Example: Using Map for Caching</h3><pre>private final Map&lt;Integer, String&gt; cache = new HashMap&lt;&gt;();<br><br>public String getData(int id) {<br>    return cache.computeIfAbsent(id, this::fetchFromDatabase);<br>}</pre><h3>Example: Using Guava Cache</h3><pre>LoadingCache&lt;Integer, String&gt; cache = CacheBuilder.newBuilder()<br>    .maximumSize(100)<br>    .expireAfterWrite(10, TimeUnit.MINUTES)<br>    .build(new CacheLoader&lt;Integer, String&gt;() {<br>        public String load(Integer key) { return fetchFromDatabase(key); }<br>    });</pre><h3>7. Optimize Database Queries</h3><p>Minimize the number of database queries and use batch operations where possible.</p><h3>Example: Use IN Instead of Multiple Queries</h3><pre>SELECT * FROM users WHERE id IN (1,2,3,4);</pre><p>Instead of executing multiple SELECT queries, a single batch query reduces overhead.</p><h3>Example: Use Prepared Statements</h3><pre>String query = &quot;SELECT * FROM users WHERE id = ?&quot;;<br>PreparedStatement stmt = connection.prepareStatement(query);<br>stmt.setInt(1, userId);<br>ResultSet rs = stmt.executeQuery();</pre><p>This prevents SQL injection and improves performance.</p><h3>8. Reduce Garbage Collection Pressure</h3><p>Frequent garbage collection (GC) can slow down applications.</p><h3>Solution: Tune JVM GC Settings</h3><p>Run with optimal GC settings:</p><pre>-XX:+UseG1GC -Xms512m -Xmx2g</pre><h3>Example: Use Object Pools for Expensive Objects</h3><pre>private static final ExecutorService threadPool = Executors.newFixedThreadPool(10);</pre><p>This avoids constant object creation and destruction, reducing GC pressure.</p><h3>9. Profile and Monitor Performance</h3><p>Use profiling tools like VisualVM, JProfiler, or Java Flight Recorder to identify bottlenecks.</p><h3>Example: Profiling with Java Flight Recorder</h3><p>Run your application with:</p><pre>java -XX:+FlightRecorder -XX:StartFlightRecording=duration=60s,filename=myrecording.jfr -jar myapp.jar</pre><p>Analyze the output file with JDK Mission Control.</p><h3>Conclusion</h3><p>By implementing these techniques, you can significantly optimize your Java applications, making them faster and more efficient. Always profile before optimizing to focus on real bottlenecks. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9089a0e70de5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Using Boilerplate Code! How Java Records Improve Spring Boot Development]]></title>
            <link>https://danielangel22.medium.com/stop-using-boilerplate-code-how-java-records-improve-spring-boot-development-f6ef543a0b15?source=rss-a93aad8008b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6ef543a0b15</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[record]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Daniel Angel]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 14:16:41 GMT</pubDate>
            <atom:updated>2025-03-06T14:16:41.701Z</atom:updated>
            <content:encoded><![CDATA[<p>Java developers have long struggled with the verbosity of POJOs (Plain Old Java Objects), especially when dealing with DTOs, entities, and value objects. However, with Java 14’s introduction of record (and its official release in Java 16), we now have a powerful tool to simplify our Spring Boot applications. Let’s explore why you should embrace records and how they can improve your codebase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X4rnQqCB0Dz_Xt6-" /><figcaption>Photo by <a href="https://unsplash.com/@cgower?utm_source=medium&amp;utm_medium=referral">Christopher Gower</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What Are Java Records?</h3><p>A record is a special kind of class in Java designed to be immutable and concise. It automatically generates essential methods such as:</p><ul><li>Constructor</li><li>Getters (without get prefix)</li><li>equals() and hashCode()</li><li>toString()</li></ul><h3>Example of a Traditional POJO</h3><pre>public class User {<br>    private final String name;<br>    private final int age;<br>    <br>    public User(String name, int age) {<br>        this.name = name;<br>        this.age = age;<br>    }<br>    <br>    public String getName() {<br>        return name;<br>    }<br>    <br>    public int getAge() {<br>        return age;<br>    }<br>    <br>    @Override<br>    public boolean equals(Object o) { /* Implementation */ }<br>    <br>    @Override<br>    public int hashCode() { /* Implementation */ }<br>    <br>    @Override<br>    public String toString() { /* Implementation */ }<br>}</pre><p>This class is repetitive and full of boilerplate code. Now, let’s see the same class as a record:</p><pre>public record User(String name, int age) {}</pre><p>That’s it! The compiler automatically generates all necessary methods.</p><h3>Why Use Java Records in Spring Boot?</h3><h3>1. Perfect for DTOs</h3><p>When working with REST APIs, Data Transfer Objects (DTOs) are essential. Java records simplify their definition:</p><pre>public record UserDTO(String name, int age) {}</pre><p>This makes controllers cleaner:</p><pre>@RestController<br>@RequestMapping(&quot;/users&quot;)<br>public class UserController {<br>    @GetMapping(&quot;/{id}&quot;)<br>    public UserDTO getUser(@PathVariable Long id) {<br>        return new UserDTO(&quot;John Doe&quot;, 30);<br>    }<br>}</pre><h3>2. Immutable and Thread-Safe</h3><p>Since records are immutable by default, they are perfect for multi-threaded applications, preventing unintended modifications.</p><h3>3. Less Boilerplate, More Readability</h3><p>Fewer lines of code mean fewer errors and improved readability.</p><h3>Where NOT to Use Records</h3><p>Records are great for DTOs and value objects but <strong>not</strong> for JPA entities. JPA requires setters and a no-argument constructor, which contradicts the immutability of records.</p><p>If you need to work with JPA, prefer regular classes with Lombok:</p><pre>@Entity<br>@Getter<br>@Setter<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class UserEntity {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    private String name;<br>    private int age;<br>}</pre><h3>Conclusion</h3><p>Java records are a game-changer for Spring Boot applications, simplifying DTOs and improving code clarity. While they are not suited for JPA entities, they are an excellent choice for data representation, making your applications more maintainable and efficient.</p><p>If you’re still writing verbose POJOs, now is the perfect time to start using records and embrace modern Java development!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6ef543a0b15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Using @Autowired! The Better Way to Inject Dependencies in Spring Boot 3]]></title>
            <link>https://danielangel22.medium.com/stop-using-autowired-the-better-way-to-inject-dependencies-in-spring-boot-3-80bde11fa5fb?source=rss-a93aad8008b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/80bde11fa5fb</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[technology-news]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Daniel Angel]]></dc:creator>
            <pubDate>Wed, 05 Mar 2025 21:08:52 GMT</pubDate>
            <atom:updated>2025-03-05T21:09:49.348Z</atom:updated>
            <content:encoded><![CDATA[<p>Since Spring Boot 3 and Spring Framework 6, the use of @Autowired for dependency injection has been discouraged. Instead, Spring recommends using constructor-based dependency injection. But why this change, and what is the best way to inject dependencies now? Let&#39;s explore it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dM36IYNReH3oAKyU" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is @Autowired?</h3><p>Before discussing why Spring no longer recommends @Autowired, let&#39;s quickly review its purpose. @Autowired is used to inject dependencies into a class. It can be applied to:</p><ul><li>Fields</li><li>Constructors</li><li>Setter methods</li></ul><p>This allows Spring to automatically resolve and assign the required beans when the application starts.</p><p>Classic example of @Autowired in a field:</p><pre>@Service<br>public class MyService {<br>    @Autowired<br>    private MyRepository myRepository;<br>}</pre><p>In this case, Spring injects an instance of MyRepository when creating MyService. While this works, it has several drawbacks, especially in larger, more complex applications.</p><h3>Why Doesn’t Spring Recommend @Autowired Anymore?</h3><h3>1. Encourages Immutable Dependencies</h3><p>When we use @Autowired on fields, dependencies can accidentally be modified within the class, which goes against the principle of immutability. In contrast, constructor injection ensures that dependencies are assigned only once during bean creation.</p><h3>2. Facilitates Unit Testing</h3><p>Using constructor injection makes it much easier to provide mock dependencies for unit testing, as they can be explicitly passed into the constructor without needing Spring.</p><p>Example with @Autowired:</p><pre>public class MyServiceTest {<br>    @InjectMocks<br>    private MyService myService;<br>    <br>    @Mock<br>    private MyRepository myRepository;<br>    <br>    @BeforeEach<br>    void setup() {<br>        MockitoAnnotations.openMocks(this);<br>    }<br>}</pre><p>Example with constructor injection (no need for @InjectMocks):</p><pre>public class MyServiceTest {<br>    private MyService myService;<br>    <br>    @Mock<br>    private MyRepository myRepository;<br>    <br>    @BeforeEach<br>    void setup() {<br>        myService = new MyService(myRepository);<br>    }<br>}</pre><h3>3. Avoids Reflection Issues</h3><p>When @Autowired is used on private fields, Spring uses reflection to inject dependencies, which can impact performance and code clarity. Constructor injection is a cleaner and more efficient alternative.</p><h3>The New Recommended Approach: Constructor Injection</h3><p>In Spring Boot 3, the best practice is to inject dependencies via constructors and omit @Autowired, as Spring implicitly applies it in classes with a single constructor.</p><p>Example:</p><pre>@Service<br>public class MyService {<br>    private final MyRepository myRepository;<br>    <br>    public MyService(MyRepository myRepository) {<br>        this.myRepository = myRepository;<br>    }<br>}</pre><p>Benefits of this approach:</p><ul><li><strong>Immutability</strong>: myRepository is final, preventing accidental reassignments.</li><li><strong>Readability</strong>: The code explicitly states its dependencies.</li><li><strong>Easy to test</strong>: Mocks can be passed without additional tools.</li></ul><h3>Exception: Multiple Optional Dependencies</h3><p>If a dependency is optional, @Autowired can still be used in the constructor along with @Nullable or Optional:</p><pre>@Service<br>public class MyService {<br>    private final MyRepository myRepository;<br>    private final Optional&lt;AuditService&gt; auditService;<br>    <br>    @Autowired<br>    public MyService(MyRepository myRepository, @Nullable AuditService auditService) {<br>        this.myRepository = myRepository;<br>        this.auditService = Optional.ofNullable(auditService);<br>    }<br>}</pre><h3>Conclusion</h3><p>Spring Boot 3 and Spring Framework 6 have made an effort to improve security, testability, and code clarity by promoting constructor-based dependency injection instead of @Autowired on fields. This change not only enhances immutability but also simplifies unit testing and improves application performance.</p><p>If you’re still using @Autowired on fields, now is a great time to migrate to constructor injection and take advantage of modern Spring best practices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80bde11fa5fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Send Messages to Slack with Spring Boot Easily and Without Dependencies]]></title>
            <link>https://danielangel22.medium.com/how-to-send-messages-to-slack-with-spring-boot-easily-and-without-dependencies-4a72db8aaf7c?source=rss-a93aad8008b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a72db8aaf7c</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[integration]]></category>
            <category><![CDATA[slack]]></category>
            <category><![CDATA[webhooks]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Daniel Angel]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 17:04:15 GMT</pubDate>
            <atom:updated>2024-09-16T17:05:50.959Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CSNrAM3dHbE-_HIS" /><figcaption>Photo by <a href="https://unsplash.com/@scottwebb?utm_source=medium&amp;utm_medium=referral">Scott Webb</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><ol><li><strong>What is Slack and How Does the Slack API Work?</strong></li></ol><p>Slack is a messaging platform focused on teamwork. It allows companies to create communication channels for different projects and work teams and offers a wide range of integrations with other tools and services.</p><p>The Slack API is a set of endpoints that allow other applications to send and receive messages through Slack. To use the Slack API, you must first create an application on the Slack platform and obtain an access token. Then, you can use any of the API endpoints to send and receive messages through Slack.</p><blockquote>Can you access the content of the link without membership from the first comment</blockquote><blockquote>This is a revised and improved copy of my previously published story in Spanish.</blockquote><p><a href="https://danielangel22.medium.com/integrando-slack-y-spring-boot-c%C3%B3mo-enviar-mensajes-desde-aplicaciones-java-c5730a6a222f">Integrando Slack y Spring Boot: cómo enviar mensajes desde aplicaciones Java</a></p><p><strong>2. Creating a Slack Application and Obtaining the Access Token for the API</strong></p><p>To start integrating Slack with your Spring Boot application, you first need to create a Slack application. Follow these steps:</p><ol><li><strong>Sign up or log in to Slack</strong>: If you don’t already have a Slack account, create one at <a href="https://slack.com/">Slack.com</a>. Once logged in, create or select a workspace where you want the application to be used.</li><li><strong>Create a new application</strong>: Go to the Slack API page and click “Create New App”. You will be prompted to name your app and choose the workspace where it will be installed.</li><li><strong>Obtain the access token</strong>: After setting up your app, navigate to the “OAuth &amp; Permissions” section. Here, you’ll find the “OAuth Tokens for Your Workspace”. Click “Install App to Workspace” to generate an access token. This token is crucial, as it will allow your Spring Boot application to authenticate and interact with the Slack API.</li><li><strong>Add permissions</strong>: Make sure your app has the necessary scopes (permissions) to send messages. In the same “OAuth &amp; Permissions” section, under “Scopes”, add the chat:write permission to allow your app to post messages on behalf of users or in specific channels.</li></ol><p>Once these steps are completed, you will have everything you need: your Slack app is configured, and you have the access token ready to integrate with your Spring Boot application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*yOjd5faMWoQ5oxIR.png" /></figure><p><strong>Next, search for the “Incoming Webhooks” app.</strong></p><p>Once your Slack application is set up, you need to enable the <strong>Incoming Webhooks</strong> feature, which allows external applications (like your Spring Boot app) to send messages to Slack channels through simple HTTP requests. Here’s how to do it:</p><ol><li><strong>Enable Incoming Webhooks</strong>: In the settings for your Slack app, go to the “Incoming Webhooks” section, and toggle the switch to activate it.</li><li><strong>Create a Webhook URL</strong>: Once Incoming Webhooks are enabled, click the “Add New Webhook to Workspace” button. You’ll be asked to select the channel where the messages will be sent. After selecting a channel, Slack will generate a unique Webhook URL for that channel.</li><li><strong>Save the Webhook URL</strong>: This URL is what you’ll use in your Spring Boot application to send messages to the selected Slack channel. Keep it safe as you’ll need it later to make HTTP requests directly from your application.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*bMxeEHFiKv9DYdhr.png" /></figure><p><strong>Click on the card and add it to a Slack workspace.</strong></p><p>Once you’ve found the Incoming Webhooks app, click on its card to open the details. From here, you’ll need to add the app to a specific Slack workspace where you want the messages to be sent.</p><ol><li><strong>Select the workspace</strong>: After clicking on the Incoming Webhooks card, you’ll be prompted to choose the workspace where the app will be installed. Make sure to select the correct workspace, especially if you manage multiple Slack environments.</li><li><strong>Authorize the app</strong>: You’ll be asked to authorize the app’s access to your selected workspace. Click “Allow” to grant the necessary permissions. This step ensures that your Slack app can send messages to the channels in that workspace.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*aocRjNbavgzJzwan.png" /></figure><p><strong>Select the channel where you want to publish your messages.</strong></p><p>After authorizing the Incoming Webhooks app, the next step is to choose the Slack channel where you want your messages to be posted. When creating a new Webhook URL, Slack will prompt you to select a specific channel from your workspace.</p><ol><li><strong>Channel selection</strong>: In the popup window, choose the desired channel from the list. This could be a public channel where your team communicates, or a private channel if the messages should be limited to certain users.</li><li><strong>Custom Webhook URL</strong>: Once the channel is selected, Slack will generate a unique Webhook URL for that specific channel. This URL is what your Spring Boot application will use to send messages to the selected channel via HTTP request</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*vEqkU5kfiO5BLu75.png" /></figure><p><strong>Copy the API link; this will be the one we use to connect our REST API in Spring Boot to send messages.</strong></p><p>Once you have generated the Webhook URL for the selected Slack channel, copy the URL. This Webhook URL will serve as the endpoint for your Spring Boot application to send messages to Slack.</p><ol><li><strong>Copy the Webhook URL</strong>: After selecting the channel, Slack will generate a unique Webhook URL. This URL is a key part of the integration as it allows your Spring Boot application to send messages by making simple HTTP POST requests.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*J-_dDWMRnYkvvIam.png" /></figure><p><strong>3. Installing the Slack Dependency in Your Spring Boot Project</strong></p><p>For integrating Slack into your Spring Boot application, you only need the basic dependencies provided by Spring Boot itself. You don’t need to add any third-party dependencies for this integration. Here’s what you need to do:</p><ol><li><strong>Add Spring Web Dependency</strong>: In your pom.xml file (for Maven) or build.gradle file (for Gradle), ensure you have the spring-boot-starter-web dependency. This starter includes everything needed to create RESTful web services, which is essential for sending HTTP requests to Slack.</li></ol><p>For Maven, add the following dependency:</p><pre>&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;</pre><p>For Gradle, add this line to your build.gradle file:</p><pre>implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;</pre><p>2. <strong>Include DevTools (optional)</strong>: You can also include Spring Boot DevTools for development convenience, but it’s not required for the Slack integration itself. DevTools provides additional features like automatic restarts and live reloads.</p><p>For maven:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-devtools&lt;/artifactId&gt;<br>    &lt;optional&gt;true&lt;/optional&gt;<br>&lt;/dependency&gt;</pre><p>For gradle:</p><pre>developmentOnly &#39;org.springframework.boot:spring-boot-devtools&#39;</pre><p><strong>Next, we need to add the Webhook URL to our </strong><strong>application.properties.</strong></p><p>To properly configure your Spring Boot application to send messages to Slack, you should store the Webhook URL in your application.properties file. This practice helps manage configurations more effectively and keeps sensitive information secure.</p><ol><li><strong>Open </strong><strong>application.properties</strong>: Locate the application.properties file in the src/main/resources directory of your Spring Boot project.</li><li><strong>Add the Webhook URL</strong>: Add a new property for the Slack Webhook URL. For example:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/0*1YLNTc4tnbmxncBL.png" /></figure><p><strong>Create a DTO with the following properties.</strong></p><p>Here’s how to create a Data Transfer Object (DTO) for sending messages to Slack using Spring Boot. This DTO will help encapsulate the properties required to send a message through the Slack API.</p><pre>import java.io.Serializable;<br><br>public class SlackMessage implements Serializable {<br><br>    private static final long serialVersionUID = 1L;<br><br>    private String username; // Direct user to whom the message will be sent<br>    private String text; // The message content<br>    private String icon_emoji; // Customizable Slack bot icon<br>    private String channel; // Channel to send the message<br><br>    // Default constructor<br>    public SlackMessage() {}<br><br>    // Parameterized constructor<br>    public SlackMessage(String username, String text, String icon_emoji, String channel) {<br>        this.username = username;<br>        this.text = text;<br>        this.icon_emoji = icon_emoji;<br>        this.channel = channel;<br>    }<br><br>    // Getters and setters<br>    public String getUsername() {<br>        return username;<br>    }<br><br>    public void setUsername(String username) {<br>        this.username = username;<br>    }<br><br>    public String getText() {<br>        return text;<br>    }<br><br>    public void setText(String text) {<br>        this.text = text;<br>    }<br><br>    public String getIcon_emoji() {<br>        return icon_emoji;<br>    }<br><br>    public void setIcon_emoji(String icon_emoji) {<br>        this.icon_emoji = icon_emoji;<br>    }<br><br>    public String getChannel() {<br>        return channel;<br>    }<br><br>    public void setChannel(String channel) {<br>        this.channel = channel;<br>    }<br>}</pre><p><strong>4. Creating a Spring Component to Send Messages to Slack</strong></p><p>In this step, we’ll create a Spring component in a service package that will use RestTemplate to handle the HTTP request for sending messages to Slack.</p><pre>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.http.HttpEntity;<br>import org.springframework.http.HttpHeaders;<br>import org.springframework.http.MediaType;<br>import org.springframework.stereotype.Component;<br>import org.springframework.web.client.RestTemplate;<br><br>@Component<br>public class SlackComponent {<br><br>    @Value(&quot;${slack.webhook.url}&quot;)<br>    private String slackWebhookUrl;<br><br>    public Object sendMessageNative(SlackMessage message) {<br>        // Create an instance of RestTemplate<br>        RestTemplate restTemplate = new RestTemplate();<br><br>        // Set the headers for the request<br>        HttpHeaders headers = new HttpHeaders();<br>        headers.setContentType(MediaType.APPLICATION_JSON);<br><br>        // Create the request entity with the SlackMessage payload and headers<br>        HttpEntity&lt;SlackMessage&gt; request = new HttpEntity&lt;&gt;(message, headers);<br><br>        // Send the POST request to the Slack webhook URL<br>        return restTemplate.postForObject(slackWebhookUrl, request, String.class);<br>    }<br>}</pre><h3>Explication:</h3><ol><li><strong>@Component</strong>: We define SlackComponent as a Spring-managed bean using the @Component annotation.</li><li><strong>Webhook URL injection</strong>: We use the @Value annotation to inject the Slack webhook URL, which is stored in the application.properties.</li><li><strong>RestTemplate</strong>: This is used to send the HTTP POST request to Slack.</li><li><strong>Headers and payload</strong>: We set the content type to application/json and use SlackMessage as the request body.</li></ol><p>This simple component allows you to easily send messages from your Spring Boot application to a Slack channel using the Webhook URL and RestTemplate.</p><p><strong>Keep in mind that </strong><strong>slackWebhookUrl uses the value defined earlier in the </strong><strong>application.properties file of our application.</strong></p><p>With this setup, we should be able to perform a unit test to verify that our component works correctly. Let’s define a simple unit test for the SlackComponent.</p><h3>Unit Test for SlackComponent</h3><p>To test the SlackComponent, we’ll use Spring Boot’s testing support along with mocking to simulate the interaction with Slack. Here’s an example of how you can write a unit test using JUnit and Mockito:</p><pre>import org.junit.jupiter.api.Test;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.boot.test.context.SpringBootTest;<br>import static org.junit.jupiter.api.Assertions.assertEquals;<br><br>@SpringBootTest<br>class SlackMessagingSpringbootApplicationTests {<br><br>    @Autowired<br>    private SlackComponent slackComponent;<br><br>    @Test<br>    void testSendMessage() {<br>        // Given<br>        String message = &quot;Hola mundo desde junit :heart: :smile:&quot;;<br>        SlackMessage slackMessage = new SlackMessage();<br>        slackMessage.setText(message);<br>        slackMessage.setChannel(&quot;varios&quot;);<br>        // slackMessage.setIcon_emoji(&quot;:smiley:&quot;); // Uncomment if needed<br>        <br>        // When<br>        var response = slackComponent.sendMessageNative(slackMessage);<br>        <br>        // Then<br>        assertEquals(&quot;ok&quot;, response); // Adjust the expected response as per Slack&#39;s actual response<br>    }<br>}</pre><p>When running our test, you would receive the message in the “varios” channel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*U4Zxs6PMEynz-bvV.png" /></figure><p><strong>5. Injecting the Slack Component Where Messages Need to Be Sent</strong></p><p>To complete our API, we will create a controller that injects the SlackComponent and exposes a method to send messages through it. This allows you to use this method from anywhere else in the application.</p><pre>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.*;<br><br>@RestController<br>public class SlackController {<br><br>    @Autowired<br>    private SlackComponent slackComponent;<br><br>    @PostMapping(&quot;/send&quot;)<br>    public ResponseEntity&lt;?&gt; sendMessage(@RequestBody SlackMessage slackRequest) {<br>        // Use SlackComponent to send the message<br>        Object response = slackComponent.sendMessageNative(slackRequest);<br>        return ResponseEntity.ok(response); // Return the response from SlackComponent<br>    }<br>}</pre><p>As the final step, test it using Postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*lG5MlIaWteO7jI8r.png" /></figure><p>And this would be the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*UnOHkjFV44JWRJd9.png" /></figure><p><strong>6. Sending Messages with Emojis and Attachments to Slack</strong></p><p>To include emojis and images in a Slack message from your API, you need to use Slack’s message formatting.</p><h4>Emojis in Slack Messages</h4><p>To include emojis in the text of a message, you should use Slack’s emoji formatting. Here’s how to include emojis in your Slack message:</p><ol><li><strong>Slack Emoji Syntax</strong>:</li></ol><ul><li><strong>Basic Emoji</strong>: Use :emoji_name: where emoji_name is the name of the emoji. For example, :smile: will display a smiley face.</li><li><strong>Custom Emoji</strong>: If your workspace has custom emojis, you can use them with the format :custom_emoji_name:.</li></ul><p>Sample:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/0*5ajmSoDWEB2rA6hp.png" /></figure><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/0*pWbjW1XRQUetz0Ud.png" /></figure><p><strong>You can also add an </strong><strong>emoji_message field to our DTO and then concatenate it to the message to provide a better segmentation experience, though it&#39;s not necessary for this example.</strong></p><p><strong>Yes, it’s possible to include images directly in the text of a message using Slack’s formatting, which allows for adding links and formatting text in various ways.</strong></p><h4>Including Images Directly in the Message Text</h4><p>To include an image directly within the text of a Slack message, you can use Markdown-style formatting. Here’s how to format your message to include an image:</p><p><strong>Image Format</strong>:</p><ul><li>Use the following format to include an image in the text of the message:</li></ul><pre>![alt_text](image_url)</pre><ul><li><strong>alt_text</strong>: This is the alternative text for the image, which describes the content for users who might not be able to view it.</li><li><strong>image_url</strong>: This is the URL of the image you want to include.</li></ul><p><strong>Example</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*udcoCnX9oOp78tfy.png" /></figure><p><strong>Result:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*ZRNKUVg5GACdl_Q_.png" /></figure><p><strong>With this, we conclude our tutorial on how to integrate the Slack API easily into a Spring Boot application. It is also possible to perform this integration using OpenFeign or WebClient. If you have any questions, feel free to contact me or let me know if you would like a tutorial on using these libraries.</strong></p><p><strong>GitHub Repository</strong>: <a href="https://github.com/danielangel22/slack-messaging-springboot">https://github.com/danielangel22/slack-messaging-springboot</a></p><p>Thanks for reading!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a72db8aaf7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convert CSV Files to SQL Scripts (INSERT, UPDATE, DELETE) and Export to .SQL File in Java]]></title>
            <link>https://danielangel22.medium.com/convert-csv-files-to-sql-scripts-insert-update-delete-and-export-to-sql-file-in-java-635eb1d4b972?source=rss-a93aad8008b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/635eb1d4b972</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[csv]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Daniel Angel]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 21:39:08 GMT</pubDate>
            <atom:updated>2024-09-13T21:50:57.272Z</atom:updated>
            <content:encoded><![CDATA[<h3>Convert CSV Files to SQL Scripts (INSERT, UPDATE, DELETE) and Export to .SQL File in Java</h3><p>Many times, when working with large datasets stored in CSV files, especially those with up to a million records, it’s common to need to migrate or update that data in a relational database. Depending on the context, you may need to insert new records, update existing ones, or even delete some records from the database.</p><p>In this tutorial, we’ll walk through the process of converting a CSV file into different SQL scripts (INSERT, UPDATE, and DELETE) using Java, and then export those scripts into a .sql file. We&#39;ll ensure the program is optimized for large datasets by handling the file writing process efficiently, let’s go.</p><blockquote><strong>In the comments is the link so you can read it if you are not members.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mD2l6z4t9brL61FQ" /><figcaption>Photo by <a href="https://unsplash.com/@laviperchik?utm_source=medium&amp;utm_medium=referral">Lavi Perchik</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>Prerequisites</strong></h4><p>Before we start, make sure you have the following:</p><ol><li><strong>Java</strong> installed on your machine.</li><li>A <strong>CSV file</strong> containing your data.</li><li>A basic understanding of Java programming and SQL.</li></ol><p>Here’s an example of the structure of the CSV file:</p><pre>id,name,email,level<br>1,Fredy Watt,fredy.watt@example.com,30<br>2,Jade Smith,jade.smith@example.com,25<br>3,Bob sponge,bob.sponge@example.com,40</pre><h3>Step 1: Reading the CSV File</h3><p>First, we’ll write a method to read the CSV file. In Java, we can use the BufferedReader to process the file line by line.</p><pre>import java.io.BufferedReader;<br>import java.io.FileReader;<br>import java.io.IOException;<br>import java.util.ArrayList;<br>import java.util.List;<br><br>public class CSVReader {<br><br>     public static List&lt;String[]&gt; readCSV(String filePath) {<br>        List&lt;String[]&gt; records = new ArrayList&lt;&gt;();<br>        ClassPathResource resource = new ClassPathResource(filePath);<br>        try (BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()))) {<br>            String line;<br>            while ((line = br.readLine()) != null) {<br>                String[] values = line.split(&quot;,&quot;);<br>                records.add(values);<br>            }<br>        } catch (IOException e) {<br>            e.printStackTrace();<br>        }<br>        return records;<br>    }<br>}</pre><p>This method reads each line of the CSV file, splits it by commas, and stores the resulting data in a list of string arrays.</p><h3>Step 2: Generating SQL INSERT, UPDATE, and DELETE Statements</h3><p>We’ll now create methods to generate SQL scripts for INSERT, UPDATE, and DELETE queries, in this same way the select could be generated but it was omitted for this example.</p><pre><br><br>public class SQLGenerator {<br><br>    public static String generateInsert(String tableName, String[] headers, String[] values) {<br>        StringBuilder query = new StringBuilder(&quot;INSERT INTO &quot;);<br>        query.append(tableName).append(&quot; (&quot;);<br><br>        for (int i = 0; i &lt; headers.length; i++) {<br>            query.append(headers[i]);<br>            if (i &lt; headers.length - 1) query.append(&quot;, &quot;);<br>        }<br><br>        query.append(&quot;) VALUES (&quot;);<br><br>        for (int i = 0; i &lt; values.length; i++) {<br>            query.append(&quot;&#39;&quot;).append(values[i]).append(&quot;&#39;&quot;);<br>            if (i &lt; values.length - 1) query.append(&quot;, &quot;);<br>        }<br><br>        query.append(&quot;);&quot;);<br>        return query.toString();<br>    }<br><br>    public static String generateUpdate(String tableName, String[] headers, String[] values, String idColumn, String idValue) {<br>        StringBuilder query = new StringBuilder(&quot;UPDATE &quot;);<br>        query.append(tableName).append(&quot; SET &quot;);<br><br>        for (int i = 0; i &lt; headers.length; i++) {<br>            query.append(headers[i]).append(&quot; = &#39;&quot;).append(values[i]).append(&quot;&#39;&quot;);<br>            if (i &lt; headers.length - 1) query.append(&quot;, &quot;);<br>        }<br><br>        query.append(&quot; WHERE &quot;).append(idColumn).append(&quot; = &#39;&quot;).append(idValue).append(&quot;&#39;;&quot;);<br>        return query.toString();<br>    }<br><br>    /**<br>     * <br>     * @param tableName name of de table that build script.<br>     * @param idColumn name of identification.<br>     * @param idValue value of the identification colum.<br>     * @return<br>     */<br>    public static String generateDelete(String tableName, String idColumn, String idValue) {<br>        return &quot;DELETE FROM &quot; + tableName + &quot; WHERE &quot; + idColumn + &quot; = &#39;&quot; + idValue + &quot;&#39;;&quot;;<br>    }<br>}<br><br></pre><p>These methods will generate SQL queries based on the CSV data. The INSERT method generates an INSERT INTO statement, while the UPDATE method creates an UPDATE query with a WHERE clause and the DELETE method creates a DELETE statement based on the record ID, this can be very useful when migrating data from a database. in excel to a SQL base.</p><h3>Step 3: Writing SQL Queries to a .sql File</h3><p>Now, instead of printing the queries to the console, we’ll write them to a .sql file. Since the dataset can be large (up to a million records), we’ll use a BufferedWriter to handle the file writing efficiently.</p><pre><br>import java.io.BufferedWriter;<br>import java.io.File;<br>import java.io.FileWriter;<br>import java.io.IOException;<br>import java.util.List;<br><br>/**<br> * Class of build sql file<br> */<br>public class SQLFileWriter {<br><br>    public static void writeSQLFile(String filePathResult, List&lt;String[]&gt; records, String tableName, String idColumn) {<br>        File directory = new File(&quot;src\\main\\resources&quot;);<br>        if (!directory.exists()) {<br>            boolean dirCreated = directory.mkdirs(); // Create directory if not exists<br>            if (!dirCreated) {<br>                return;<br>            }<br>        }<br><br>        // Create a complete route for the file<br>        String filePath = directory.getPath() + File.separator + filePathResult;<br>        try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(filePath)))) {<br>            String[] headers = records.get(0); // First row is headers (columns of table)<br><br>            for (int i = 1; i &lt; records.size(); i++) {<br>                String[] values = records.get(i);<br>                String idValue = values[0]; // Assuming the first column is the &#39;id&#39;<br><br>                // Generate INSERT query<br>                String insertQuery = SQLGenerator.generateInsert(tableName, headers, values);<br>                writer.write(insertQuery);<br>                writer.newLine();<br>                System.out.println(&quot;Generating insert..&quot;);<br><br>                // Generate UPDATE query<br>                String updateQuery = SQLGenerator.generateUpdate(tableName, headers, values, idColumn, idValue);<br>                writer.write(updateQuery);<br>                writer.newLine();<br>                System.out.println(&quot;Generating update.&quot;);<br><br>                // Generate DELETE query<br>                String deleteQuery = SQLGenerator.generateDelete(tableName, idColumn, idValue);<br>                writer.write(deleteQuery);<br>                writer.newLine();<br>                System.out.println(&quot;Generating delete&quot;);<br><br>                // Flush periodically to handle large files efficiently<br>                if (i % 10000 == 0) {<br>                    writer.flush();<br>                }<br>            }<br><br>        } catch (IOException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}<br><br></pre><h3>Step 4: Main Class to Run the Process</h3><p>Finally, we’ll create the main class that ties everything together. This class reads the CSV file and writes the SQL queries to the output .sql file.</p><pre>public class CSVtoSQLConverter {<br><br>    public static void main(String[] args) {<br>        String csvFilePath = &quot;data.csv&quot;; // Path to your CSV file<br>        String sqlFilePath = &quot;output.sql&quot;; // Output SQL file<br>        String tableName = &quot;users&quot;; // your table name<br>        String idColumn = &quot;id&quot;; //name the column used to identify the record<br><br>        // Read CSV file<br>        List&lt;String[]&gt; records = CSVReader.readCSV(csvFilePath);<br><br>        // Write SQL file<br>        SQLFileWriter.writeSQLFile(sqlFilePath, records, tableName, idColumn);<br><br>        System.out.println(&quot;SQL file generated successfully!&quot;);<br>    }<br>}</pre><h3>Step 5: Running the Code</h3><p>When you run the program, it will create an output.sql file containing all the INSERT, UPDATE, and DELETE queries based on the CSV data.</p><p>Here’s an example of the content of the .sql file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EdEdGUnW3pfXmWmnYhTvsg.png" /></figure><h3>Optimizing for Large Datasets</h3><p>Handling a CSV file with up to a million records can cause memory issues if not optimized. Here are some strategies we implemented to optimize the process:</p><ul><li><strong>BufferedReader/BufferedWriter:</strong> We use BufferedReader for reading the CSV file and BufferedWriter for writing the .sql file to minimize memory usage.</li><li><strong>Flushing the Writer:</strong> For large datasets, we periodically flush the BufferedWriter every 10,000 records to prevent the buffer from growing too large.</li><li><strong>Efficient Memory Handling:</strong> Since we are processing the records sequentially and writing them to a file, the memory footprint is kept low.</li></ul><h3>Conclusion</h3><p>By following this approach, you can efficiently convert a CSV file into SQL scripts for INSERT, UPDATE, and DELETE operations, and write them to a .sql file. This solution scales well even for large datasets of up to a million records.</p><p>With these optimizations in place, your application can handle large volumes of data while maintaining good performance and low memory usage. You can further enhance the logic to meet your specific requirements, such as adding data validation or dealing with edge cases in the CSV file.</p><p>Happy coding!</p><h4>Github: <a href="https://github.com/danielangel22/Useful-Algorithms-for-Daily-Tasks/tree/main/csv-to-sql-scripts-converter">https://github.com/danielangel22/Useful-Algorithms-for-Daily-Tasks/tree/main/csv-to-sql-scripts-converter</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=635eb1d4b972" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create an OpenFeign Client with Resilience4j]]></title>
            <link>https://danielangel22.medium.com/how-to-create-an-openfeign-client-with-resilience4j-f9e7a6d87282?source=rss-a93aad8008b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9e7a6d87282</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[resilience]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[feignclient]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Daniel Angel]]></dc:creator>
            <pubDate>Wed, 11 Sep 2024 00:44:23 GMT</pubDate>
            <atom:updated>2024-09-11T00:44:23.100Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, you will learn how to create an OpenFeign client with Resilience4j to handle failures and improve the resilience of your Spring Boot applications. We will go step-by-step through the configuration and integration of these components to build a robust and fault-tolerant application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ndqQui7e1BWOM7DE" /><figcaption>Photo by <a href="https://unsplash.com/@faithgiant?utm_source=medium&amp;utm_medium=referral">Alex Shute</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>OpenFeign is a declarative HTTP client that simplifies calling web services, while Resilience4j is a library that provides resilience patterns such as Circuit Breaker, Rate Limiter, Retry, and Bulkhead. By combining them, we can build applications that handle failures gracefully.</p><h3>Prerequisites</h3><p>Before you start, ensure you have:</p><ul><li>Java JDK 11 or higher.</li><li>Maven.</li><li>Basic knowledge of Spring Boot.</li></ul><h3>Project Setup</h3><ol><li><strong>Initialize a new Spring Boot project:</strong></li></ol><ul><li>Go to <a href="https://start.spring.io/">Spring Initializr</a> and set up your project with the following dependencies:</li><li>Spring web</li><li>OpenFeign</li><li>Resilience4j</li><li>Download and unzip the project.</li></ul><p>2. <strong>Add dependencies in your </strong><strong>pom.xml:</strong></p><pre>&lt;dependencies&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-cloud-starter-openfeign&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;io.github.resilience4j&lt;/groupId&gt;<br>        &lt;artifactId&gt;resilience4j-spring-boot2&lt;/artifactId&gt;<br>        &lt;version&gt;1.7.1&lt;/version&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;io.github.resilience4j&lt;/groupId&gt;<br>        &lt;artifactId&gt;resilience4j-micrometer&lt;/artifactId&gt;<br>        &lt;version&gt;1.7.1&lt;/version&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;<br><br>&lt;dependencyManagement&gt;<br>    &lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;<br>            &lt;version&gt;Hoxton.SR9&lt;/version&gt;<br>            &lt;type&gt;pom&lt;/type&gt;<br>            &lt;scope&gt;import&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br>&lt;/dependencyManagement&gt;</pre><h4>Creating the OpenFeign Client</h4><ol><li>Enable Feign in your main application class:</li></ol><pre>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.cloud.openfeign.EnableFeignClients;<br><br>@SpringBootApplication<br>@EnableFeignClients<br>public class FeignResilienceApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.run(FeignResilienceApplication.class, args);<br>    }<br>}</pre><p>2. Create a Feign interface for your client:</p><pre>import org.springframework.cloud.openfeign.FeignClient;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RequestParam;<br><br>@FeignClient(name = &quot;exampleClient&quot;, url = &quot;https://api.example.com&quot;)<br>public interface ExampleClient {<br>    @GetMapping(&quot;/data&quot;)<br>    String getData(@RequestParam(name = &quot;param&quot;) String param);<br>}</pre><h4>Integration with Resilience4j</h4><ol><li>Add the @CircuitBreaker annotation to your Feign method:</li></ol><pre>import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;<br><br>@FeignClient(name = &quot;exampleClient&quot;, url = &quot;https://api.example.com&quot;)<br>public interface ExampleClient {<br>    @GetMapping(&quot;/data&quot;)<br>    @CircuitBreaker(name = &quot;exampleClient&quot;, fallbackMethod = &quot;fallbackGetData&quot;)<br>    String getData(@RequestParam(name = &quot;param&quot;) String param);<br><br>    default String fallbackGetData(String param, Throwable throwable) {<br>        return &quot;Fallback response due to: &quot; + throwable.getMessage();<br>    }<br>}</pre><h4>Resilience4j Configuration</h4><ol><li>Configure Resilience4j in your application.yml file:</li></ol><pre>resilience4j:<br>  circuitbreaker:<br>    instances:<br>      exampleClient:<br>        registerHealthIndicator: true<br>        slidingWindowSize: 10<br>        permittedNumberOfCallsInHalfOpenState: 3<br>        minimumNumberOfCalls: 5<br>        waitDurationInOpenState: 10000<br>        failureRateThreshold: 50<br>        eventConsumerBufferSize: 10<br>        recordExceptions:<br>          - org.springframework.web.client.HttpServerErrorException<br>          - java.io.IOException<br>        ignoreExceptions:<br>          - org.springframework.web.client.HttpClientErrorException$NotFound</pre><h4>Create a controller to test the Feign client:</h4><pre>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RequestParam;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController<br>public class ExampleController {<br>    <br>    @Autowired<br>    private ExampleClient exampleClient;<br><br>    @GetMapping(&quot;/fetch-data&quot;)<br>    public String fetchData(@RequestParam String param) {<br>        return exampleClient.getData(param);<br>    }<br>}</pre><h4>Run your application:</h4><pre>./mvnw spring-boot:run</pre><p><a href="https://danielangel22.medium.com/how-to-generate-massive-pdfs-java-spring-a3f2b136ab9c">How to generate massive PDFs | Java |Spring</a></p><p><strong>Conclusion</strong></p><p>In summary, integrating <strong>Feign Client</strong> with <strong>Resilience4j</strong> allows us to build resilient and robust applications, prepared to handle temporary failures in communication with external services. Throughout the article, we explored how to configure a Feign client and apply fault tolerance patterns like circuit breakers, timeouts, and retries. This approach helps mitigate network failures and ensures our applications remain stable and reliable even in distributed environments.</p><p>Adopting these practices not only improves the user experience by reducing wait times and unexpected errors, but also enhances the scalability and maintainability of our applications, aligning with modern design principles for microservices.</p><p>It’s important to remember that while Resilience4j provides an excellent set of tools, we must always adjust its configuration according to the requirements and expected behavior of our application to avoid introducing unnecessary overhead. With proper implementation, our microservices will be better equipped to handle failures and continue operating under adverse conditions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9e7a6d87282" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to generate massive PDFs | Java |Spring]]></title>
            <link>https://danielangel22.medium.com/how-to-generate-massive-pdfs-java-spring-a3f2b136ab9c?source=rss-a93aad8008b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3f2b136ab9c</guid>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[rest]]></category>
            <dc:creator><![CDATA[Daniel Angel]]></dc:creator>
            <pubDate>Sat, 02 Mar 2024 06:10:58 GMT</pubDate>
            <atom:updated>2024-03-02T06:10:58.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CYul9C1I-sSlTJIZ" /><figcaption>Photo by <a href="https://unsplash.com/@fin21?utm_source=medium&amp;utm_medium=referral">FIN</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In the development of enterprise applications, there’s often a need to generate multiple PDFs, such as invoices for multiple clients. In this article, we’ll explore how to create an API in Spring Boot that can generate multiple PDFs from a list of information. We’ll cover everything from project setup to code implementation, using popular libraries like iText for PDF generation, why itext? because in my opinion it is the easiest to use and most complete library to generate pdfs.</p><h4>Step 1</h4><p>Setting Up the Spring Boot Project Let’s start by creating a new Spring Boot project using Spring Initializr or your preferred IDE. Make sure to include the necessary dependencies, such as spring-boot-starter-web for creating the REST API and itext7-core the last version for PDF generation.</p><pre>&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><br>  &lt;!-- https://mvnrepository.com/artifact/com.itextpdf/itext7-core --&gt;<br> &lt;dependency&gt;<br>   &lt;groupId&gt;com.itextpdf&lt;/groupId&gt;<br>   &lt;artifactId&gt;itext7-core&lt;/artifactId&gt;<br>   &lt;version&gt;8.0.3&lt;/version&gt;<br>   &lt;type&gt;pom&lt;/type&gt;<br> &lt;/dependency&gt;</pre><h4>Step 2</h4><p>Designing the Model Class Define a model class to represent the data for each invoice. For example:</p><pre>public class Invoice {<br>  private String invoiceNumber;<br>  private String clientName;<br>  private LocalDate date;<br>  private List&lt;String&gt; details;<br>  private String titleImg;<br>  //others methods<br>}</pre><h4>Step 3</h4><p>Creating the REST Controller Create a REST controller to handle requests for generating the PDFs:</p><pre><br>import com.massive.pdfs.dtos.Invoice;<br>import com.massive.pdfs.service.PDFGenerator;<br>import java.io.IOException;<br>import java.util.List;<br>import org.springframework.http.HttpStatus;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.PostMapping;<br>import org.springframework.web.bind.annotation.RequestBody;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController<br>public class PDFController {<br>    private final PDFGenerator pdfGenerator;<br><br>    public PDFController(PDFGenerator pdfGenerator) {<br> this.pdfGenerator = pdfGenerator;<br>    }<br><br>    @PostMapping(&quot;/generate-massive-pdfs&quot;)<br>    public ResponseEntity&lt;byte[]&gt; generateMultiplePDFs(@RequestBody List&lt;Invoice&gt; invoices) {<br> try {<br>     byte[] zipContent = pdfGenerator.generatePDFs(invoices);<br>     return ResponseEntity.ok().header(&quot;Content-Disposition&quot;, &quot;attachment; filename=invoices.zip&quot;)<br>      .body(zipContent);<br> } catch (IOException e) {<br>     e.printStackTrace();<br>     return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);<br> }<br>    }<br>}</pre><h4>Step 4</h4><p>Implementing the PDF Generation Logic Implement the logic to generate the PDFs using the iText library or any other PDF generation library of your choice. You can use the generatePDF method in the controller to generate a PDF for each invoice.</p><pre>import com.itextpdf.io.image.ImageDataFactory;<br>import com.itextpdf.kernel.pdf.PdfDocument;<br>import com.itextpdf.kernel.pdf.PdfWriter;<br>import com.itextpdf.layout.Document;<br>import com.itextpdf.layout.element.Image;<br>import com.itextpdf.layout.element.Paragraph;<br>import com.itextpdf.layout.element.Table;<br>import com.itextpdf.layout.properties.TextAlignment;<br>import com.massive.pdfs.dtos.Invoice;<br>import java.io.ByteArrayOutputStream;<br>import java.io.IOException;<br>import java.net.URL;<br>import java.util.List;<br>import java.util.zip.ZipEntry;<br>import java.util.zip.ZipOutputStream;<br>import org.springframework.stereotype.Component;<br><br>@Component<br>public class PDFGenerator {<br><br><br>    private byte[] generatePDF(Invoice invoice) throws IOException {<br> ByteArrayOutputStream outputStream = new ByteArrayOutputStream();<br> try (PdfWriter writer = new PdfWriter(outputStream);<br>  PdfDocument pdfDocument = new PdfDocument(writer);<br>  Document document = new Document(pdfDocument)) {<br>     addTitleText(document, &quot;Dinamic ttitle invoice 2024&quot;);<br>     addTitleImage(document, invoice.getTitleImg(), true);<br>     addInvoiceTable(document, invoice);<br> }<br> return outputStream.toByteArray();<br>    }<br><br>    private void addTitleImage(Document document, String titleImage, boolean isExternalImg) {<br> Image image = null;<br> try {<br>     if (!isExternalImg)<br>  image = new Image(ImageDataFactory.create(titleImage));<br>     else<br>  image = new Image(ImageDataFactory.create(new URL(titleImage)));<br>     image.setWidth(100);<br>     image.setTextAlignment(TextAlignment.LEFT);<br>     document.add(image);<br> } catch (Exception e) {<br>     e.printStackTrace();<br>     System.err.println(&quot;Error to get img&quot;);<br> }<br>    }<br><br>    private void addTitleText(Document document, String titleText) {<br> Paragraph paragraph = new Paragraph(titleText).setBold().setFontSize(20).setMarginTop(20);<br> paragraph.setTextAlignment(TextAlignment.CENTER);<br> document.add(paragraph);<br>    }<br><br>    private void addInvoiceTable(Document document, Invoice invoice) {<br> Table table = new Table(2);<br> table.addCell(&quot;Invoice Number&quot;);<br><br> table.addCell(invoice.getInvoiceNumber());<br> table.addCell(&quot;Client Name&quot;);<br> table.addCell(invoice.getClientName());<br> table.addCell(&quot;Date&quot;);<br> table.addCell(invoice.getDate().toString());<br> table.addCell(&quot;Details&quot;);<br> com.itextpdf.layout.element.List list=new com.itextpdf.layout.element.List();<br> invoice.getDetails().forEach(list::add);<br> table.addCell(list);<br> document.add(table);<br>    }<br>}</pre><h4>Step 5</h4><p>Compressing the PDFs into a ZIP File Once the PDFs are generated, compress them into a ZIP file and return it as the response to the client. The client can then download the ZIP file containing all the generated PDFs.</p><pre>public byte[] generatePDFs(List&lt;Invoice&gt; invoices) throws IOException {<br> ByteArrayOutputStream zipStream = new ByteArrayOutputStream();<br> try (ZipOutputStream zipOutputStream = new ZipOutputStream(zipStream)) {<br>     for (int i = 0; i &lt; invoices.size(); i++) {<br>  Invoice invoice = invoices.get(i);<br>  byte[] pdfContent = generatePDF(invoice);<br>  zipOutputStream.putNextEntry(new ZipEntry(&quot;invoice_&quot; + (i + 1) + &quot;.pdf&quot;));<br>  zipOutputStream.write(pdfContent);<br>  zipOutputStream.closeEntry();<br>     }<br> }<br> return zipStream.toByteArray();<br>    }</pre><h4>Step 6</h4><p>Testing and Debugging Test the API thoroughly to ensure it works as expected. Send requests with different sets of invoice data and verify that the ZIP file contains the correct PDFs.</p><p>Sample of generation 10 pdfs files with simple desing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pRnE-SIZLh-AlCE4fNmp9Q.png" /><figcaption>The time is 3sg for 10 files</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZkAyu-ncRn6T09pODLjDCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WlJx00MvE7WoKuK2IaRXGg.png" /><figcaption>Content of, the image is get of the internet</figcaption></figure><p>Here are some points to consider to evaluate if the time is acceptable:</p><p>Content complexity: If the PDFs contain a large amount of data, images, or complex graphics, the generation time could be longer. In this case, 3 seconds to generate 10 PDFs could be a reasonable time.</p><p>System resources: The generation time of the PDFs may be influenced by the processing capacity of your system. If you are running the PDF generation on hardware with limited resources, such as a server with low CPU power, the generation time could be longer.</p><p>Performance requirements: If your application requires the PDFs to be generated quickly to meet user or system performance requirements, you may need to optimize the PDF generation process to reduce processing time.</p><p><a href="https://danielangel22.medium.com/preventing-xss-attacks-in-your-spring-boot-api-c266a175e011">Preventing XSS Attacks in your Spring Boot API</a></p><blockquote>The following is an improvement to the method that generates the zip file using the available processors</blockquote><pre> public byte[] generatePDFsIn(List&lt;Invoice&gt; invoices) throws IOException, InterruptedException {<br>       ByteArrayOutputStream zipStream = new ByteArrayOutputStream();<br>       try (ZipOutputStream zipOutputStream = new ZipOutputStream(zipStream)) {<br>           for (int i = 0; i &lt; invoices.size(); i++) {<br>        Invoice invoice = invoices.get(i);<br>        @SuppressWarnings(&quot;unused&quot;)<br>        ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();<br>      <br>        final int index = i;<br>        executorService.execute(() -&gt; {<br>            try {<br>         byte[] pdfContent = generatePDF(invoice);<br>         synchronized (zipOutputStream) {<br>             zipOutputStream.putNextEntry(new ZipEntry(&quot;invoice_&quot; + (index + 1) + &quot;.pdf&quot;));<br>             zipOutputStream.write(pdfContent);<br>             zipOutputStream.closeEntry();<br>         }<br>            } catch (IOException e) {<br>         e.printStackTrace();<br>            }<br>        });<br>           }<br>           executorService.shutdown();<br>           executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);<br>       }<br>       return zipStream.toByteArray();<br>    }</pre><blockquote><strong><em>Thank you very much for reading I hope this helps you if you like to support me with a coffee it is always appreciated below I will leave the link to the Github repository</em></strong></blockquote><p><a href="https://www.buymeacoffee.com/danielangel?new=1">☕️ https://www.buymeacoffee.com/danielangel?new=1</a></p><p>🔨<a href="https://github.com/danielangel22/generatemassive-pdfs-springrest">https://github.com/danielangel22/generatemassive-pdfs-springrest</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3f2b136ab9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create Custom Annotations in Java and Spring Boot]]></title>
            <link>https://danielangel22.medium.com/how-to-create-custom-annotations-in-java-and-spring-boot-a0e37c4a4550?source=rss-a93aad8008b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0e37c4a4550</guid>
            <category><![CDATA[aspect-oriented]]></category>
            <category><![CDATA[annotations]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Daniel Angel]]></dc:creator>
            <pubDate>Wed, 31 Jan 2024 04:54:04 GMT</pubDate>
            <atom:updated>2024-01-31T04:54:04.658Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*miAYk-st7RjP3YvO" /><figcaption>Photo by <a href="https://unsplash.com/@tirzavandijk?utm_source=medium&amp;utm_medium=referral">Tirza van Dijk</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Usually when we are working with Java and Spring Boot, specific needs arise that require the use of not-so-common technologies such as AOP (Aspect-Oriented Programming). This is generally used to handle specific functions that must be executed based on certain guidelines, for example.</p><p><strong>Use Case:</strong> A company needs to know how many times the user checks the account status service in a month.</p><p><strong>Solution Proposal:</strong> Create an annotation that evaluates client identifiers, for example, an ID, and records the queries made by the clients to this service, saving them in a table that can be queried. For this example, we will do it in cache.</p><p><a href="https://danielangel22.medium.com/preventing-xss-attacks-in-your-spring-boot-api-c266a175e011">Preventing XSS Attacks in your Spring Boot API</a></p><h4>Step 1: Define the annotation with parameters</h4><p>Let’s start by defining our custom annotation with parameters to detect certain values in HTTP requests:</p><pre>import java.lang.annotation.*;<br><br>@Target(ElementType.METHOD)<br>@Retention(RetentionPolicy.RUNTIME)<br>public @interface SpecificParameter {<br>    String value() default &quot;&quot;; // The value of the parameter to detect<br>}</pre><p>In this annotation, we’ve defined a value attribute that will represent the name of the parameter we want to detect in the requests.</p><h4><strong>Step 2: Using the annotation in a controller</strong></h4><p>Now, we can use our custom annotation in a Spring Boot controller to detect specific parameters in the requests:</p><pre>import org.springframework.web.bind.annotation.*;<br><br>@RestController<br>public class ExampleController {<br><br>    @GetMapping(&quot;/&quot;)<br>    @SpecificParameter(&quot;card&quot;)<br>    public String checkStatusCard(@RequestParam(name = &quot;card&quot;) String card, @RequestParam String id) {<br>        return &quot;status account for client id, &quot; + id+ &quot;!&quot;; //this is a simple example code<br>    }<br>}</pre><p>In this example, we’ve applied our @SpecificParameter annotation to the checkStatusCard() method and specified that we want to detect the parameter named &quot;card&quot;.</p><h4>Step 3: Accessing the annotation in an aspect</h4><p>To access the annotation metadata at runtime, we’ll create a Spring aspect that intercepts annotated methods and checks if the specified parameter is provided in the request:</p><pre>import org.aspectj.lang.annotation.*;<br>import org.springframework.stereotype.*;<br>import org.springframework.web.context.request.*;<br><br>@Aspect<br>@Component<br>public class SpecificParameterAspect {<br><br>    private static final Map&lt;String, Integer&gt; queryCountMap = new ConcurrentHashMap&lt;&gt;();<br><br>    public static void incrementQueryCount(String clientId) {<br>        queryCountMap.put(clientId, queryCountMap.getOrDefault(clientId, 0) + 1);<br>    }<br><br>    public static int getQueryCount(String clientId) {<br>        return queryCountMap.getOrDefault(clientId, 0);<br>    }<br><br>    @Before(&quot;@annotation(specificParameter)&quot;)<br>    public void beforeAnnotatedMethod(JoinPoint joinPoint, SpecificParameter specificParameter) {<br>        String parameterName = specificParameter.value();<br>        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();<br>        String parameterValue = request.getParameter(parameterName);<br>        if (parameterValue != null) {<br>            System.out.println(&quot;The parameter &#39;&quot; + parameterName + &quot;&#39; was detected in the request with the value: &quot; + parameterValue);<br>            incrementQueryCount(parameterValue); // Increment query count for the client ID<br>        } else {<br>            System.out.println(&quot;The parameter &#39;&quot; + parameterName + &quot;&#39; was not detected in the request.&quot;);<br>        }<br>    }<br>}</pre><p>With this cache implementation, you can increment the query count for each client ID and retrieve the query count for a specific client ID. This map can be accessed and updated by the annotation or any other part of the application as needed.</p><ul><li>The AccountStatusCache methods incrementQueryCount and getQueryCount are included in the SpecificParameterAspect.</li><li>Inside the beforeAnnotatedMethod advice, when a parameter is detected in the request, the incrementQueryCount method is called to increment the query count for the corresponding client ID.</li></ul><h4>Conclusion</h4><p>In this example, we explored the creation of a custom annotation in Java and Spring Boot to address a specific use case where a company needs to track how many times users access the account status service. By leveraging aspects and annotations, we were able to design a solution that detects client identifiers in HTTP requests and records the queries made to the service in a cache map.</p><p>This tutorial demonstrated the power and flexibility of using custom annotations and aspects in Spring Boot applications. By extending the functionality of Spring’s AOP capabilities, developers can implement domain-specific logic in a modular and reusable manner, enhancing the overall maintainability and scalability of their applications.</p><p>Through this tutorial, you should now have a solid understanding of how to create and integrate custom annotations and aspects into your Java and Spring Boot projects, empowering you to address a wide range of business requirements with elegance and efficiency.</p><blockquote>Thank you for reading</blockquote><p><a href="https://www.buymeacoffee.com/danielangel?new=1">Daniel Angel</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0e37c4a4550" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Preventing XSS Attacks in your Spring Boot API]]></title>
            <link>https://danielangel22.medium.com/preventing-xss-attacks-in-your-spring-boot-api-c266a175e011?source=rss-a93aad8008b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c266a175e011</guid>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[owasp]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[xss-attack]]></category>
            <dc:creator><![CDATA[Daniel Angel]]></dc:creator>
            <pubDate>Tue, 02 Jan 2024 21:45:04 GMT</pubDate>
            <atom:updated>2024-01-02T21:45:04.989Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uqTpSKE1EqUJ9xQV" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>XSS (Cross-Site Scripting) attacks pose a significant threat to web applications. In this tutorial, you’ll learn how to implement security measures to prevent these attacks in your Spring Boot-developed API.</p><h4>Add OWASP dependency and Spring Security</h4><pre>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.owasp.encoder&lt;/groupId&gt;<br>   &lt;artifactId&gt;encoder&lt;/artifactId&gt;<br>   &lt;version&gt;1.2.3&lt;/version&gt; <br>  &lt;/dependency&gt;<br> &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;<br>  &lt;/dependency&gt;</pre><p>An average application might lack input data prevention measures or have minimal measures in place. Here’s a basic example of a Spring Boot application without XSS security measures.</p><p><strong><em>For parameters:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*BvbGAx_NU85msyE2kitJ3Q.png" /></figure><p><strong><em>For body request:</em></strong></p><pre>{<br>    &quot;id&quot;: 1,<br>    &quot;name&quot;: &quot;&lt;script&gt;alert(&#39;Hola &gt;:)!&#39;)&lt;/script&gt;&quot;<br>}</pre><h3>Step 1: Create the XSS Protection Filter</h3><p>The XSSFilter intercepts incoming requests and applies the necessary sanitization to prevent XSS attacks.</p><pre>import javax.servlet.*;<br>import javax.servlet.annotation.WebFilter;<br>import java.io.IOException;<br><br>@WebFilter(&quot;/*&quot;)<br>public class XSSFilter implements Filter {<br><br>    @Override<br>    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)<br>            throws IOException, ServletException {<br>        chain.doFilter(new XSSRequestWrapper((HttpServletRequest) request), response);<br>    }<br><br>}</pre><h4>Create a Wrapper</h4><pre>public class XSSRequestWrapper extends HttpServletRequestWrapper {<br><br>  public XSSRequestWrapper(HttpServletRequest request) {<br>    super(request);<br>  }<br><br>  @Override<br>  public String[] getParameterValues(String parameter) {<br>    String[] values = super.getParameterValues(parameter);<br>    if (values == null) {<br>      return null;<br>    }<br>    int count = values.length;<br>    String[] encodedValues = new String[count];<br>    for (int i = 0; i &lt; count; i++) {<br>      encodedValues[i] = sanitizeInput(values[i]);<br>    }<br>    return encodedValues;<br>  }<br><br>  private String sanitizeInput(String string) {<br>    return Encode.forHtml(string);<br>  }<br>}</pre><p>In the example of the XSSRequestWrapper, it&#39;s used to intercept HTTP requests before they are fully processed by the server. The wrapper extends the functionality of the HttpServletRequestWrapper class, which is an implementation of HttpServletRequest provided by the server. This wrapper overrides certain methods, such as getParameter() and getReader(), to apply sanitization logic to the data entering the HTTP request.</p><p>The primary function of the wrapper is to provide an additional layer of processing to HTTP requests. In the case of the XSS filter, it’s used to sanitize input data and prevent potential XSS attacks. This is achieved by examining and modifying the parameters and body of the request before they are processed and passed to the main controller or application.</p><h3>Step 2: Configure XSS Protection Filter</h3><pre>@Configuration<br>public class WebConfig {<br><br>    @Bean<br>    public FilterRegistrationBean&lt;XSSFilter&gt; filterRegistrationBean() {<br>        FilterRegistrationBean&lt;XSSFilter&gt; registrationBean = new FilterRegistrationBean&lt;&gt;();<br>        registrationBean.setFilter(new XSSFilter());<br>        registrationBean.addUrlPatterns(&quot;/*&quot;);<br>        return registrationBean;<br>    }<br>}</pre><p>This snippet demonstrates the setup of an XSSFilter within a Spring Boot application. The filter intercepts all incoming requests (&quot;/*&quot;) and applies the XSSFilter logic, which includes sanitization procedures to prevent Cross-Site Scripting attacks.</p><h3>Step 3: Configure XSS Protection in Spring Security</h3><p>We’ll add response headers to enhance security against XSS attacks:</p><pre>@Configuration<br>public class SecurityConfig {<br><br>  @Bean<br>  SecurityFilterChain config(HttpSecurity http) throws Exception {<br>    http<br>      .csrf(csrf -&gt; csrf.disable())<br>      .authorizeHttpRequests(<br>        re -&gt; re.anyRequest().permitAll()<br>      )<br>      .headers(<br>        header -&gt;<br>          header<br>            .xssProtection()<br>            .and()<br>            .contentSecurityPolicy(cs -&gt; cs.policyDirectives(&quot;script-src &#39;self&#39;&quot;))<br>      );<br><br>    return http.build();<br>  }<br>}</pre><h3>Step 4: Update Wrapper for sanitize Json</h3><pre>import com.fasterxml.jackson.databind.ObjectMapper;<br><br>// ...<br><br>public class XSSRequestWrapper extends HttpServletRequestWrapper {<br><br>    private final ObjectMapper objectMapper = new ObjectMapper();<br><br>    // ... (other methods)<br><br>    @Override<br>    public ServletInputStream getInputStream() throws IOException {<br>        ServletInputStream originalInputStream = super.getInputStream();<br>        String requestBody = new String(originalInputStream.readAllBytes());<br><br>        // Sanitize the JSON body<br>        String sanitizedBody = sanitizeInput(requestBody);<br><br>        return new ServletInputStream() {<br>          private final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(<br>            sanitizedBody.getBytes()<br>          );<br>    <br>          @Override<br>          public int read() throws IOException {<br>            return byteArrayInputStream.read();<br>          }<br>    <br>          @Override<br>          public boolean isFinished() {<br>            return byteArrayInputStream.available() == 0;<br>          }<br>    <br>          @Override<br>          public boolean isReady() {<br>            return true; <br>          }<br>    <br>          @Override<br>          public void setReadListener(ReadListener readListener) {<br>           <br>          }<br>        };<br>}<br><br>    // ... (other methods)<br><br>    private String sanitizeInput(String input) {<br>        return Encode.forHtml(input); // Implement appropriate sanitization logic<br>    }<br>}</pre><p>This modified XSSRequestWrapper intercepts the JSON request body and applies sanitization before sending it to the servlet for processing. This ensures that the received JSON data is also treated to prevent potential XSS attacks.</p><h4>Others samples using controllers</h4><pre>@RestController<br>@RequestMapping(&quot;/api&quot;)<br>public class DemoController {<br><br>  @PostMapping(&quot;/&quot;)<br>  public Object test(@RequestBody Object re) throws JsonProcessingException {<br>//Prevent with Xss filter for body request<br>    System.out.println(new ObjectMapper().writeValueAsString(re));<br>    return re;<br>  }<br><br>  @GetMapping(&quot;/test-unescape&quot;)<br>  public String testUn(@RequestParam String datos) {<br>   //Prevent with Xss filter for parameters<br>    System.out.println(datos);<br>    return datos;<br>  }<br>  <br>  @GetMapping(&quot;/test&quot;)<br>  public String testResturn() {<br>   //return a execution script if spring security configuration is disable<br>    return &quot;&quot;&quot;<br>      {<br>    &quot;id&quot;: 1,<br>    &quot;name&quot;: &quot;&lt;script&gt;alert(&#39;Hola &gt;:)!&#39;)&lt;/script&gt;&quot;<br>    }<br>      &quot;&quot;&quot;;<br>  }<br>}</pre><h4>Result</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lr4Z9de0wsVium4f5KcZYQ.png" /></figure><h4>Conclusion</h4><p>Here are some of the most common ways XSS attacks can enter web applications, and while we’ve covered a great deal, there’s much more to consider if needed. I hope this helps in making your application more secure.”</p><p>XSS attacks can take various forms and it’s crucial to consider a wide range of attack vectors to ensure comprehensive protection. Some common forms of XSS attacks include:</p><ol><li><strong>Reflected:</strong> User-entered data is directly reflected in the server’s response, such as through URL parameters or customized error messages.</li><li><strong>Stored: </strong>Malicious data is stored in databases or other data stores and later displayed to other users. This can happen in comment sections, user profiles, etc.</li><li><strong>DOM-based:</strong> Occurs on the client side when insecure JavaScript code manipulates the DOM using unvalidated data.</li><li><strong>Third-party attacks:</strong> Third-party scripts, like embedded ads or widgets, can be manipulated to execute malicious code.</li><li><strong>Form-based attacks:</strong> Input fields, such as web forms, can be exploited to inject malicious code.</li><li><strong>HTTP Headers: </strong>HTTP headers can be manipulated to inject scripts.</li><li><strong>Cookie-based attacks:</strong> Cookie manipulation can also be a form of XSS attack.</li></ol><p>While we’ve covered a significant portion of these vulnerabilities, it’s always advisable to continuously review and enhance security measures, such as input data sanitization, implementing security headers, using Content Security Policy (CSP), and educating end-users about security risks.</p><p>These steps are crucial in strengthening a web application’s security and preventing XSS attacks! If you need more details on specific areas or how to further extend security, I’m here to help</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c266a175e011" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fighting DDoS Attacks: Implementing Custom Rate Limiting in Your API with Spring Boot]]></title>
            <link>https://danielangel22.medium.com/fighting-ddos-attacks-implementing-custom-rate-limiting-in-your-api-with-spring-boot-1a038b8124e7?source=rss-a93aad8008b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a038b8124e7</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[ddos]]></category>
            <dc:creator><![CDATA[Daniel Angel]]></dc:creator>
            <pubDate>Fri, 01 Dec 2023 05:20:03 GMT</pubDate>
            <atom:updated>2023-12-01T05:20:03.479Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-poywvgREO4WHztt" /><figcaption>Photo by <a href="https://unsplash.com/@gantas?utm_source=medium&amp;utm_medium=referral">Gantas Vaičiulėnas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Distributed Denial-of-Service (DDoS) attacks on APIs are malicious attempts to overload an online service, such as a web API, by generating a massive amount of simultaneous requests from multiple sources. The goal is to overwhelm the target server, exhaust its resources, and render the service inaccessible to legitimate users.</p><p>Key features of DDoS attacks on APIs include:</p><ol><li><strong><em>Massive volume of requests:</em></strong> Attackers send a large number of simultaneous requests to the API from a network of compromised devices (botnets) or automated tools, causing a resource overload on the server.</li><li><strong><em>Geographical distribution</em>:</strong> DDoS attacks often originate from multiple geographical locations, making it challenging to identify and block malicious IP addresses.</li><li><strong><em>Variability in the application layer:</em></strong> DDoS attacks can target different parts of the API infrastructure, including network, transport, or application layers. Some attacks may focus on specific endpoints or critical functions within the API.</li><li><strong><em>Aim to disrupt service: </em></strong>The primary goal of a DDoS attack on an API is to render the service inaccessible to legitimate users, potentially leading to revenue loss, reputation damage, and a negative user experience.</li></ol><p>DDoS attacks can take various forms, such as SYN flood attacks, HTTP flood attacks, DNS amplification attacks, among others. Perpetrators exploit vulnerabilities in the underlying infrastructure to execute these attacks and disrupt service.</p><p>It is crucial for organizations to implement protective measures like rate limiting, real-time monitoring systems, firewalls, intrusion detection systems (IDS), and CDN services to mitigate the impact of these attacks and maintain the availability and security of their APIs.</p><p>On this occasion, we will see how to create a custom filter that will help us address this issue in case we don’t have third-party cloud systems or architectures and need to implement this method in our API.</p><pre>import org.springframework.core.annotation.Order;<br>import org.springframework.stereotype.Component;<br>import javax.servlet.*;<br>import javax.servlet.http.HttpServletResponse;<br>import java.io.IOException;<br>import java.util.concurrent.ConcurrentHashMap;<br>import java.util.concurrent.atomic.AtomicLong;<br><br>@Component<br>@Order(1)<br>public class RateLimitFilter implements Filter {<br><br>    private final ConcurrentHashMap&lt;String, AtomicLong&gt; requestCount = new ConcurrentHashMap&lt;&gt;();<br>    private final long rateLimit = 10; <br><br>    @Override<br>    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {<br>        String ipAddress = request.getRemoteAddr();<br>        AtomicLong count = requestCount.computeIfAbsent(ipAddress, k -&gt; new AtomicLong());<br><br>        if (count.incrementAndGet() &gt; rateLimit) {<br>            HttpServletResponse httpResponse = (HttpServletResponse) response;<br>            httpResponse.setStatus(HttpServletResponse.SC_TOO_MANY_REQUESTS);<br>            httpResponse.getWriter().write(&quot;Rate limit exceeded. Please try again later.&quot;);<br>            return;<br>        }<br><br>        chain.doFilter(request, response);<br>    }<br><br> <br>}</pre><p>This RateLimitFilter checks the number of requests per second for each IP address and responds with a status code 429 Too Many Requests if the established limit (rateLimit) is exceeded.</p><h4>Add a logging monitoring system to your API to validate which IPs were blocked</h4><pre>private void logBlockedRequest(String ipAddress, ServletRequest request) {<br>        logger.log(Level.INFO, &quot;Blocked request from IP: &quot; + ipAddress + &quot;, URI: &quot; + ((HttpServletRequest) request).getRequestURI());<br>}<br><br>//call in validation of limit</pre><h3>Conclusion</h3><p>The implementation of rate limiting is a fundamental strategy to protect an API against DDoS attacks and ensure its availability and stability. Although considered a simple method, its effectiveness lies in its ability to control the number of requests the API can handle, helping to prevent resource overload and service disruption.</p><p>Through rate limiting, a limit can be set on the number of requests allowed per second, significantly reducing the impact of a DDoS attack by restricting malicious traffic. As the API grows and security needs evolve, this simple method can be scaled and adjusted to meet specific requirements.</p><p>By combining rate limiting with other security strategies such as firewalls, real-time monitoring, and security updates, a comprehensive approach is created to safeguard the API from cyber threats and attacks. The inherent flexibility of rate limiting allows for adjusting limits, setting custom rules, and excluding certain IP addresses or routes based on changing application needs.</p><p>In summary, while rate limiting may be considered a straightforward solution, its scalability and adaptability make it an essential component for API security, providing a robust first line of defense against DDoS attacks and serving as a solid foundation for building a more complex and comprehensive security ecosystem.</p><p><a href="https://danielangel22.medium.com/spring-retry-to-handle-retries-in-critical-operations-spring-boot-3-c597ed2b5665">Spring Retry to Handle Retries in Critical Operations + Spring boot 3</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a038b8124e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>