<?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 Diluckshan Puviraj on Medium]]></title>
        <description><![CDATA[Stories by Diluckshan Puviraj on Medium]]></description>
        <link>https://medium.com/@diluckshan?source=rss-32ad62c1bcf7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WRdNSQawMm4Cw4Zu2rJ3wQ.jpeg</url>
            <title>Stories by Diluckshan Puviraj on Medium</title>
            <link>https://medium.com/@diluckshan?source=rss-32ad62c1bcf7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:48:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@diluckshan/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[Multi Tenancy in Java Applications: A Practical Guide]]></title>
            <link>https://medium.com/@diluckshan/implementing-a-per-tenant-per-database-architecture-in-a-property-management-system-8a006b817a3a?source=rss-32ad62c1bcf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a006b817a3a</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[multitenancy]]></category>
            <category><![CDATA[oracle]]></category>
            <dc:creator><![CDATA[Diluckshan Puviraj]]></dc:creator>
            <pubDate>Thu, 01 May 2025 08:23:23 GMT</pubDate>
            <atom:updated>2025-05-09T16:30:07.472Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JrkXglXXhinTceL6lPeGFg.jpeg" /></figure><p>In the world of property management software(PMS), data isolation isn’t just a nice to have but it’s essential. When multiple property management companies use the same software platform, keeping their data completely separate is critical for security, compliance, and customization needs.</p><p>Let’s explore implementing a database-per-tenant architecture using Spring Boot, Oracle DB in Docker(via Podman), and AWS DynamoDB.</p><h3>Why Database-Per-Tenant Architecture?</h3><p>For property management systems, the database-per-tenant approach delivers several key benefits:</p><ul><li><strong>Enhanced security and data isolation</strong>: Each company’s data lives in its own database, minimizing cross-tenant data leakage risks.</li><li><strong>Customization flexibility</strong>: Different companies can have unique schema requirements.</li><li><strong>Regulatory compliance</strong>: Property management often involves location-specific regulations.</li><li><strong>Performance isolation</strong>: Resource-intensive operations by one tenant won’t affect others.</li><li><strong>Simplified backup and recovery</strong>: Tenant-specific database restoration becomes straightforward.</li></ul><p>While this approach does increase infrastructure costs and complexity, the benefits typically outweigh these drawbacks for systems where data security and compliance are non-negotiable.</p><h3>Use Case: Property Management System</h3><ul><li><strong>Scenario</strong>: A PMS serves multiple properties (e.g., “Sunset Hotel,” “City Apartments”). Each property is a tenant with its own database to store guest bookings, staff details, and invoices.</li></ul><p><strong>Requirements</strong>:</p><ul><li>Isolate data for each property to ensure privacy and compliance (e.g., GDPR).</li><li>Route database requests to the correct tenant database based on the property selected by the user.</li><li>Support dynamic addition of new properties without restarting the application.</li><li><strong>Tenant Identification</strong>: The tenant is identified via a custom HTTP header (X-Property-Id) sent by the client (e.g., a web app or mobile app).</li></ul><h3>Implementation Overview</h3><p>Our implementation uses:</p><ul><li><strong>Spring Boot</strong> for the application framework</li><li><strong>Oracle databases</strong> (one per tenant) running in Podman containers</li><li><strong>DynamoDB</strong> to store tenant metadata and connection details</li><li><strong>Dynamic datasource routing</strong> to connect to the appropriate tenant database</li></ul><p>Let’s break down the key components:</p><h3>1. Setting Up Oracle Databases</h3><p>For local development and demos, spinning up actual Oracle instances can be heavy and slow.</p><pre># Pull Oracle Enterprise Image<br>podman pull container-registry.oracle.com/database/enterprise:21.3.0.0</pre><p>That’s where <strong>Podman (or Docker)</strong> comes in. Each tenant’s Oracle DB runs in an isolated container, simulating a real-world deployment while keeping things <strong>lightweight, disposable, and easy to showcase</strong>.</p><p>First, we’ll create separate Oracle instances for each tenant.To avoid port conflicts and reflect a real-world distributed setup, <strong>each tenant’s Oracle DB runs on a different host port</strong>:</p><pre># Run Oracle Container for Sunset Hotel<br>podman run -d --name oracle_sunset_hotel -p 1521:1521 -e ORACLE_PWD=Oracle123 container-registry.oracle.com/database/enterprise:21.3.0.0</pre><pre># Run Oracle Container for City Apartments<br>podman run -d --name oracle_city_apartments -p 1522:1521 -e ORACLE_PWD=Oracle123 container-registry.oracle.com/database/enterprise:21.3.0.0</pre><h3>2. DynamoDB for Tenant Registry</h3><p>We’ll store tenant metadata in a DynamoDB table:</p><pre># Create the DynamoDB table<br>aws dynamodb create-table \<br>    --table-name TenantRegistry \<br>    --attribute-definitions AttributeName=TenantId,AttributeType=S \<br>    --key-schema AttributeName=TenantId,KeyType=HASH \<br>    --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XpJ23RalDwAS9SXCFnNG0A.png" /></figure><pre># Add tenant data<br>aws dynamodb put-item --table-name TenantRegistry \<br>    --item &#39;{<br>        &quot;TenantId&quot;: {&quot;S&quot;: &quot;sunset_hotel&quot;},<br>        &quot;DbUrl&quot;: {&quot;S&quot;: &quot;jdbc:oracle:thin:@localhost:1521:ORCLCDB&quot;},<br>        &quot;userName&quot;: {&quot;S&quot;: &quot;PMS_USER&quot;},<br>        &quot;password&quot;: {&quot;S&quot;: &quot;Pms123&quot;},<br>        &quot;PropertyName&quot;: {&quot;S&quot;: &quot;Sunset Hotel&quot;},<br>        &quot;SchemaName&quot;: {&quot;S&quot;: &quot;SUNSET&quot;}<br>    }&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VK6JjSPMeNqV8qj03axYBw.png" /></figure><p>You might wonder — why not just list all tenant DB configs in application.properties?</p><h4>Here’s why DynamoDB is a better fit:</h4><ul><li><strong>Dynamic Configuration</strong> — Add or remove tenants without restarting the app.</li><li><strong>Cloud-Native</strong> — DynamoDB is fast, scalable, and serverless.</li><li><strong>Centralized Metadata</strong> — Easier to secure, audit, and manage in one place.</li><li><strong>No Bloat in Codebase</strong> — Keeps your Spring Boot config clean and environment-agnostic.</li></ul><h3>3. Key Components of the Spring Boot Application</h3><p>The application comprises several critical components:</p><h3>TenantContext</h3><p>Manages the current tenant ID using ThreadLocal storage:</p><pre>public class TenantContext {<br>  private static final ThreadLocal CURRENT_TENANT = new ThreadLocal&lt;&gt;();<br>  public static String getCurrentTenant() {<br>    return (String) CURRENT_TENANT.get();<br>  }<br>  public static void setCurrentTenant(String tenant) {<br>    CURRENT_TENANT.set(tenant);<br>  }<br>  public static void clear() {<br>    CURRENT_TENANT.remove();<br>  }<br>}</pre><h3>Tenant Metadata Model</h3><p>A simple POJO to hold tenant details fetched from DynamoDB.</p><pre>@Data<br>public class TenantInfo {<br>  private String tenantId;<br>  private String dbUrl;<br>  private String userName;<br>  private String password;<br>}</pre><h3>DynamoDB Tenant Lookup</h3><p>Interacts with DynamoDB to validate tenant IDs and fetch connection details.</p><pre>@Service<br>public class TenantService {<br><br>  @Autowired<br>  private DynamoDbClient dynamoDbClient;<br><br>  public List&lt;TenantInfo&gt; getAllTenants() {<br>    List&lt;TenantInfo&gt; tenants = new ArrayList&lt;&gt;();<br>    ScanRequest scanRequest = ScanRequest.builder()<br>        .tableName(&quot;TenantRegistry&quot;)<br>        .build();<br><br>    ScanResponse response = dynamoDbClient.scan(scanRequest);<br>    for (Map&lt;String, AttributeValue&gt; item : response.items()) {<br>      TenantInfo tenantInfo = new TenantInfo();<br>      tenantInfo.setTenantId(item.get(&quot;TenantId&quot;).s());<br>      tenantInfo.setDbUrl(item.get(&quot;DbUrl&quot;).s());<br>      tenantInfo.setUserName(item.get(&quot;userName&quot;).s());<br>      tenantInfo.setPassword(item.get(&quot;password&quot;).s());<br>      tenants.add(tenantInfo);<br>    }<br>    return tenants;<br>  }<br>}</pre><h3>TenantFilter</h3><p>Extracts the tenant ID from HTTP headers and validates it against DynamoDB:</p><pre>@Component<br>public class TenantFilter extends OncePerRequestFilter {<br>  @Autowired<br>  private TenantValidator tenantValidator;<br>  @Override<br>  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)<br>      throws ServletException, IOException {<br>    String tenantId = request.getHeader(&quot;X-Property-Id&quot;);<br>    if (tenantId != null &amp;&amp; !tenantId.isEmpty() &amp;&amp; tenantValidator.isValidTenant(tenantId)) {<br>      TenantContext.setCurrentTenant(tenantId);<br>    } else {<br>      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);<br>      response.getWriter().write(&quot;Invalid or missing Tenant ID&quot;);<br>      return;<br>    }<br>    try {<br>      filterChain.doFilter(request, response);<br>    } finally {<br>      TenantContext.clear();<br>    }<br>  }<br>}</pre><h3>Dynamic Datasource Routing</h3><p>The MultiTenantDataSource class extends Spring’s AbstractRoutingDataSource to route database connections to the appropriate tenant database:</p><pre>public class MultiTenantDataSource extends AbstractRoutingDataSource {<br>    @Override<br>    protected Object determineCurrentLookupKey() {<br>        return TenantContext.getCurrentTenant();<br>    }<br>}</pre><h3>DataSource Configuration</h3><p>This class creates datasources for all tenants at startup and etches all tenant details from TenantService at startup, creates a connection pool (PoolDataSource) for each, and registers them with the MultiTenantDataSource.</p><pre>@Configuration<br>public class DataSourceConfig {<br>    private final TenantService tenantService;<br>    public DataSourceConfig(TenantService tenantService) {<br>        this.tenantService = tenantService;<br>    }<br>    private static final Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);<br>    @Bean<br>    public DataSource dataSource() throws SQLException {<br>        Map&lt;Object, Object&gt; targetDataSources = new HashMap&lt;&gt;();<br>        // Fetch all tenants from DynamoDB<br>        for (TenantInfo tenant : tenantService.getAllTenants()) {<br>            logger.info(&quot;Configuring datasource for tenant : {}&quot;, tenant.getTenantId());<br>            PoolDataSource poolDataSource = getPoolDataSource(tenant);<br>            targetDataSources.put(tenant.getTenantId(), poolDataSource);<br>            TenantContext.setCurrentTenant(tenant.getTenantId());<br>        }<br>        MultiTenantDataSource routingDatasource = new MultiTenantDataSource();<br>        routingDatasource.setTargetDataSources(targetDataSources);<br>        return routingDatasource;<br>    }<br><br>    private PoolDataSource getPoolDataSource(TenantInfo tenant) throws SQLException {<br>        PoolDataSource poolDataSource = PoolDataSourceFactory.getPoolDataSource();<br>        poolDataSource.setConnectionFactoryClassName(&quot;oracle.jdbc.pool.OracleDataSource&quot;);<br>        poolDataSource.setUser(tenant.getUserName());<br>        poolDataSource.setPassword(tenant.getPassword());<br>        poolDataSource.setURL(tenant.getDbUrl());<br>        poolDataSource.setValidateConnectionOnBorrow(true);<br>        poolDataSource.setSecondsToTrustIdleConnection(15);<br>        poolDataSource.setConnectionPoolName(&quot;TENANT&quot; + tenant.getTenantId());<br>        return poolDataSource;<br>    }<br>}</pre><h3>Booking Entity + Controller + Repository</h3><p>These are standard Spring Data JPA and Spring Web components. The crucial part is that they operate seamlessly without needing direct knowledge of the tenant; the DataSource routing handles directing the operations to the correct database based on the TenantContext.</p><pre>@Entity<br>@Data<br>public class Booking {<br>    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    private String guestName;<br>    private String roomNumber;<br>    private String checkInDate;<br>}</pre><pre>@RestController<br>@RequestMapping(&quot;/bookings&quot;)<br>public class BookingController {<br>    @Autowired private BookingRepository repo;<br><br>    @PostMapping<br>    public Booking create(@RequestBody Booking booking) {<br>        return repo.save(booking);<br>    }<br><br>    @GetMapping(&quot;/{id}&quot;)<br>    public Booking get(@PathVariable Long id) {<br>        return repo.findById(id).orElse(null);<br>    }<br>}</pre><pre>package com.spring.multitenant.repository;<br><br>import com.spring.multitenant.entity.Booking;<br>import org.springframework.data.jpa.repository.JpaRepository;<br><br>public interface BookingRepository extends JpaRepository&lt;Booking, Long&gt; {<br><br>}</pre><h3>Testing the Implementation</h3><p>With this architecture in place, testing is straightforward:</p><ul><li>Send a POST request to create a booking for Sunset Hotel:</li></ul><pre>POST http://localhost:8080/bookings<br>Accept: */*<br>X-Property-Id: sunset_hotel<br>Content-Type: application/json<br><br>{<br>  &quot;guestName&quot; : &quot;Dilux Puvi&quot;,<br>  &quot;roomNumber&quot; : &quot;101&quot;,<br>  &quot;checkInDate&quot; : &quot;2025-05-20&quot;<br>}</pre><ul><li>Send a similar request for City Apartments:</li></ul><pre>POST http://localhost:8080/bookings<br>Accept: */*<br>X-Property-Id: city_apartments<br>Content-Type: application/json<br><br>{<br>  &quot;guestName&quot; : &quot;Kiri Aruna&quot;,<br>  &quot;roomNumber&quot; : &quot;A12&quot;,<br>  &quot;checkInDate&quot; : &quot;2025-05-21&quot;<br>}</pre><ul><li>Send a GET request to retrieve booking details for required tenant:</li></ul><pre>GET http://localhost:8080/bookings/3<br>Accept: */*<br>X-Property-Id: {tenant}<br>Content-Type: application/json</pre><h3>Why This Approach Instead of Microservices</h3><p>While microservices are popular, a multi-tenant architecture with per-tenant databases offers significant advantages for property management systems:</p><ol><li><strong>Simplified Management</strong>: One application instance manages all tenants, reducing deployment complexity.</li><li><strong>Easier Maintenance</strong>: Code updates and bug fixes are applied once to a single codebase.</li><li><strong>Consistent Experience</strong>: All tenants receive the same features and fixes simultaneously.</li><li><strong>Efficient Resource Utilization</strong>: A single application instance with multiple databases often requires fewer resources than multiple microservices.</li></ol><p>Microservices might make sense if tenants require drastically different functionality or need separate scaling mechanisms, but for most property management systems, the multi-tenant approach delivers the right balance of isolation and manageability.</p><h3>Conclusion</h3><p>Building a per-tenant per-database architecture for property management systems strikes an excellent balance between data isolation and application simplicity. By using Spring Boot’s dynamic datasource routing capabilities alongside DynamoDB for tenant metadata storage, we can create a secure, scalable solution that meets the unique needs of property management companies.</p><p>This approach ensures that each tenant’s data remains completely isolated while allowing for a single, maintainable application that serves all tenants effectively.</p><p>If you have any questions, feel free to reach out, and don’t forget to check the <a href="https://github.com/diluckshan8/java-multitenant-service">sample application </a>for more details!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a006b817a3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practices for Setting Up Spring Boot 3.x Tests with Java 21 and JUnit 5]]></title>
            <link>https://medium.com/@diluckshan/best-practices-for-setting-up-spring-boot-3-x-tests-with-java-21-and-junit-5-b0ef55bdac0f?source=rss-32ad62c1bcf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0ef55bdac0f</guid>
            <category><![CDATA[no-matching-tests-found]]></category>
            <dc:creator><![CDATA[Diluckshan Puviraj]]></dc:creator>
            <pubDate>Mon, 02 Sep 2024 18:35:22 GMT</pubDate>
            <atom:updated>2024-09-03T13:51:59.808Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/657/0*SCLNU_ooG2RRXqM7.png" /></figure><p>In today’s fast-paced software development world, clean, maintainable, and high-coverage test code is critical. Test-driven development (TDD) is gaining traction as a methodology to ensure software quality from the outset. If you’re working with Spring Boot 3.x and Java 21, setting up a robust test environment for both unit and integration tests is essential. This article covers the steps and troubleshooting techniques I’ve employed to configure a reliable test environment.</p><h3>Common Issues and Solutions in Spring Boot Testing</h3><h4>1. “No Matching Tests Found” Error</h4><p><strong>Problem:</strong> When running tests, you might encounter an error stating that no matching tests were found. This typically occurs if you’re using JUnit 4 syntax in a JUnit 5-based project.</p><p><strong>Solution:</strong> To resolve this issue, update your annotations and imports to JUnit 5 syntax.</p><ul><li><strong>Replace @RunWith with @ExtendWith:<br>- </strong>JUnit 4 @RunWith(SpringRunner.class)<br><strong>- </strong>JUnit 5 @ExtendWith(SpringExtension.class</li><li><strong>Update Test Import:<br>- </strong>JUnit 4 import org.junit.Test; <br><strong>- </strong>JUnit 5 import org.junit.jupiter.api.Test;</li><li><strong>Modify Access Modifiers:</strong> Ensure your test classes are public:<br>- <strong>JUnit 4 : </strong><em>class HelloControllerTest {<br> …<br>}</em><strong><br>- JUnit 5 : </strong><em>public class HelloControllerTest {<br> …<br>}</em></li><li><strong>Switch Test Execution Tool in IntelliJ IDEA:</strong> If you’re using IntelliJ IDEA, try switching the test execution tool to IntelliJ IDEA instead of Gradle(my case).<br>- Navigate to: Preferences &gt; Build, Execution, Deployment &gt; Build Tools &gt; Gradle &gt; Build and Execution &gt; Run tests using.<br>- Replace “Gradle” with “IntelliJ IDEA”</li></ul><p>Following these steps should resolve the “No Matching Tests Found” error, and your build and tests should succeed.</p><h4>2. java.lang.NoSuchMethodError</h4><p><strong>Problem:</strong> This error often arises due to version mismatches between Spring Boot, JUnit, or Mockito dependencies. If you specify a version for JUnit, it might conflict with other versions used in your project.</p><p><strong>Solution:</strong> To fix this, remove the specific version number for JUnit dependencies, allowing Gradle to match the correct versions automatically.</p><pre>dependencies { <br>   // Spring Boot Starter Test <br>   testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br>   // JUnit 5 (Jupiter)<br>   testImplementation &#39;org.junit.jupiter:junit-jupiter-api&#39;<br>   testRuntimeOnly &#39;org.junit.jupiter:junit-jupiter-engine&#39;<br>}</pre><p>By removing the version numbers, Gradle will resolve the appropriate versions, eliminating the NoSuchMethodError.</p><h4>3. contextLoads() Failed / Spring Boot Test Failed</h4><p><strong>Problem:</strong> The default contextLoads() test ensures that the Spring application context (all beans) loads correctly. If this test fails, it could be due to several reasons, including missing profiles or incorrect properties.</p><p><strong>Solution:</strong></p><ul><li><strong>Add Spring Boot Profile:</strong> If your project doesn’t have a default profile, you need to add one explicitly in your test class.</li></ul><pre>@SpringBootTest  <br>@ActiveProfiles({&quot;local&quot;})  <br>class BackendApplicationTests {  <br>    @Test  <br>    void contextLoads() {} <br>}</pre><ul><li><strong>Fix PropertyPlaceholderHelper Error:</strong> If you encounter a PropertyPlaceholderHelper error, it may be due to issues in your application.properties or application.yaml files, or with beans using the @Value annotation. To identify the issue, run:</li></ul><pre>./gradlew test -i</pre><ul><li>This command provides detailed logs, helping you pinpoint the error.</li></ul><h3>Conclusion</h3><p>Setting up a testing environment for Spring Boot 3.X and Java 21 with JUnit 5 can be challenging, especially when transitioning from JUnit 4 or dealing with version mismatches. By following the solutions outlined in this article, you can troubleshoot common issues and ensure a robust and maintainable test environment.</p><p>If you have any questions or suggestions, feel free to leave a comment. Thanks for reading!</p><h3>Reference</h3><ol><li><a href="https://velog.io/@yeseul/No-matching-tests-found-in-any-candidate-test-task.-%EC%97%90%EB%9F%AC-%ED%95%B4%EA%B2%B0">https://docs.localstack.cloud/overview/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0ef55bdac0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-End Component Testing: Spring Boot 3 with TestContainers, DynamoDB, and LocalStack]]></title>
            <link>https://medium.com/@diluckshan/end-to-end-component-testing-spring-boot-3-with-testcontainers-dynamodb-and-localstack-0bbea39988de?source=rss-32ad62c1bcf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bbea39988de</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[testcontainer]]></category>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Diluckshan Puviraj]]></dc:creator>
            <pubDate>Mon, 02 Sep 2024 17:47:17 GMT</pubDate>
            <atom:updated>2024-09-05T14:04:31.981Z</atom:updated>
            <content:encoded><![CDATA[<p>Component testing is essential for verifying the behavior of individual components or modules before integrating them into a larger system. This is especially important in event-driven architectures, where components interact asynchronously and in a distributed manner, adding complexity to testing. In this article, I will explore how Testcontainers and LocalStack can simplify component testing for AWS services like DynamoDB in a local environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*VrNqGEDBp3DT5Nju.png" /></figure><h3>Why Testcontainers?</h3><p>Testcontainers is an open-source library that provides lightweight, disposable instances of external systems using Docker containers. It supports a wide range of modules, including relational databases, NoSQL databases, message brokers, and even cloud services. With Testcontainers, you can spin up real instances of external systems for testing, minimizing the risk of discrepancies between test and production environments. Testcontainers also automates the setup and teardown of these containers, streamlining the CI/CD process.</p><h3>Prerequisites</h3><p>To follow along, ensure that you have the following installed:</p><ul><li>A Docker environment (we will use <a href="https://medium.com/@diluckshan/streamline-your-container-management-on-windows-with-podman-884bed94161f">Podman </a>for this example)</li><li>Java 21</li><li>Gradle</li><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">AWS CLI</a></li><li>An IDE of your choice</li></ul><h3>Example Application</h3><p>In this article, we’ll build a sample Spring Boot 3 application that interacts with DynamoDB. The application will allow you to create a user for an event with a specific name and then fetch it using the ID of the newly created resource.</p><p>You can find it on my GitHub account by clicking the link <a href="https://github.com/diluckshan8/spring-practise-service">here</a>.</p><h3>Dependencies Setup</h3><p>First, create a simple Spring MVC project using Spring Initializr, selecting the following dependencies:</p><ul><li>Spring Web</li><li>Testcontainers</li></ul><p>Next, ensure your build.gradle file includes the necessary dependencies for Spring Boot and Testcontainers:</p><pre>testImplementation &#39;org.springframework.boot:spring-boot-testcontainers&#39;</pre><p>For working with DynamoDB, we’ll use the DynamoDB Enhanced library, which is part of the AWS SDK for Java v2:</p><pre>implementation group: &#39;software.amazon.awssdk&#39;, name: &#39;dynamodb-enhanced&#39;, version: &#39;2.23.4&#39;</pre><p>Additionally, we’ll use LocalStack to emulate AWS services locally:</p><pre>testImplementation &#39;org.testcontainers:localstack:1.20.0&#39;</pre><h3>Document Definition</h3><p>We’ll define a UserDocument class to represent a user entity in DynamoDB. This class will define a partition key on the userId field of type String. For simplicity, we won’t be using any secondary indexes in this example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be5f79e81264e75553115b47e221b2ef/href">https://medium.com/media/be5f79e81264e75553115b47e221b2ef/href</a></iframe><h3>Application Configuration</h3><p>Now, let’s configure the application, particularly the persistence layer. We need to register beans for the DynamoDB table and repository.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a37c4866626f02d23284ffb408479e8/href">https://medium.com/media/2a37c4866626f02d23284ffb408479e8/href</a></iframe><h3>Component Test Configuration</h3><p>With the application configuration in place, let’s set up the component tests. Our goals are:</p><ol><li>Start the LocalStack container with DynamoDB service.</li><li>Register an AwsCredentialsProvider bean.</li><li>Ensure that the DynamoDB table is created before the tests run.</li></ol><h4>LocalStack Container with DynamoDB</h4><p>To achieve the first goal, we register the LocalStack container as a bean.Next, we need to configure the AwsCredentialsProvider. Although this step isn&#39;t strictly necessary in the current phase, extracting it makes future extensions easier, such as adding more AWS services. Spring Boot 3 and Testcontainers make this straightforward:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62952784a13fd998050e3a7a28d221b4/href">https://medium.com/media/62952784a13fd998050e3a7a28d221b4/href</a></iframe><h4>DynamoDB Setup</h4><p>Finally, we register the DynamoDbClient bean and set up the DynamoDB table. It’s crucial to override the endpoint to point to the LocalStack container instead of the real AWS DynamoDB service.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0966e70b05c4f47a46f7406fe3463cf0/href">https://medium.com/media/0966e70b05c4f47a46f7406fe3463cf0/href</a></iframe><p>To ensure the table is created before running tests, subscribe to the ApplicationReadyEvent and create the table when the application is ready to receive requests.</p><h3>Writing a Component Test</h3><p>With everything in place, we can now write a component test. Here’s a basic setup using @SpringBootTest and @AutoConfigureMockMvc to spin up the application and configure MockMvc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3559bd7d4da15f4ad642896c720bf590/href">https://medium.com/media/3559bd7d4da15f4ad642896c720bf590/href</a></iframe><h3><strong>Testing with LocalStack</strong></h3><p>When executing tests, LocalStack spins up the necessary AWS services inside Testcontainers. These services, such as DynamoDB, are automatically cleaned up once the tests complete. In debug mode, you can use AWS CLI commands to inspect and retrieve data, making it easy to verify outcomes and troubleshoot issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YQ9is3DdNZ6puEV01rZi-A.png" /></figure><h3><strong>Best Practices for Setting Up Spring Boot 3.x Tests</strong></h3><p>If you encounter issues like No tests found matching, java.lang.NoSuchMethodError, or test failures such as contextLoads() during your setup, check out this <a href="https://medium.com/@diluckshan/best-practices-for-setting-up-spring-boot-3-x-tests-with-java-21-and-junit-5-b0ef55bdac0f">detailed guide</a> for solutions and best practices.</p><h3>Conclusion</h3><p>In this article, we walked through the setup of a Spring Boot 3 application to use Testcontainers and LocalStack for component testing with DynamoDB. This setup simplifies both testing and local development, making it easier to ensure your application behaves as expected before deploying it to production. If you have any questions, feel free to reach out, and don’t forget to check the <a href="https://github.com/diluckshan8/spring-practise-service">sample application</a> for more details!</p><h3>References</h3><ol><li><a href="https://docs.localstack.cloud/overview/">https://docs.localstack.cloud/overview/</a></li><li><a href="https://java.testcontainers.org/">https://java.testcontainers.org/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bbea39988de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS AppConfig: Mastering Feature Flags for Dynamic Applications]]></title>
            <link>https://awstip.com/aws-appconfig-mastering-feature-flags-for-dynamic-applications-a316a130c648?source=rss-32ad62c1bcf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a316a130c648</guid>
            <category><![CDATA[aws-appconfig]]></category>
            <category><![CDATA[feature-flags]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Diluckshan Puviraj]]></dc:creator>
            <pubDate>Fri, 05 Jul 2024 14:24:44 GMT</pubDate>
            <atom:updated>2024-07-09T15:39:24.862Z</atom:updated>
            <content:encoded><![CDATA[<p>Feature flags have been a staple in software development since the inception of software itself. Despite their evolution over time, the core purpose remains unchanged: to easily toggle features on and off. In this article, we’ll explore how to leverage AWS’s native Feature Flag capabilities via AWS AppConfig.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*gG0s1bpEd48Q1Adg.png" /></figure><p>It is a powerful tool that allows for the safe, gradual rollout of new features to customers. AWS AppConfig enables the effective separation of code from configuration data, allowing features to be hidden behind a configuration toggle. This means you can deploy code to production while retaining the ability to tweak your application at runtime without redeployment or restarts.</p><h3>Requirements for a Feature Flag Solution</h3><p>To implement an effective feature flag solution, the following criteria should be met:</p><ul><li>Provide an API to retrieve a feature flag by name.</li><li>Keep feature flags simple and Boolean.</li><li>Enable feature flags selectively for different customers based on session context.</li><li>Maintain high performance even with numerous feature flags.</li><li>Ensure the solution is cost-effective and user-friendly.</li><li>Keep the overall implementation straightforward.</li></ul><h3>Components of AWS AppConfig</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*nI7t9PlTpcRc8gFn.png" /></figure><p>To begin using AWS AppConfig services, you need to create an application..</p><h3>Creating the Application</h3><p>An application in AWS AppConfig serves as a namespace for organizing feature flags and other configuration data. Here’s how to create one:</p><ol><li><strong>Navigate to AWS AppConfig.</strong></li><li><strong>Choose Get Started.</strong></li><li><strong>Enter the Name</strong> as TestApplication.</li><li><strong>Enter the Description</strong> as AppConfig for TestApplication.</li><li><strong>Choose Create Application.</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kJAn2WSrV7ftlYtFlkej4A.png" /></figure><h3>Create an Environment</h3><ol><li>Select <strong>Environment</strong> and click <strong>Create Environment</strong>.</li><li>Fill in the form fields as shown in the screenshot and click <strong>Create environment</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6V-NBMxch3DitZ_YvkshgQ.jpeg" /></figure><h3>Selecting and Creating the Configuration Type and Profile</h3><p>AWS AppConfig supports two types of configuration profiles: feature flags and freeform configurations. Feature flag configuration profiles store data in the AWS AppConfig hosted configuration store. For this guide, we’ll use the Feature Flag option.</p><ol><li><strong>Click the Feature Flag option.</strong></li></ol><p>Create a Configuration Profile to group related flags. This profile can contain a single flag or multiple flags.</p><ol><li>Choose <strong>“Feature Flag</strong>” as the configuration type.</li><li>Name the <strong>Configuration Profile</strong> as testFeatureFlag.</li><li>Click “<strong>Next</strong>” to proceed.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W7RdD5YG0NsmZIAMnu6urg.jpeg" /></figure><h3>Adding the Feature Flag</h3><p>With the Configuration Profile set up, you can now create the flag:</p><ol><li><strong>Enter </strong><strong>enable_feature for Flag Name and Flag Key.</strong></li><li><strong>Provide a Description</strong> to explain the flag’s purpose.</li><li><strong>Select the short-term flag option</strong> if the flag is temporary.</li><li><strong>Define Attributes and Constraints</strong> if necessary. Constraints help validate attribute values to prevent deploying unexpected values.</li><li>Click “<strong>Next</strong>” to proceed.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bS3kU6nO_DIngtB_ubB90A.jpeg" /></figure><p>6.Review your configuration and click “Save and Continue” to deploy instantly or choose “Save” for later deployment.</p><h3>Deploying the Feature Flags</h3><p>Once the feature flags are created, they need to be deployed. AWS AppConfig allows for gradual deployment strategies to minimize the impact of any unintended outcomes.</p><ol><li><strong>Select a gradual deployment strategy</strong> before starting the deployment.</li><li>An AppConfig Configuration Version represents a specific snapshot or version of a configuration, allowing for tracking and managing changes.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mj1CKk0yctMdCkzFgdow1g.jpeg" /></figure><p>Congratulations! You’ve successfully created and deployed your first Feature Flag using AWS AppConfig.</p><h3>Managing Feature Flags via AWS CLI</h3><p>To manage feature flags using the AWS Command Line Interface (CLI), you can perform several operations such as listing applications, configuration profiles, configuration versions, and retrieving specific versions of configurations. Here’s how:</p><h4>List Applications</h4><p>To list all applications along with their IDs:</p><pre>aws appconfig list-applications</pre><p>Output Response:</p><pre>{<br>    &quot;Items&quot;: [<br>        {<br>            &quot;Id&quot;: &quot;x8cgs9k&quot;,<br>            &quot;Name&quot;: &quot;TestApplication&quot;,<br>            &quot;Description&quot;: &quot;AppConfig for TestApplication&quot;<br>        }<br>    ]<br>}</pre><h4>List Configuration Profiles</h4><p>Replace YOUR_APPLICATION_ID with the application ID obtained from the previous command to list all configuration profiles for that application, along with their IDs:</p><pre>aws appconfig list-configuration-profiles --application-id x8cgs9k</pre><p>Output Response:</p><pre>{<br>    &quot;Items&quot;: [<br>        {<br>            &quot;ApplicationId&quot;: &quot;x8erx1k&quot;,<br>            &quot;Id&quot;: &quot;p34fvru&quot;,<br>            &quot;Name&quot;: &quot;testFeatureFlag1&quot;,<br>            &quot;LocationUri&quot;: &quot;hosted&quot;,<br>            &quot;Type&quot;: &quot;AWS.AppConfig.FeatureFlags&quot;<br>        },<br>        {<br>            &quot;ApplicationId&quot;: &quot;x9hgx1k&quot;,<br>            &quot;Id&quot;: &quot;3jssiti&quot;,<br>            &quot;Name&quot;: &quot;testFeatureFlag&quot;,<br>            &quot;LocationUri&quot;: &quot;hosted&quot;,<br>            &quot;Type&quot;: &quot;AWS.AppConfig.FeatureFlags&quot;<br>        }<br>    ]<br>}</pre><h4>List Configuration Versions</h4><p>To list all versions for a particular feature flag configuration profile:</p><pre>aws appconfig list-hosted-configuration-versions --application-id x9hgx1k --configuration-profile-id 3jssiti</pre><p>Output Response:</p><pre>{<br>    &quot;Items&quot;: [<br>        {<br>            &quot;ApplicationId&quot;: &quot;x8cgx1k&quot;,<br>            &quot;ConfigurationProfileId&quot;: &quot;3jssiti&quot;,<br>            &quot;VersionNumber&quot;: 3,<br>            &quot;ContentType&quot;: &quot;application/json&quot;<br>        },<br>        {<br>            &quot;ApplicationId&quot;: &quot;x8cgx1k&quot;,<br>            &quot;ConfigurationProfileId&quot;: &quot;3jssiti&quot;,<br>            &quot;VersionNumber&quot;: 2,<br>            &quot;ContentType&quot;: &quot;application/json&quot;<br>        },<br>        {<br>            &quot;ApplicationId&quot;: &quot;x8cgx1k&quot;,<br>            &quot;ConfigurationProfileId&quot;: &quot;3jssiti&quot;,<br>            &quot;VersionNumber&quot;: 1,<br>            &quot;ContentType&quot;: &quot;application/json&quot;<br>        }<br>    ]<br>}</pre><h4>Retrieve Specific Configuration Version</h4><p>To save a particular version of a feature flag configuration to a JSON file:</p><pre>aws appconfig get-hosted-configuration-version --application-id x9hgx1k --configuration-profile-id 3jssiti --version-number 3 config.json</pre><p>The JSON output will look like this:</p><pre>{<br>    &quot;flags&quot;: {<br>        &quot;enable_core_receive&quot;: {<br>            &quot;_createdAt&quot;: &quot;2024-05-27T06:45:03.685Z&quot;,<br>            &quot;_updatedAt&quot;: &quot;2024-05-28T05:35:38.435Z&quot;,<br>            &quot;attributes&quot;: {<br>                &quot;attribute&quot;: {<br>                    &quot;constraints&quot;: {<br>                        &quot;elements&quot;: {<br>                            &quot;type&quot;: &quot;string&quot;<br>                        },<br>                        &quot;type&quot;: &quot;array&quot;<br>                    }<br>                }<br>            },<br>            &quot;name&quot;: &quot;enable_feature&quot;<br>        }<br>    },<br>    &quot;values&quot;: {<br>        &quot;enable_core_receive&quot;: {<br>            &quot;_createdAt&quot;: &quot;2024-05-27T06:45:03.685Z&quot;,<br>            &quot;_updatedAt&quot;: &quot;2024-05-30T08:39:09.287Z&quot;,<br>            &quot;enabled&quot;: true,<br>            &quot;attribute&quot;: [<br>                &quot;condition01&quot;,<br>                &quot;condition02&quot;,<br>                &quot;condition03&quot;<br>            ]<br>        }<br>    },<br>    &quot;version&quot;: &quot;1&quot;<br>}</pre><h3>Conclusion</h3><p>Using AWS AppConfig for feature flag management simplifies the process of toggling features on and off, ensuring high performance and flexibility.</p><p>You might be wondering how to integrate and access AWS AppConfig configurations within your Spring Boot applications. Don’t worry! In my upcoming article, we’ll delve into practical implementation steps and best practices for effectively leveraging AWS AppConfig with Spring Boot.</p><p>Follow to stay updated on the latest insights and tutorials!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a316a130c648" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/aws-appconfig-mastering-feature-flags-for-dynamic-applications-a316a130c648">AWS AppConfig: Mastering Feature Flags for Dynamic Applications</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamline Your Container Management on Windows with Podman]]></title>
            <link>https://medium.com/@diluckshan/streamline-your-container-management-on-windows-with-podman-884bed94161f?source=rss-32ad62c1bcf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/884bed94161f</guid>
            <category><![CDATA[image]]></category>
            <category><![CDATA[podman]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Diluckshan Puviraj]]></dc:creator>
            <pubDate>Wed, 03 Jul 2024 10:45:55 GMT</pubDate>
            <atom:updated>2024-07-05T15:17:48.024Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*HqDbx6xyiAy-LRGm.png" /></figure><p>Containers are essential in modern software development, providing isolated environments for running applications. While Docker has been a popular choice, Podman offers several advantages, especially for Mac and Windows users. This guide will walk you through setting up Podman on Windows, leveraging the Windows Subsystem for Linux 2 (WSL2) for a seamless container experience.</p><h4>Why Use Podman Instead of Docker?</h4><ol><li><strong>Daemonless Architecture</strong>: Unlike Docker, Podman operates without a central daemon. This means fewer potential single points of failure and enhanced security, as each container runs as an individual process.</li><li><strong>Rootless Containers</strong>: Podman supports running containers as non-root users, enhancing security by minimizing the risk of privilege escalation attacks.</li><li><strong>Docker Compatibility</strong>: Podman is designed to be compatible with Docker. It uses the same commands and can work with Docker-formatted containers and images, making it easy to switch without changing your existing workflows.</li><li><strong>Kubernetes Integration</strong>: Podman natively supports Kubernetes YAML files, allowing you to seamlessly transition between container management and orchestration tasks.</li><li><strong>Lightweight and Flexible</strong>: Podman is known for its lightweight nature and flexibility, making it ideal for development environments and production deployments alike.</li></ol><h4>Prerequisites</h4><p>Before you start, ensure you meet the following requirements:</p><ul><li><strong>Windows 10 version 19043 or later (or Windows 11)</strong>: Podman requires a recent version of Windows.</li><li><strong>Administrator privileges</strong>: You’ll need admin rights to install Podman and configure WSL2.</li><li><strong>WSL 2 enabled</strong>: Ensure WSL2 is set up and running. Follow the <a href="https://learn.microsoft.com/en-us/windows/wsl/">WSL2 installation guide</a> if needed.</li><li><strong>6 GB RAM (recommended)</strong>: While Podman will run with less, a minimum of 6GB RAM is recommended for smooth operation.</li></ul><h4>Installing Podman</h4><p>To set up Podman on your Windows machine, follow these steps:</p><p><strong>1.Download Podman</strong>:</p><ul><li>Visit the <a href="https://github.com/containers/podman/releases">official Podman GitHub release page</a> and look for version 4.1 or later.</li><li>Download the setup file (e.g., podman-#.#.#-setup.exe).</li></ul><p><strong>2.Run the Installer</strong>:</p><ul><li>Execute the downloaded EXE file.</li><li>Relaunch a new terminal (PowerShell or CMD).</li></ul><p><strong>3.Initialize Podman Machine</strong>:</p><ul><li>Run the following command to create your first Podman machine:</li></ul><pre>PS C:\Users\Diluckshan Puviraj&gt; podman machine init</pre><h4>Default Networking</h4><p>By default, Podman creates a virtual machine (VM) with its own network stack. This VM might not be configured to use your office’s proxy server, leading to “<strong>Temporary failure in name resolution</strong>” errors while pulling images from the Docker registry.</p><p><strong>Resolution</strong>: Use the --user-mode-networking flag to tell Podman to use a user-space process on your host machine for network traffic. This ensures the VM respects your office&#39;s proxy configuration.</p><pre>PS C:\Users\Diluckshan Puviraj&gt; podman machine init --user-mode-networking</pre><h4>Successful Machine Initialization</h4><p>Here’s a sample output of a successful machine initialization:</p><pre>C:\Users\Diluckshan Puviraj&gt;podman machine init --user-mode-networking<br>Downloading VM image: v20240703001932-5.1-rootfs-amd64.tar.zst: done<br>Extracting compressed file: podman-machine-default-amd64: done<br>Importing operating system into WSL (this may take a few minutes on a new WSL install)...<br>Import in progress, this may take a few minutes.<br>The operation completed successfully.<br>Installing user-mode networking distribution...<br>Import in progress, this may take a few minutes.<br>The operation completed successfully.<br>Configuring system...<br>Machine init complete</pre><h4>Starting Your Machine</h4><p>After initializing the machine, you can start and stop it as needed:</p><pre>C:\Users\Diluckshan Puviraj&gt;podman machine start<br>Starting machine &quot;podman-machine-default&quot;<br>Starting user-mode networking...<br>Machine &quot;podman-machine-default&quot; started successfully.</pre><h4>First Podman Command</h4><p>For a quick working example with a small image, you can run the Linux date command:</p><pre>C:\Users\Diluckshan Puviraj&gt;podman run ubi8-micro date<br>Resolved &quot;ubi8-micro&quot; as an alias (/etc/containers/registries.conf.d/000-shortnames.conf)<br>Trying to pull registry.access.redhat.com/ubi8-micro:latest...<br>Getting image source signatures<br>Checking if image destination supports signatures<br>Copying blob sha256:e7a9d64512cdd59a229c45e2d05787ea57ef27ef3a978a1c3361d3161ab493ad<br>Copying config sha256:10a6ac0f9a25c420b860f98a7f3dd91ff51ffe80f6610d2044f883676cf94720<br>Writing manifest to image destination<br>Storing signatures<br>Wed Jul  3 05:18:18 UTC 2024</pre><h3>Practical Guides and Templates</h3><p>To maximize the benefits of Podman and Docker in various scenarios, it’s essential to have practical guides and templates that cater to both beginners and professionals. This section provides step-by-step examples and templates for building, using, and adjusting containers with Podman and Docker, covering a range of use cases from simple setups to advanced configurations.</p><h4>For Newbies: Simple Container Setups</h4><p><strong>Running Your First Podman Container: A step-by-step guide to running a simple web server container.</strong></p><ol><li><strong>Pull the Image</strong>: Start by pulling the official Nginx image from Docker Hub:</li></ol><pre>podman pull nginx</pre><p>2. <strong>Run the Container</strong>: Launch your Nginx container with Podman:</p><pre>podman run --name mynginx -d -p 8080:80 nginx</pre><p>3. <strong>Verify the Container</strong>: Ensure the container is running and accessible:</p><pre>podman ps</pre><p>Open a browser and navigate to http://localhost:8080 to see the Nginx welcome page.</p><h3>Conclusion</h3><p>By following this guide, you can leverage Podman on Windows to manage your containers seamlessly, benefiting from its compatibility with Docker tools and WSL2 integration. With its daemonless architecture, rootless containers, and Kubernetes support, Podman is a powerful alternative to Docker, enhancing security and flexibility in your container management. Happy containerizing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=884bed94161f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Exception Handling in Spring Filters]]></title>
            <link>https://medium.com/@diluckshan/mastering-exception-handling-in-spring-boot-filters-70be7bb940c7?source=rss-32ad62c1bcf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/70be7bb940c7</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[filters]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Diluckshan Puviraj]]></dc:creator>
            <pubDate>Wed, 08 May 2024 07:20:01 GMT</pubDate>
            <atom:updated>2024-05-23T15:15:30.475Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-yHwCdl6PPYOd6qiLMq-Aw.png" /></figure><p>Filters in Spring Boot applications act as the gatekeepers, intercepting requests and responses before they reach controllers. While they’re invaluable for security checks, logging, and data validation, exceptions thrown within filters require special attention due to their unique position in the request processing flow.</p><p>When I tested my application with an Invalid Request, BANG! I was greeted with the default, unsightly Error Response (something like the one below) from Spring Boot.</p><pre>{<br>  &quot;timestamp&quot;: &quot;2024-05-08T07:28:52.726+00:00&quot;,<br>  &quot;status&quot;: 500,<br>  &quot;error&quot;: &quot;Internal Server Error&quot;,<br>  &quot;path&quot;: &quot;/api/rest/test/{id}&quot;<br>}</pre><p>So clearly my Exception didn’t reach the GlobalExceptionHandler class.</p><p>This article, accompanied by diagrams, will equip you with the knowledge to effectively handle exceptions in your Spring Boot filters.</p><p><strong>Understanding the Roadblock</strong></p><ul><li>Filters reside outside the controller-based request processing pipeline.</li><li>Standard Spring MVC exception handling mechanisms, like @ControllerAdvice and @ExceptionHandler annotations, bypass filter exceptions.</li></ul><p><strong>Effective Strategy : </strong>Manual Exception Handling within the Filter</p><ul><li>Directly catch exceptions within the doFilter method of your filter.</li><li>Log the exception details for debugging purposes.</li><li>Set appropriate HTTP status codes on the response object (e.g., 400 Bad Request, 500 Internal Server Error).</li><li>Optionally, write a custom error response body in the desired format (JSON, XML, etc.).</li></ul><p>This strategy directly tackles exceptions within the doFilter method of your filter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*XfLkUs6fki1331CeAudd3Q.png" /></figure><p>In the flowchart, the first step is to check if the lamp is plugged in. This is analogous to a pre-filter check in a Spring Boot filter. If the lamp is not plugged in, then it’s the same as a filter exception being thrown. The flowchart then instructs the user to plug in the lamp, which is analogous to resolving the filter exception.</p><p>The next step in the flowchart is to check if the bulb is burned out. This is analogous to another pre-filter check in the Spring Boot filter. If the bulb is burned out, then it’s the same as another filter exception being thrown. The flowchart then instructs the user to replace the bulb, which is analogous to resolving the filter exception.</p><ul><li><strong>Start:</strong> Request arrives at the filter.</li><li><strong>Filter Logic:</strong> The filter performs its designated tasks (e.g., security checks, logging).</li><li><strong>Decision Point:</strong> If no exception occurs, the filter chain continues processing the request (green arrow).</li><li><strong>Exception Handling:</strong> If an exception arises (red arrow), relevant actions are taken</li><li><strong>Logging:</strong> Exception details are logged for debugging purposes.</li><li><strong>HTTP Status Code:</strong> An appropriate HTTP status code is set on the response object (e.g., 400 Bad Request, 500 Internal Server Error).</li><li><strong>Custom Error Response (Optional):</strong> A custom error response body in the desired format (JSON, XML) can be written to the response.</li><li><strong>End:</strong> The request processing flow concludes.</li></ul><p><strong>Code Example:</strong></p><pre>@Component<br>public class ExceptionHandlerFilter extends OncePerRequestFilter {<br><br>    @Override<br>    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {<br>        try {<br>            // Filter logic...<br>            filterChain.doFilter(request, response);<br>        } catch (Exception e) {<br>            logger.error(&quot;Error during filtering:&quot;, e);<br>            response.setStatus(HttpServletResponse.SC_BAD_REQUEST); // Set appropriate status code<br>            response.getWriter().write(&quot;An error occurred while processing your request.&quot;);<br>        }<br>    }<br>}</pre><p><strong>Conclusion</strong></p><p>By employing this strategy, you can effectively handle exceptions thrown within Spring Boot filters, ensuring a robust and user-friendly application. Remember to tailor the approach to your application’s specific needs for optimal results.</p><p><em>Thank you for reading until the end.Good luck!!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70be7bb940c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>