Monday, 9 September 2019

How to add a filter to spring boot application?


Step 1: Create a filter by implementing Filter interface.
@Component
public class PerformanceFilter implements Filter {
    private final Logger logger = LoggerFactory.getLogger(PerformanceFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        long time1 = System.nanoTime();
        chain.doFilter(request, response);
        long time2 = System.nanoTime();

        logger.info("Total time taken: {} nano seconds", (time2 - time1));

    }

}

Make sure you added spring annotation @Component.


Step 2: Create a bean of type 'FilterRegistrationBean'.
@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean<PerformanceFilter> perfFilter() {
        FilterRegistrationBean<PerformanceFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new PerformanceFilter());
        registration.addUrlPatterns("/*");
        return registration;
    }
}

As you see above snippet, I applied PerformanceFilter on all url patterns.

Find the below working application.


App.java
package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

}


FilterConfig.java
package com.sample.app.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.sample.app.filter.PerformanceFilter;

@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean<PerformanceFilter> perfFilter() {
        FilterRegistrationBean<PerformanceFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new PerformanceFilter());
        registration.addUrlPatterns("/*");
        return registration;
    }
}


HomeController.java
package com.sample.app.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {

    @RequestMapping("/")
    public String homePage() {
        return "Welcome to Spring boot Application Development";
    }

}


PerformanceFilter.java
package com.sample.app.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class PerformanceFilter implements Filter {
    private final Logger logger = LoggerFactory.getLogger(PerformanceFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        long time1 = System.nanoTime();
        chain.doFilter(request, response);
        long time2 = System.nanoTime();

        logger.info("Total time taken: {} nano seconds", (time2 - time1));

    }

}


pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>springbootMisc</groupId>
    <artifactId>springbootMisc</artifactId>
    <version>1</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
    </parent>

    <packaging>jar</packaging>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

    </dependencies>

</project>


Total project structure looks like below.

Run App.java.

Open the url ‘http://localhost:8080/’ in browser. You can see below kind of message in console.

2019-07-19 12:05:59.462  INFO 41560 --- [nio-8080-exec-1] com.sample.app.filter.PerformanceFilter  : Total time taken: 34703886 nano seconds

You can download complete working application from this link.

Previous                                                    Next                                                    Home

Saturday, 7 September 2019

JsonPath Syntax


Below table summarises the syntax that we should follow while extracting the data from json document.

JSONPath
Description
$
Represents root element
@
Represent current object
. or []
Child Operator. Used to access child document.
..
Recursive descent
*
All objects
[]
Array Operator
[,]
Union operator in XPath results in a combination of node sets. JSONPath allows alternate names or array indices as a set.
[start:end:step]
Array Slice Operator
?()
Applies a filter or expression
()
Script Expression, using the underlying script engine.

I am going to explain each JsonPath syntax in my upcoming posts.


Previous                                                    Next                                                    Home

JsonPath: Parse the document before querying


In my previous post, I explained how to extract the information from a json document using 'JsonPath.read()' method. If you want to extract the data once this is OK. In case you need to extract other parts of the data as well this is not the way to go since the document will be parsed every time you call JsonPath.read(...). To avoid the problem you can parse the json first.

Example
Object jsonDocument = Configuration.defaultConfiguration().jsonProvider().parse(json);

String firstOrganization = JsonPath.read(jsonDocument, "$.org[0].name");
String secondOrganization = JsonPath.read(jsonDocument, "$.org[1].name");
String firstName = JsonPath.read(jsonDocument, "$.empName.firstName");
String lastName = JsonPath.read(jsonDocument, "$.empName.lastName");
double salary = JsonPath.read(jsonDocument, "$.salary");

Input
{
 "org": [{
  "name": "Honeywell",
  "yrsOfExperience": 2.2
 }, {
  "name": "IBM",
  "yrsOfExperience": 1.8
 }],

 "empName": {
  "firstName": "Krishna",
  "lastName": "Rama"
 },

 "salary": 80000.0
}


App.java
package com.sample.app;

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;

public class App {

 public static void main(String[] args) {

  String json = "{\n" + 
    " \"org\": [{\n" + 
    "  \"name\": \"Honeywell\",\n" + 
    "  \"yrsOfExperience\": 2.2\n" + 
    " }, {\n" + 
    "  \"name\": \"IBM\",\n" + 
    "  \"yrsOfExperience\": 1.8\n" + 
    " }],\n" + 
    "\n" + 
    " \"empName\": {\n" + 
    "  \"firstName\": \"Krishna\",\n" + 
    "  \"lastName\": \"Rama\"\n" + 
    " },\n" + 
    "\n" + 
    " \"salary\": 80000.0\n" + 
    "}";

  Object jsonDocument = Configuration.defaultConfiguration().jsonProvider().parse(json);
  
  String firstOrganization = JsonPath.read(jsonDocument, "$.org[0].name");
  String secondOrganization = JsonPath.read(jsonDocument, "$.org[1].name");
  String firstName = JsonPath.read(jsonDocument, "$.empName.firstName");
  String lastName = JsonPath.read(jsonDocument, "$.empName.lastName");
  double salary = JsonPath.read(jsonDocument, "$.salary");

  System.out.println("firstOrganization : " + firstOrganization);
  System.out.println("secondOrganization : " + secondOrganization);
  System.out.println("firstName : " + firstName);
  System.out.println("lastName : " + lastName);
  System.out.println("salary : " + salary);


 }

}

Output
firstOrganization : Honeywell
secondOrganization : IBM
firstName : Krishna
lastName : Rama
salary : 80000.0



Previous                                                    Next                                                    Home

JsonPath: Hello World Application


Let's extract organization names, employee firstName, lastName and salary from below json document.
{
 "org": [{
  "name": "Honeywell",
  "yrsOfExperience": 2.2
 }, {
  "name": "IBM",
  "yrsOfExperience": 1.8
 }],

 "empName": {
  "firstName": "Krishna",
  "lastName": "Rama"
 },

 "salary": 80000.0
}

"$.empName.firstName": Extract firstName from the document.
"$.empName.lastName": Extract lastNam from the document.
"$.org[0].name": Extract first organisation name
"$.org[1].name": Extract second organisation name

"$" represents root element.

Example
String firstOrganization = JsonPath.read(json, "$.org[0].name");
String secondOrganization = JsonPath.read(json, "$.org[1].name");
String firstName = JsonPath.read(json, "$.empName.firstName");
String lastName = JsonPath.read(json, "$.empName.lastName");
double salary = JsonPath.read(json, "$.salary");

App.java
package com.sample.app;

import com.jayway.jsonpath.JsonPath;

public class App {

 public static void main(String[] args) {

  String json = "{\n" + 
    " \"org\": [{\n" + 
    "  \"name\": \"Honeywell\",\n" + 
    "  \"yrsOfExperience\": 2.2\n" + 
    " }, {\n" + 
    "  \"name\": \"IBM\",\n" + 
    "  \"yrsOfExperience\": 1.8\n" + 
    " }],\n" + 
    "\n" + 
    " \"empName\": {\n" + 
    "  \"firstName\": \"Krishna\",\n" + 
    "  \"lastName\": \"Rama\"\n" + 
    " },\n" + 
    "\n" + 
    " \"salary\": 80000.0\n" + 
    "}";

  String firstOrganization = JsonPath.read(json, "$.org[0].name");
  String secondOrganization = JsonPath.read(json, "$.org[1].name");
  String firstName = JsonPath.read(json, "$.empName.firstName");
  String lastName = JsonPath.read(json, "$.empName.lastName");
  double salary = JsonPath.read(json, "$.salary");

  System.out.println("firstOrganization : " + firstOrganization);
  System.out.println("secondOrganization : " + secondOrganization);
  System.out.println("firstName : " + firstName);
  System.out.println("lastName : " + lastName);
  System.out.println("salary : " + salary);


 }

}


Output
firstOrganization : Honeywell
secondOrganization : IBM
firstName : Krishna
lastName : Rama
salary : 80000.0


Previous                                                    Next                                                    Home

Introduction to jsonPath


jsonPath is used to analyse, transform and selectively extract data out of json documents.

I am going to use below maven dependency.

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>


Reference

Previous                                                    Next                                                    Home