Skip to main content

Posts

Showing posts with the label spring boot

Using Spring Cloud Config Server for Multi-tenancy configuration

Let's walk through a basic example of how to set up and use Spring Cloud Config Server to manage configuration for multiple tenants in a Spring Boot Application. Step 1: Create a Spring Cloud Config Server Create a new Spring Boot project with the Spring Cloud Config Server dependency. <!-- pom.xml --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> Configure the Spring Cloud Config Server: // src/main/java/com/example/ConfigServerApplication.java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.config.server.EnableConfigServer; @SpringBootApplication @EnableConfigServer public class ConfigServerApplication { public static void main(String[] args) { SpringApplication.run(ConfigServerApplication.class, args); } } Configure the appl

Upgrade from http1.1 to http2 for Java spring boot applications hosted in tomcat

In this post, we will list down the tasks to be done for enabling the HTTP 2.0 support in spring boot applications which are hosted in Apache tomcat webserver Application Level Changes Spring boot Application Configuration Changes server.http2.enabled=true In the spring boot application's application.properties file, we have to add the above line so that Spring boot can add the support for http2 Tomcat server configuration In the tomcat web server, we should have SSL enabled before doing the below change. To start with, we have to shutdown the tomcat server instance that is running CD to the directory that has tomcat installed and cd to the bin directory and run the below command sh shutdown.sh We have add the UpgradeProtocol  which adds the respective Http2Protocol handler classname to the connector pipeline that enables support for http2.0 <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" /> The above UpgradeProtocol can be added to the connec

Jsonview in Spring boot

Introduction There are scenarios where we have a DTO or a model class that contains a collection of properties and there might be some endpoints that require a subset of them and some other endpoint that might need all of them. Example: Consider a scenario where we need a list of Categories in a dropdown and we have an API that gets all the categories from the static masterdata and need to send to the UI in response to an API call. Problem Statement  We might choose to use a `Map` data type so that we send out the key-value pairs to the database or to choose to build a custom DTO with only the Id, name of the categories. In a longer run, if we opt to use multiple DTO in the source, sooner there will be a very large collection of DTO classes that represent subset of a static data. Solution Rather than ending up with a large number of such DTO classes, we can use a JSON View. This helps us have a single class and control which fields are part of which view.  Example: We can have a dropd

Handling exceptions in the Executor service threads in Java

Introduction This is a continuation post on the exception handling strategies in the threads in Java. For Introduction, please read this post The second post is available here This post addresses the problem statement "How to use the exception handlers in the threads spawned by the Executor Service in Java?" Not all times, we will be using Thread  classes to run our threads because we have to manage a lot of the underlying logic for managing threads. There is ExecutorService in Java which comes to the rescue for the above problem. In the previous posts, we have discussed on how to handle the exceptions in plain threads. However, when using executor service, we do not create / manage threads, so how do we handle exception in this case. We have a ThreadFactory   as an argument which can be used to customize the way threads are created for use within the ExecutorService . The below snippet of code leverages this feature to illustrate the exception handling, wherein we create a

Handling exceptions at thread level in Java

Introduction This is a continuation to the post on exception handling on threads. For those interested in the background, please visit this link This post discusses on the topic "Can I use separate exception handlers for threads performing mission critical tasks vs non trivial tasks?" Per-Thread Exception Handler Let's us assume that we built a handler that wants to notify the support team that something has gone wrong in some special thread processing, like the one below (not really notifying anyone but helps correlate the context) class SupportNotificationExceptionHandler implements Thread . UncaughtExceptionHandler { @Override public void uncaughtException ( Thread t, Throwable e) { notifySupport (t, e); } private void notifySupport ( Thread t, Throwable e) { System . out . println ( "Notified support team on: " + e. getMessage () + " raised from : " + t. getName ()); } } Let us now apply the above special handle

How to implement Global Exception Handler in Spring Boot

Exception Handling There is always a requirement to handle all the NFR (Non-Functional Requirements) well in any application so that the application performs well in production and possess the excellent traceability and exception reporting mechanisms for better visibility on what happens in applications. Types of Exceptions We normally use exceptions within each domain of the application like Customers, Orders, Inventory etc. There are also a lot of custom exceptions that might be required when the application is built to capture, report the exceptions to the user. In this process, we can follow the below given process Base Exceptions There are multiple use-cases where we need separate exceptions to report multiple error conditions or cases, let us consider one such case for data validation. BaseValidationException import java.util.List; public class BaseValidationException extends RuntimeException { public BaseValidationException() { super(); } public BaseVali

Helpful functions from org apache commons collections

Introduction There are times when we are faced with the option to get the intersection of 2 lists. The type of list can be either a simple type like number / strings or a complex type like Object. This might involve developers building loops and performing comparison. This can be resulting in not following the DRY principle where we do not have to repeat ourselves what is already implemented. We can leverage the functionality provided in the collections4 library which can help us get the desired result. In this example, let us consider the following example.  Sample Scenario We can consider a "Cart" store which keeps track of the various items that we have added the cart. Every addition or deletion of the item to the cart needs to be updated. User's normally add some items and when they find out that their product of interest has its availability, they would want to add that to the cart and balance out by removing a lesser priority item. Now, when the user proceeds for th

Spring boot Aspect Oriented Programming

What is AOP AOP stands for Aspect Oriented Programming. It is mainly used to implement the Cross-Cutting concerns in applications. These are used to reduce the mix of the business logic from the NFR (Non Functional Requirements) like logging, performance monitoring, validations etc. Also, these "Aspects" can be [should be] generalized and be located in a common library or package so that it can be easily upgraded / patched. Further, these Aspects are to be implemented without bringing-in these Aspects into every service or business logic layer so that they can be less invasive and like autowired to get the job done without being omni-present. Spring AOP helps us achieve this model by bringing in the support for the Aspects and help us wire these aspects at places where required. Core Terms / Concepts Aspect This is the cross cutting concern like logging / time measurement / validation etc. Join Point The method execution. (Example: Executing a service method like CustomerServ

Using Hashicorp Vault

Why a Vault? The reason for having a vault is to have the secrets for the application stored in a very "safe" / "secure" location so that only trusted clients of the Vault (Web Apps / Services etc ) can get access to the secrets. When we do not use a vault, the dev team will check-in the secrets like Database Credentials, AWS credentials etc to the source control, which leaves it open to be accessible to anyone that gets access to source code. There are a lot of Vaults out there in AWS, Azure etc, but this system is opensource and we have full control of the installation and security, which piqued my interest and hence I started exploration. Dangers of exposing Secrets In the hands of wrong person, it could be disastrous, especially if the secret has more privileges, more the depth of the damage Developers might get to try out changes with these credentials. In recent years, a colleague of mine forgot to append the where clause in the production

Migrating from Springfox to OpenAPI 3 in spring boot Java

Migrating from Springfox to OpenAPI 3 in Spring Boot Application This blogpost, I would like to share about the migration to OpenAPI 3 in my project application that is built using Java 8 and Spring boot.  I was working in a project that had a very old framework support and JDK. I was taking my free time whenever I find one and then did some upgrade to the core so as to get the application to be on the latest frameworks and get support if any issues. Why Upgrade? The reason for upgrade is to facilitate the following The application dependencies are up-to-date, meaning that when we face any issue or require any help, people will be able to help (Community support). Though we have support for the deprecated frameworks also from the vibrant community like Stackoverflow.com, better to be with the upgrades There might be limitations hindering in building new functionality or extending existing ones with the older versions, so a version upgrade to the latest will be always handy