Category Archives: Core Java

Error with Spring Context Lookup Failed

In this post, I will show how to resolve the error Spring context lookup failed. This scenario resembles if you are using Spring Boot 2.x or Spring Boot 1.5. I was recently using Spring Boot 2.x and ran into an error like below:

org.glassfish.jersey.server.spring.SpringComponentProvider: Spring context lookup failed, 
skipping spring component provider initialization.

 

Why did I see this error?

Before I can explain why I saw this error. Let’s sort of some basic concepts about what  ContextLoaderListner is and what DispatcherServlet is.

Spring boot creates multiple contexts. It will start with a root context and the rest of the contexts will be child contexts. Child contexts can access the beans defined in the root context, but not vice versa.

ContextLoaderListener

When you start the Spring Boot application, ContextLoaderListener creates the root application context. Spring boot will share this root context with all other child contexts that DispatcherServlet will create. Usually, you define ContextLoaderListener in web.xml like below:


<listener>
  <listener-class>
    org.springframework.web.context.ContextLoaderListener
  </listener-class>
</listener>
  
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/spring/applicationContext.xml</param-value>
</context-param>

ServletContext stores this root application context and one can use WebApplicationContextUtils to retrieve this context.

DispatcherServlet

DispatcherServlet is a HttpServlet whose primary purpose is to handle incoming web requests matching the configured URL pattern. When you define DispatcherServlet in Spring configuration, Spring will use a configured configuration file or creates its own configuration file based on controllers and views in the code.

DispatcherServlet creates one child application context per servlet entry.

Why Spring Context Lookup Failed:

Spring Boot 2.x offers a programmatic way to configure your contexts and servlets. In my particular case, I was using this programmatic way. But I had configured anyway to load application context, especially root application context.

To configure this root application context, I needed ContextLoaderListener . Since I didn’t want to use web.xml , I looked for a programmatic way. Spring boot 2.x offers this through SpringBootServletInitializer . Basically, when we extend the root application class with SpringBootServletInitializer, it binds Servlet, Filter, and ServletInitializer beans from the application context to the server. This also allows us to create a WAR archive of our application and run in any web container.

Once I added SpringBootServletInitializer in my main Spring Boot Application class, I was able to resolve this error. The code for that will look like below:


@SpringBootApplication
public class Application extends SpringBootServletInitializer 
{    
    public static void main(String[] args) 
    {
        SpringApplication sa = new SpringApplication(Application.class);
        sa.run(args);
    }
}

 

Conclusion

In this post, we showed how we can resolve an error Spring Context Lookup Failed. If you have any feedback about this post, please comment and I will be happy to answer.

References

  1. ContextLoaderListener vs DispatcherServlet
  2. Spring Boot Servlet Initializer
  3. Upgrade Spring Boot and adding Spring Boot Actuator – Spring Boot Actuator

 

 

How to integrate reCaptcha with Spring Boot Application

In this post, I want to show how to integrate ReCaptcha in a Spring Boot application. This will be an important step if you have forms in your application and if those forms are publicly available on the internet. You can face a lot of spams or bots trying to fill those forms. To avoid these spams from bots, ReCaptcha is of utmost importance.

Google offers a reCaptcha service that we will integrate with Spring Boot application to stop bots from submitting the forms in our application.

Registration with Google for ReCaptcha

Google offers a reCaptcha service that developers can use in their applications. As part of this implementation, we will register our service in Google APIs so that Google can provide us credentials to use while calling its service.

We can register our site at Google Recaptcha Administration. This registration will provide us with site-key and site-secret.

Now as part of Spring boot application, we can store these credentials in application.properties file as below:

# ====================================================================================
# Google reCaptcha Settings
# ====================================================================================
google.recaptcha.key.site=site-key
google.recaptcha.key.secret=site-secret

We will make these properties available through a spring bean object in our application, so we can use them when we call Google Recaptcha Service.

UI changes to display ReCaptcha box

Now to display Recaptcha box on your form, we will add the following code in our templates where our public form resides. In this case, I am putting Recaptcha box in Contact Us and Sign Up pages as those are publicly available forms.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <title>Renters Feedback</title>

    <!-- other scripts and stylesheets -->
    <script src='https://www.google.com/recaptcha/api.js'></script>

</head>
<body>

<form method = "post" id="contactus" th:action="@{/contact}">
<!--- other code to display contact us form -->
<div class="g-recaptcha" th:attr="data-sitekey=${@captchaSettings.getSite()}"></div><br/><br/>
<span id="captchaError" class="alert alert-danger col-sm-4" style="display:none"></span>
</form>

</body>
</html>

 

Server-side handling of ReCaptcha

So as we have a widget on our form. When a user completes a challenge and submits the form, the request will be sent to the server containing an encoded site key and a unique string that identifies user’s challenge completion.

But on the server side, we can’t just assume and trust what the user has submitted. So we need to verify this captcha challenge by sending a request to Google API at https://www.google.com/recaptcha/api/siteverify by passing captcha response we have received.

If the verification is successful, the json response from API will contain a success parameter.

If the verification fails, then an application will throw an exception and reCaptcha library will instruct a client to create a new challenge.

One thing to understand here is that we limit how many attempts a client can make to reCaptcha challenge. The reason for this is to avoid any kind of DoS attack. Of course, this is precautionary and elementary step. We implement ReCaptchaAttemptService to block if a client tries to use the challenge for more than 4 attempts.

Demo of the complete workflow of ReCaptcha

Conclusion

In this post, we showed how we can use google reCaptcha service to integrate a reCaptcha widget in a form that is publicly available to avoid bots spams. From the security perspective, this is an important step and developers should take into account this important feature for their web applications.

References

  1. Recaptcha with Spring Boot Application – Recaptcha With Spring Boot Application
  2. Protecting Spring Boot application with Google Recaptcha – Protecting Spring Boot Application

 

 

Techstack Framework for RentersFeedback

As a developer, we make different choices based on what is available to us and what we know. But are those choices always better? They may not or they may. It really depends. In this post, I describe the techstack framework that I used to build Renters Feedback.

You can read my post, how I came up with an idea to build an application for renters feedback.

I wanted to describe the process of the choices I made to choose a tech stack framework for building the application. Considering my expertise in Spring Boot, it was a default choice to use to build this application. There are other factors I took into account like the ease of coding, ease of deploying as a microservice-based application in the cloud, and docker.

Techstack Framework for Renters Feedback

Development Framework For Renters Feedback

For developing the application, my focus was on the re-usability of code. Since I have written few applications as part of this blog using Spring Boot, there was authentication, login forms, sign up forms, most of that code was readily available. One thing I have to think through for RentersFeedback was database modeling.

Database Framework for Renters Feedback

For developing a database based application, I used mysql as a development database. In production, I changed that to postgresql . 

Why database change? 

Heroku support for mysql wasn’t straightforward, so I preferred what was available by default and it was postgresql. I have to do a few changes to mysql scripts. I could have automated these scripts through liquibase, but I preferred not to for the first version of the product. In the future, when I plan to add more changes to the database model, I will add liquibase-based scripts.

Authentication Scheme

There were some questions about why a user needs to login on a RentersFeedback website. Well, someone has to post those reviews before people can browse it. You need to login if you want to post a review.

The easiest choice was to have form-based login even though it is getting old and not safe. I still feel most users would use email to login. User passwords are stored in an encrypted and hashed format in the database.

Another mechanism, I decided to add, was OAuth2 OpenId protocol by using Google API for the same. It was easy to implement and something I have expertise in.

I could add other social logins, but I prefer to keep it simple and if the need arises, I will add those logins in the future.

Using Google API, made me use Redis Cache. I wasn’t planning to use cache since the application is still in nascent stages, but now it is there, so future scaling would be easier from a performance perspective.

User Interface

The user interface was built using Spring Boot provided thymeleaf templates along with Twitter’s Bootstrap CSS library and javascript library. For the search feature, I have used javascript library of Google search APIs.

After deploying the application on Heroku, I came across a few issues about having forms available publicly. To avoid spams, I will be adding Captcha on those forms. I will show how to use reCaptcha APIs in the next post.

To allow users to reset the password, I have used Spring Boot Email system. This was an easy implementation once you know how the forgot your password flow works.

Deployment Environment

I used Heroku to deploy my application. Heroku has great documentation. It’s very easy to sync up with your GitHub repository. So if you push your changes to GitHub, it will sync up to build and deploy on Heroku.

Questions

Choosing the right tech stack framework for your application can be a difficult task if you are a beginner.  Since I have experience in building applications, choosing this techstack framework for Renters Feedback was a straightforward choice. If you have any questions about implementation, why I used certain technology, and how it can be improved, you can post a comment on this blog and I will answer those questions.

 

Metrics collection with Micrometer and Prometheus

In my previous post here, I showed how to configure Micrometer and Prometheus to collect microservice performance metrics data. In this post, I will show how we can collect Spring Boot Actuator metrics data and transfer to Prometheus UI, and view it using dashboards.

Spring Boot offers a lot of great features with Actuator. With enterprise applications constantly looking for ways to monitor the application, these metrics become even more important.

Configure Prometheus using the docker

Firstly, we will configure the Prometheus. Depending on the environment you are using, start the docker terminal. Use the following command to download Prometheus

docker pull prom/prometheus

We will configure Prometheus to scrape metrics from our application’s actuator endpoint. As shown in the previous post here, spring boot actuator endpoint is running on http://localhost:8080/actuator/prometheus

We will add Prometheus configuration in prometheus.yml file as below:

# my global config
global:
  scrape_interval:     5s # Set the scrape interval to every 5 seconds. Default is every 1 minute.
  evaluation_interval: 5s # Evaluate rules every 5 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).
 
# Alertmanager configuration
alerting:
  alertmanagers:
  - static_configs:
    - targets:
      # - alertmanager:9093
 
# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  # - "first_rules.yml"
  # - "second_rules.yml"
 
# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: 'prometheus'
 
    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.
 
    static_configs:
    - targets: ['localhost:9090']
 
  - job_name: 'spring-actuator'
    metrics_path: '/actuator/prometheus'
    scrape_interval: 5s
    static_configs:
    - targets: ['IPADDRESS_OF_HOST:8080']

Few things to notice from this configuration file. scrape_interval is 5s. In scrape_configs , job name for our Spring Actuator endpoint is spring-actuator and the endpoint is running at /actuator/prometheus. The targets section shows where our application is running.  Save this file at a location that we can use to mount while running the docker container.

To Run the Prometheus using docker, use the following command:

docker run --name prometheus -d --mount type=bind,source=//c/Users/sandbox/prometheus.yml,destination=/etc/prometheus/prometheus.yml -p 9090:9090 prom/prometheus

This will start the Prometheus server at 9090 and it can be accessed at 9090.  Meanwhile, we can check the Prometheus dashboard. Let’s get the docker IP first by using the following command

docker-machine ip

Now check the Prometheus dashboard at http://docker-ip:9090 , it will look like below:

Spring Boot Actuator Metrics in Prometheus Dashboard

Conclusion

In this post, we showed how to run a Prometheus out of docker container and scrape metrics from Spring boot application.

References

  1. Spring Boot and Prometheus – Spring boot actuator and Prometheus
  2. Monitoring your microservices – Monitoring your microservices