Tuesday, 13 March 2018

A short tutorial on FindBugs

In this tutorial series, you are going to learn
a.   What is FindBugs
b.   System Requirments
c.   Platform independency of FindBugs
d.   Install FindBugs
e.   Running FindBugs
f.    Running the Analysis using FindBugs GUI
g.   Saving and Opening the results
h.   How to install FindBugs in Eclipse
i.     Configure FireBug in Eclipse
j.    How to find the bugs using FindBugs in Eclipse

What is FindBugs?
FindBugs is a tool that uses static analysis to find bugs in Java code. At the time of writing this article, the current version of FindBugs is 3.0.1.

System Requirements
FindBugs requires JRE (or JDK) 1.7.0 or later to run.

Is FindBugs platform Independent?
Yes, it can run on Windows, Linux MacOS X platforms.

Install FindBugs
Download FindBugs executable from below location.

Extract the downloaded zip file.

The extracted zip contains below structure.


Set the 'FINDBUGS_HOME' property to the installed directory location of FindBug. In my case, I extracted the downloaded zip file to below location.

C:\Users\krishna\softwares\findbugs\findbugs-3.0.1.

Running FindBugs
If you are running on Linux systems, run below command.
java -jar $FINDBUGS_HOME/lib/findbugs.jar

If you are running on Windows systems, run below command.
java -jar %FINDBUGS_HOME%\lib\findbugs.jar

On you ran above command, it opens user interface like below.

I set the value of FINDBUGS_HOME' to ‘C:\Users\krishna\softwares\findbugs\findbugs-3.0.1’.

Running the Analysis using FindBugs GUI
Go to File -> New Project.

It opens below kind of window.
Give the project name as ‘My_Findbugs_demo’, click on the Add button to add jar files to analyze. Add the sources using the third pane of the window.

Click on the button ‘Analyze’. FindBugs starts analyzing process.
When the analysis completes, you will see a screen like the following.

Saving and Opening the results
You may use the File → Save as... menu option to save your work. To save your work, including the jar file lists you specified and all bug results, choose "FindBugs analysis results (.xml)" from the drop-down list in the "Save as..." dialog. There are also options for saving just the jar file lists ("FindBugs project file (.fbp)") or just the results ("FindBugs analysis file (.fba)"). A saved file may be loaded with the File → Open... menu option.

How to install FindBugs in Eclipse?
Open Eclipse.

Help -> Install New Software.
Work with the below url.


Once the installation is done, restart the Eclipse.

Configure FireBug in Eclipse
Window->Preferences->Java->FindBugs

How to find the bugs using FindBugs in Eclipse
We need to create and build a java project to find bugs using FindBugs. Add some classes to the java project.

Now, Build the project using Project->Build Project.

Now Right click on the project -> Find Bugs -> Find Bugs.


Now you can see all the bugs in bug explorer. Window->Show View->Other->FindBugs->Bug Explorer.

You may like



Hamcrest: greaterThanOrEqualTo: check whether given object is greater than or equal to this value

By using ‘greaterThanOrEqualTo’ method, you can create a matcher of Comparable object that matches when the examined object is greater than or equal to the specified value.

Ex
assertThat("2 is >= 1", 2, greaterThanOrEqualTo(1));
assertThat("2 is >= 2", 2, greaterThanOrEqualTo(2));

Find the below working application.

TestApp.java
package com.sample.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  assertThat("2 is >= 1", 2, greaterThanOrEqualTo(1));
  assertThat("2 is >= 2", 2, greaterThanOrEqualTo(2));
 }
}

As you see the signature of greaterThanOrEqualTo method, you can call this method on any Comparable instances.

public static <T extends java.lang.Comparable<T>> org.hamcrest.Matcher<T> greaterThanOrEqualTo(T value)

Let me try to compare whether one employee greater than or equal to other based on their experience in the organization.

public class Employee implements Comparable<Employee> {
         ....
         ....
        
         public int compareTo(Employee emp) {
                  if (emp == null)
                           return 1;

                  return this.experience.compareTo(emp.experience);
         }

}

Since Employee class is implementing Comparable interface, we can use greaterThanOrEqualTo matcher to compare two employee objects.

Ex
assertThat("emp2 is >= emp1", emp2, greaterThanOrEqualTo(emp1));
assertThat("emp2 is >= emp3", emp2, greaterThanOrEqualTo(emp3));

Employee.java

package com.sample.model;

public class Employee implements Comparable<Employee> {
 private int id;
 private String name;
 private Double experience;

 public Employee(int id, String name, Double experience) {
  this.id = id;
  this.name = name;
  this.experience = experience;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public double getExperience() {
  return experience;
 }

 public void setExperience(double experience) {
  this.experience = experience;
 }

 public int compareTo(Employee emp) {
  if (emp == null)
   return 1;

  return this.experience.compareTo(emp.experience);
 }

}


TestApp.java

package com.sample.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;

import org.junit.Test;

import com.sample.model.Employee;

public class TestApp {

 @Test
 public void testmethod() {
  Employee emp1 = new Employee(1, "Krishna", 5.6);
  Employee emp2 = new Employee(2, "Chamu", 6.1);
  Employee emp3 = new Employee(3, "Gopi", 5.6);

  assertThat("emp2 is >= emp1", emp2, greaterThanOrEqualTo(emp1));
  assertThat("emp2 is >= emp3", emp2, greaterThanOrEqualTo(emp3));
 }
}





Previous                                                 Next                                                 Home

Monday, 12 March 2018

Hamcrest: greaterThan: check whether given object is greater than this value

By using ‘greaterThan’ method, you can create a matcher of Comparable object that matches when the examined object is greater than the specified value.

Ex
assertThat("2 greater than 1", 2, greaterThan(1));

TestApp.java
package com.sample.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  assertThat("2 greater than 1", 2, greaterThan(1));
 }
}

As you see the signature of greaterThan method, you can call this method on any Comparable instances.

public static <T extends java.lang.Comparable<T>> org.hamcrest.Matcher<T> greaterThan(T value)

Let us try to compare whether two employees greater than or not based on their experience in the organization.

public class Employee implements Comparable<Employee> {
         ....
         ....
        
         public int compareTo(Employee emp) {
                  if (emp == null)
                           return 1;

                  return this.experience.compareTo(emp.experience);
         }

}

Since Employee class is implementing Comparable interface, we can use greaterThan matcher to compare two employee objects.

Employee emp1 = new Employee(1, "Krishna", 5000.56);
Employee emp2 = new Employee(2, "Chamu", 7090.57);

assertThat("emp2 must > emp1", emp2, greaterThan(emp1));

Find the below working application.

Employee.java
package com.sample.model;

public class Employee implements Comparable<Employee> {
 private int id;
 private String name;
 private Double experience;

 public Employee(int id, String name, Double experience) {
  this.id = id;
  this.name = name;
  this.experience = experience;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public double getExperience() {
  return experience;
 }

 public void setExperience(double experience) {
  this.experience = experience;
 }

 public int compareTo(Employee emp) {
  if (emp == null)
   return 1;

  return this.experience.compareTo(emp.experience);
 }

}


TestApp.java
package com.sample.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;

import org.junit.Test;

import com.sample.model.Employee;

public class TestApp {

 @Test
 public void testmethod() {
  Employee emp1 = new Employee(1, "Krishna", 5000.56);
  Employee emp2 = new Employee(2, "Chamu", 7090.57);

  assertThat("emp2 must > emp1", emp2, greaterThan(emp1));
 }
}






Previous                                                 Next                                                 Home

Hamcrest: Matchers to compare objects

Hamcrest provides below matchers to compare objects.






Previous                                                 Next                                                 Home

Saturday, 10 March 2018

Hamcrest: emptyArray: match empty array

By using ‘emptyArray’ method, you can create a matcher for arrays that matches when the length of the array is zero.

Ex
String arr[] = {};
assertThat("arr size should be equal to 0", arr, emptyArray());

TestApp.java
package com.sample.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.emptyArray;

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  String arr[] = {};
  assertThat("arr size should be equal to 0", arr, emptyArray());
 }
}




Previous                                                 Next                                                 Home

Cross-origin resource sharing (CORS) example using servlets

CORS stands for Cross Origin Resource Sharing. By using CORS, web application from one domain can access the resources from the application that is deployed in another domain.

Below step-by-step procedure explains how CORS works in real time?
we should handle CORS. When the application 'APP1' (Assume APP1 is deployed on domain D1) from browser 'B1' wants to access the resource 'R2' of the application 'APP2' (Assume 'APP2' is deployed on domain D2). 

Below step-by-step procedure explains, how can we build a CORS application using servlets.

Step 1: Browser 'B1' send the OPTIONS request to the application 'APP2' with an ‘Origin’ HTTP header. The ‘Origin’ header contains the domain of the application ‘APP1’.

When a page from http://www.sample.com attempts to access a user's data in http://www.usersTree.com, the following request header would be sent to http://www.usersTree.com:



Step 2: Application 'APP2' receives the request and either approve/reject the request.

Step 3: Upon successful approval from APP2, browser 'B1' fires the actual request and access the resource.

You should be known about below HTTP headers while working with CORS.

Request headers
a. Origin: Origin header specifies the host, where the fetch originates from.

Syntax
Origin: ""
Origin: <scheme> "://" <hostname> [ ":" <port> ]

Example

b. Access-Control-Request-Method
It tells about the HTTP method going to be used when the actual request is made.

Syntax
Access-Control-Request-Method: <method>

Example
Access-Control-Request-Method: POST

c. Access-Control-Request-Headers
It tells which HTTP headers will be used when the actual request is made.

Syntax
Access-Control-Request-Headers: <header-name>, <header-name>, ...

Example
Access-Control-Request-Headers: Content-Type, Authorization

Response headers
a. Access-Control-Allow-Origin
It specify the origin that are allowed to access your resource.

Syntax
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: <origin>

Example
Access-Control-Allow-Origin: https://self-learning-java-tutorial.blogspot.com

How can I allow my resource to be accessed by all origins?
By setting the value of the header 'Access-Control-Allow-Origin' to *, you can allow the resource to be shared by all origins.
Access-Control-Allow-Origin: *

b. Access-Control-Allow-Credentials
By default, CORS does not include cookies on cross-origin requests. When server responds by setting the header 'Access-Control-Allow-Credentials' to true, means that the server allows cookies (or other user credentials) to be included on cross-origin requests.
Syntax
Access-Control-Allow-Credentials: <true/false>

Example
Access-Control-Allow-Credentials: true

c. Access-Control-Expose-Headers
It specifies the headers that can be exposed as part of the response by listing their names.

Below headers are exposed by default.
Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma

Syntax
Access-Control-Expose-Headers: <header-name>, <header-name>, ...

Example
Access-Control-Expose-Headers: Content-Length, Host, Keep-Alive

d. Access-Control-Max-Age
This header specifies, how long the results of the request are cached.

Syntax
Access-Control-Max-Age: <seconds>

Example
Access-Control-Max-Age: 300

e. Access-Control-Allow-Methods
It specifies the methods that are allowed while accessing the resource.

Syntax
Access-Control-Allow-Methods: <method>, <method>, ...

Example
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS


f. Access-Control-Allow-Headers
It specifies the headers that can be used in actual request.

Syntax
Access-Control-Allow-Headers: <header-name>, <header-name>, ...

Example
Access-Control-Allow-Headers: Age, Content-Type
  
Now, let’s build a simple application.

As you see above diagram, I am going to build two applications
a.   APP1
b.   APP2

APP1 requests welcome message service of APP2. APP2 sends the response, if the request comes from the domain localhost:8080.

Develop Application APP1
Create a new dynamic web project in Eclipse.

Create new file ‘index.jso’ with below content.


index.jsp

<!DOCTYPE html>
<html>
<head>
<script
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
 $(document).ready(function() {
  $("button").click(function() {
   $("#corsResponse").load("http://localhost:9090/APP2/welcomeMessage");
  });
 });
</script>
</head>
<body>
 <h2>CORS Demo Application</h2>
 <div id="corsResponse"></div>
 <br />
 <button>Get Welcome Message</button>
</body>
</html>

Develop application APP2
Create new dynamic web project APP2 in Eclipse.

Create new package 'com.app2.sample' and define the servelt 'WelcomeMessage' like below.


WelcomeMessage.java

package com.app2.sample;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/welcomeMessage")
public class WelcomeMessage extends HttpServlet {
 private static final long serialVersionUID = 1L;

 public WelcomeMessage() {
  super();
 }

 protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  handleCORSHeadersOptions(request, response);
  PrintWriter writer = response.getWriter();
  writer.write("Hello, Very Good Morning");
 }

 protected void doOptions(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  handleCORSHeadersOptions(request, response);
 }

 private void handleCORSHeadersOptions(HttpServletRequest request, HttpServletResponse response) {
  String originHeader = request.getHeader("Origin");

  System.out.println("Origin header is coming as : " + originHeader);

  response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
  response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS");
  response.setHeader("Access-Control-Max-Age", "600");
  response.setHeader("Access-Control-Allow-Credentials", "true");
  response.setStatus(HttpServletResponse.SC_OK);

 }

}

I configured ‘APP1’ to run on port 8080 and ‘APP2’ to run on port 9090.

Run the application ‘APP2’.


Run the application ‘APP1’. You can able to see below kind of image.

Click on the button ‘Get Welcome Message’. You can able to see the welcome message in web page. As you see below image, response headers specific to CORS request are come as part of the response.


Now let’s comment the code in the method 'handleCORSHeadersOptions' of servlet 'WelcomeMessage.java' and rerun the application.
Since the CORS headers are not coming from the server, application will not render the response in web page.

Reference







Previous                                                 Next                                                 Home

Hamcrest: arrayWithSize: Check array length

By using ‘arrayWithSize’ method, you can create a matcher for arrays that matches when the length of the array equals the specified size.

Ex
String arr[] = { "Hello", "How", "are", "you"};
assertThat("arr size should be equal to 4", arr, arrayWithSize(4));

Find the below working application.

TestApp.java
package com.sample.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.arrayWithSize;

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  String arr[] = { "Hello", "How", "are", "you"};
  assertThat("arr size should be equal to 4", arr, arrayWithSize(4));
 }
}




Previous                                                 Next                                                 Home