Skip to main content

Posts

Showing posts with the label Spring

How to implement Cache Aside Pattern with Spring?

Problem You want to boost application performance by loading data from a cache and prevent the network trip to the persistent store (and also the query execution). This can be achieved by loading data from a cache. However, you want to load data on demand or lazily. Also, you want the application to control the cache data management – loading, eviction, and retrieval. Forces Improve performance by loading data from cache lazily. Application code controls cache data management. The underlying caching system does not provide read-through, write-through/write-behind strategies (strange really ??). Solution Use cache aside design pattern to solve the problems outlined above. This is also one of many caching patterns/strategies. I believe it is named in this because aside from managing the data store, application code is responsible for managing the cache also. Let's now try to understand how this caching technique works and then explore how it solves the proble...

How to Stand up a Spring Cloud Config Server?

Setup and Configure Spring Cloud Config Server Project Spring Cloud Config Server is just another Spring Boot application. It provides several infrastructure micro services to centralize access to configuration information backed by a version controlled (well at least in the case of default GIT storage) repository. Step 1 - Create a Spring Boot project in STS with the dependencies shown in Figure 2. Figure 1 - Creating Spring Boot project to setup Spring Cloud Config Server Figure 2 - Spring Cloud Config Server dependencies Click on 'Finish' to complete the creation of the Spring Boot project in STS. The build.gradle file is shown in listing below. There is only one dependency to the Spring Cloud Config Server. Also Spring Cloud release train 'Dalston.SR1'. Step 2 - Annotate the class containing main method The next step is to annotate the ConfigServerInfraApplication class with  @EnableConfigServer That's all is needed on the Java si...

Upgrading Lead Microservice - Use MariaDB and Flyway with Spring Boot

So far I have been using an in-memory H2 database or Mockito for testing the lead microservice. To make the transition towards using the Spring Cloud Config server, I need to upgrade the micro-application to use MariaDB . I will be adding the configuration in the application.yml  the file which in the subsequent post will move over to the config server store. I will also be using Flyway to make it easy to maintain the database schema changes in future. I will use this post to introduce Flyway in the mix. Spring Boot also provides first class integration with Flyway. I am using Flyway as its really quick and easy to get started, minimal learning curve (no DSL) and I am comfortable with it having used it in the past. Assumptions MariaDB 10 is installed Basic familiarity with Flyway Heidi SQL client is installed. Step 1 - Update build.gradle to include the MariaDB JDBC and Flyway dependencies. Do not forget to do a Gradle refresh on your IDE (I am using STS 3.8.4 on...

Unit Test - Microservices - Business Layer

In this post, I am going to show how to unit test the business layer of the lead microservice that I am developing. A couple of things to keep in mind to write the unit test for the business layer. These tests run must very fast for quick feedback. Only the business layer is involved and hence the web layer and repository layer should not be started. In other words, the Spring web tier beans should not be created and neither any database connections should be used. (This helps to achieve #1).  The repository layer will be mocked using Mockito. The fluent assert from AssertJ library will be used.  The source code of the lead business unit test is shown in listing below. Most of the test methods are straight forward. However, the testDelete  the method needs some explanation. Here the findOne method is mocked/stubbed. This ensures that correct lead object is returned by the stub method. The other thing to note is that the verify the method for saving method...

Complete Unit tests - Microservices - Repository Layer

In the previous post, I introduced the unit tests for the repository layer of the lead microservice. In this short post, I will do some cleanup, add all the unit tests. Finally, I replaced all the JUNIT asserts with AssertJ asserts. AssserJ is also recommended by the Spring champions over at Pivotal. AssertJ  - provides fluent assertions for Java.  Testing improvements in Spring Boot .  Ok thats it for now. In the next post I will show how to unit test the business / service layer of the lead microservice.

Microservice - Unit Test - Repository Layer

Now that we have completed the first round of development of our lead microservice, it is time to focus on some testing. I will follow a bottom-up approach and start by writing unit tests for the repository layer. In order to write unit tests, I will make use of the Spring Test Framework and Spring Boot Test support. Spring Boot makes it extremely easy to unit test slices of the application. We can use @ DataJpaTest  and just unit test the database layer with an embedded database like H2. However, there are some gotchas (I do not know exactly what at this moment), the @DataJpaTest does not work if you have extended the Spring Data JPA to add a custom method for all the repositories. The problem I found was that the when running the Spring Boot application, everything works fine and the custom method works fine and the query returns the correct results. However, when the unit test is run, Spring Data JPA fails, complaining that it is not able to find an attribute for ...

Lead Microservice - Add the service and controller

This post continues from the last one . I will try to complete the lead microservice in this post. I will be focusing primarily on the CRUD operation. In CRM applications, that is the primary set of operations. I will start by creating the exception class. Later I would show how to use this exception class and Spring Rest exception handling and build a robust error handling around the API calls. Listing 1 - BusinessException.java Next step would be to introduce the service class. Since this is CRUD most of the functionality can be encapsulated in an abstract parent service class. Any specific feature like convert lead to opportunity can be implemented in the LeadService class. Listing 2 - AbstractBaseBusinessDelegate.java And then finally the LeadService implementation class is shown in Listing 3. Listing 3 - LeadBusinessDelegate.java Note that this code will not compile. In order to get this to compile, you will need to add 2 new dependencies for the...

First Microservice - Lead Service

This is a continuation of my previous post where I listed the key domain components of CRM. For sake of simplicity, I will focus on just two key components - Lead and Opportunity respectively. These two modules will help me explore end to microservice implementation. I will be primarily using Spring framework's support to deliver the microservices. I am deliberating on a nice interesting Javascript framework for the front end. More on this later. Goal For the time being, I am just going to focus on building the backend and cloud enable it. Then slowly I am going to add the front end and security to the backend and front end. I will also explore the complete Sping Cloud gamut of projects and beyond. I will then deliberate on cloud-native applications, transactions and actually making this application suitable to run on virtually any cloud. I will also explore cloud and microservices application design patterns. Last but not the least we also need to check where this application...

Spring 4: Unit Testing Classic Controller

Spring Boot is a great gift for all Spring developers. The productivity boost is enormous. It also makes it extremely easy to unit tests slices of your layered application. This feature is available from Spring Boot 1.4.x onwards. In this post, I am going to focus only on unit testing of Spring MVC classic controller i.e non-REST controller. Spring Boot test slice support for MVC controller is enabled by the following annotation This tells Spring MVC test framework that we only intend to test EmployeeController So it will only make the web MVC components (controllers, interceptors etc) available with mocking support. For more details of this annotation please refer to the Javadoc here . In the example above, we are testing the request to copy the Employee. Mockito is used to create and inject the mock objects. Spring takes care of the mock objects, dependencies for us. This makes it extremely easy to write unit tests for classic Spring MVC controllers. Note that for quic...

Part 3 - Introducing Spring Security, Thymeleaf and Spring MVC

Security is one of the key aspect of an application, especially web application. In our application we intend to integrate Spring Security as we are already on Spring framework. Alternative was Apache Shiro. But we prefer Spring Security. Here is how we can integrate Spring Security with Spring MVC and Thymeleaf. The first step to this integration is to include the Spring Security and Thymeleaf Spring Security jars into our application. This can be done by adding Maven dependencies. Here is the snippet from the parent/pom.xml file. Listing 1 - parent/pom.xml - snippet <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <!-- SPRING SECURITY --> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${spring-security.version}</version> </dependency>...

Adding anonymous or guest access in Spring Security

As you have seen in my previous post the access to index.html was restricted. Whenever the user tries to access this page they were redirected to the login page. But this should not be case. The logical index.html page should be accessible to guest users as well as authenticated users. Turning this on is just a matter of configuration. This is shown in the modified spring-security.xml file. Listing 1 - spring.security.xml I have now added a new intercept url line. <intercept-url pattern="/index.html" access="IS_AUTHENTICATED_ANONYMOUSLY" /> This line makes it possible to access index.html as a guest user. Now when you click on any link on the index.html page you will be redirected to the login page in case you have not signed in. In my next post, I will try to get into some theoretical details/framework internals before proceeding to the next round of coding and adding additional features.

Enabling Spring Security

1> Add few more jars in your WEB-INF/lib folder. The current view of jars is shown in the figure below. Figure 1 - Adding the Jars 2> Add a new member named - spring-security.xml in the WEB-INF/config folder. The contents of this file is shown in Listing 1 below: Listing 1 - spring-security.xml This is the bare minimum configuration you need to do to get Spring Security started. This is a great relief for those of you who had worked with earlier versions of Spring Security or its ancestor Acegi Security. You had to explicitly configure the entire filter chain. That was tedious and very cumbersome leading to lot of errors and time and effort going down the drain. Thanks Ben and team for this good change. I will explain the different elements in this configuration in future posts as the intention of this post is to quickly get started with Spring Security as promised earlier. Step 3 - wire everything now in the web.xml. The modified web.xml looks like the one shown be...

Getting the security less application ready

1> Add jstl.jar (version 1.1 i guess) to your WEB-INF/lib folder 2> Modify index.jsp as shown below Listing 1 - index.jsp 3> Add a controller for the landing or index page. Listing 2 - EntryController.java 4> Add a controller for the upload page view Listing 3 - UploadController.java 5> Time to launch the browser and test it on the browser. Figure 1 - Skyphotos 6> Click on upload photo, you will see it is accessible to any one. But only logged on users should be able to access that page. Figure 2 - secure page In the next post I will start with the first step to ensure that a user is logged in / signed in before he or she can access the upload photo page.

Adding few more JSPs and Security Requirements

Now I will add two more JSPs – one is the home page showing some dashboard information and the other is the file upload JSP which will be used to upload photos. Listing 1 – home.jsp Listing 2 – upload.jsp Requirement index.jsp should be accessible without any security filtering home.jsp should be accessible only to registered users upload.jsp should only be accessible to registered users Since the JSPs are placed under WEB-INF in any case no one can directly access it. So in the next post I will try to add a few page controllers to the scheme of things to make these pages accessible without any application security credentials.

Setting up Spring MVC 3 Web Application

Now its time to code a bit in Skyphoto. So launch Eclipe and create a dynamic web project ready to be deployed on Tomcat 6. I am assuming that readers are atleast familiar with this. Next we will do a bit of configuration and throw in some Spring 3 jar files into the WEB-INF/lib folder. Step 1 - Configure Spring Servlets and log4j in the web application deployment descriptor. Step 2 - log4j.xml The log4j configuration will be very useful later to see all framework and application messages. I have set it to debug level to help understand the framework better. Step 3 - Setting up a bare minimal spring configuration file Listing 3 - spring-web.xml Step 4 - setup a simple jsp Listing 4 - index.jsp Figure 1 - Project Directory Structure in Eclipse Finally here is a view of the Eclipse project shown in Figure 1. You can very well make out the jar files you need for the time being. Note 1 - that I am storing all configuration files under /WEB-INF/config Note 2 -...

Exploring Spring Security 3

I am finally back to writing again after an absence of almost year and half. I will try to be more regular from now now. In this edition I will start with Spring Security 3. This will be a series of posts where I will try to build a very simple photo uploading and sharing service. This is actually my PoC with Spring Security 3. Spring Security unlike most Spring product portfolio is a not at all well documented. The tutorials available on googling are mostly outdated. Spring Security 3 certainly by look of things seems to be a very good feature rich product yet hefty beast. So here is my attempt to conquer it. Skyphoto Basic Requirements Securely upload photos into your account Download photos Share photos with friends and other application In the course of this simple application development I will try to uncover most of the features of Spring Security. I will use Restful services support provided by Spring MVC so that I can expose a simple API for external applications ...

Consuming a JMS Message from ActiveMQ using Spring Message Driven POJO

In my last post, I had shown how you can post a JMS message to a ActiveMQ queue. In this post I will show the reverse process. I will not try to consume this message using a Spring Message Driven POJO. I assume your familiarity with Spring MDP. If not you can look here - http://static.springframework.org/spring/docs/2.5.x/reference/jms.html The operation that I intend to carry out is depicted in Figure 1. Figure 1 - Consuming JMS message using Spring MDP Step 1 - Create the message listener. Listing 1 - EventMessageConsumer.java Step 2 - Wire up the bean in Spring configuration Listing 2 - spring-activemq-config.xml Step 3  - Test Finally you can see the results of message produced and consumed in the Admin web console as shown in Figure 2. Figure 2 - Queue statistics

Sending JMS message to ActiveMQ using Spring 2.5 from a web application

Last Updated 04/16/2017 In this post, I will show how you can send JMS message to ActiveMQ from your Spring web application. I have a Spring 2.5 + JBOSS Richfaces based web application that runs on Tomcat 6 running on JDK 5. Figure 1. depicts what I intend to do. Figure - 1 Send JMS Message to ActiveMQ using Spring from a web application Step 1: Drop in the following jars to WEB-INF/lib activemq-core-5.2.0.jar jms.jar geronimo-j2ee-management_1.0_spec-1.0.jar Step 2: Create the destination/Queue using the ActiveMQ admin web application. Launch your browser and point it to - http://localhost:8161/admin/ Figure 2 - ActiveMQ Admin Console Click on 'Queues' to navigate to queue list and create screen. You will need to supply the queue name and click on 'Create' to create a new queue destination on ActiveMQ server. This is shown in Figure 3. Figure 3 - Create a new Queue Step 3. Create a message producer interface . This may not be necessary...

Initializing static fields of Spring beans

New Solution - Updated 4/16/2017 The old solution shown below is very cumbersome. So here is the new solution which is much easier. Old solution This solution is courtesy Chris Harris UK. Step 1: Create a bean factory post processor.  Step 2 : Create the simple test class Step 3 : Finally wire up everything in Spring configuration file