RSS

Category Archives: java

java programming related stuff

SSL configuration on spring boot application with self signed certificate


Let’s start with What?

SSL – (Secure Sockets Layer) is the standard security technology for establishing an encrypted link between a web server and a browser. This link ensures that all data passed between the web server and browsers remain private and integral

Self signed certificate – is an identity certificate that is signed by the same entity whose identity it certifies

Keystore and Truststore – is used to store SSL certificates in Java but there is subtle difference between them. truststore is used to store public certificates while keystore is used to store private certificates of client or server

Let’s pretend you need to build simple application with spring boot(with fat jar deployment) and you need to expose the application with encryption(over https). In oder to do that you have to configure the spring boot application over https by adding the key-store which holds the certificates. So when its comes to get the certificate you have to choices either self signed or signed by one of the public certificate authorities(CAs)

Now the question is why we need to go for the self signed certificate rather public CA signed certificate. The main reason that people do self-signed certificates because it doesn’t add any cost it is free, But if the site is public facing it would be better to go for the public CA signed certificate rather the self signed. So if you have public CA signed certificate then client browser do verify the certificate without any problem because the browser by default identifies the public CAs otherwise it will show as follows which is not trusted site unless you import the certificate to the browser trust store.

screen-shot-2017-01-28-at-10-10-56-am

The good thing is you will get the encryption over https no matter which certificate you use.

Best scenario that I’m thinking is to create a self-signed certificate when you are in DEV and TEST environments but when you need to expose that to PROD which will be exposing to public use the public CA signed certificate. But if it is internal facing then you can still use the self-signed certificate once you have registered the certificate on clients browser trust stores.

How to create the self signed certificate with JAVA key-tool.

1. Create Java Key Store with certificate

keytool -genkey -keyalg RSA -alias selfsigned -keystore ${DEST_PATH}/keystore.jks -storepass ${PASS_WORD} -validity 360 -keysize 2048

screen-shot-2017-01-28-at-10-54-29-am

2. List out the details of the given keystore 

keytool -v -list -keystore ${PATH_TO_KEYSTORE}/keystore.jks

Screen Shot 2017-01-28 at 11.03.51 AM.png

3. Export self-signed certificate if you want to distribute to the clients.

keytool -exportcert -rfc -alias selfsigned -keystore ${DEST_PATH}/keystore.jks -file ${DEST_PATH}/selfsigned.crt

Screen Shot 2017-01-28 at 10.59.21 AM.png

4. Verify the certificate

keytool -printcert -file ${PATH_TO_CERTIFCATE}/selfsigned.crt

Screen Shot 2017-01-28 at 11.12.26 AM.png

So now need to expose your .jks file to spring boot application and configure that to be exposed as https. Fist of all place your keystore.jks file on the class path and then set the following properties in application-*.properties file.

server.port=8443
server.ssl.key-alias=selfsigned
server.ssl.key-password=test123
server.ssl.key-store=classpath:keystore.jks
server.ssl.key-store-provider=SUN
server.ssl.key-store-type=JKS

 

 
4 Comments

Posted by on January 28, 2017 in java, Other, spring

 

Tags: , , , , ,

How to make the java runtime to trust the certificate present by the host


URL -https://my-site.com/test

Let’s start with simple example. If you invoke above URL through your simple java application you will simply get the SSLHandshakeException because it is exposed as https endpoint and the java runtime is not going to trust the certificate that present through the URL call. So before you invoke the service you have to present the certificate to your java runtime to trust the certificate. Then when ever you call the URL it will trust the certificate. You can do this in two different ways as follows.

  1. Download and import the certificate to your java runtime certificate store.
  2. Write the code in your program to trust the certificate provided by the host.

1. Download and import the certificate to your java runtime certificate store.

First of all you have to download the certificate from the host. In order to do that you can simply go to the URL through the browser and then download the certificate to your local machine as .cer file.

In Chrome browser you can simply go to the certificate as follows and drag and drop to the local folder. I choose the https://google.com as a example.

1

2

So once you have downloaded the certificate  you should be able to use the keytool to import the certificate.

keytool -import -alias google -keystore ${PATH_TO_JDK}/jre/lib/security/cacerts -file ${PATH_TO_CERT_FILE}

You have to provide the keystore password as “changeit” unless you have customized it.

ex/

keytool -import -alias google -keystore /Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home/jre/lib/security/cacerts -file /Users/dmalalan/Documents/www.google.com.cer

3

screen-shot-2017-01-14-at-11-48-44-am

2. Write the code in your program to trust the certificate provided by the host

You need to use the following code sample before you invoke the URL. This is just allow the runtime to trust all the certificates presented by the host but you need to be careful with this approach because host can present the bogus certificates.

screen-shot-2017-01-14-at-11-55-53-am

References : sample code & sample instructions

 
Leave a comment

Posted by on January 14, 2017 in java, Other, web

 

Tags: , , ,

RMI vs JMS Clarification


Most of the developers and system designers may know what is RMI and what is JMS but when they come to develop or design the real world application then they are in trouble with which one to choose. So I thought its better to publish some thoughts on this.

Lets start with the regular descriptions.

RMI – Remote Method Invocation

rmi-5

  1. Synchronous communication – Request initiator wait for the response. In order to archive this RMI service need to be up at the time of communication.
  2. Tightly coupled – Requesting system is couple to the declared interface in RMI service.
  3. Unreliable communication – If something happen in-between the communication you will loose the request and you have to handle those in application level.

Advantages :
Easy to start by writing the simple interface and the implementation.

Disadvantages :
Can use only the java supported platforms.
Cannot use the code out of the scope of java.
Security issues need to be monitored more closely.

Using RMI :
If you have process with heavy computation and need more computation power to improve the performance then you can go with RMI because it will give you the computation power on simple method call.

JMS – Java Message Service

Topic – Publish and subscribe model

publish_subscribe
Queue – Load balancing model

qs-multiple-consumers

  1.  Asynchronous communication – Request initiator is not going to wait for the response and it just send the message out then close the connection. No need to have backing service up at the time of communication.
  2. Loosely coupled – It is not tight to the service as RMI. You can use any kind of data format to communicate via message QUEUEs and TOPICs. ex/ XML, JSON
  3. Reliable communication – This is not like RMI because this communication has message broker in-between the systems and message broker has capability of error handling and the persistent of the messages and handover them to the responsible party.

Advantages :
Due to asynchronous messaging, All the modules don’t need to be up for the application to function as a whole.

Disadvantages :
Extra overhead on setup and maintain the message broker

Using JMS :
If you have any process which will be getting heavy request load and that can be run asynchronously then go for JMS Queue implementation and run them separately and communicate via the queue. The next point is if you have a process that need to send the data to many downstream applications then go for JMS Topic implementation.

By the way remember this, There is no such a thing as bad technology only bad choice.

 
Leave a comment

Posted by on April 19, 2016 in java, jms, RMI

 

Tags: , , , , ,

Apache-Camel with Java (Integration)

Apache-Camel with Java (Integration)

Apache camel is very useful routing implementation. If you involve with some integration then you will realize how it is solving your problems. When technology evolves Integration will come to the picture as follows.

A company has a software, which runs in old technology. The company wants to go for another tool, which is going to work on latest platforms and technology. But still the company need to get integrated with the old system because new tool depends on the company data, which is in old system. In this case we need to come up with good solution that can be bridge to the communication. In the industry we used Message Queues to make realtime communication so if it is realtime we can use the message queue in between the two systems.

Above sample is really simple scenario but think about if you have number of systems in downstream to communicate, then you will need proper routing mechanism otherwise you will end up with multiple endpoints, which is doing the same thing (duplicate work). Apache Camel is open source tool for routing data with JAVA application.

Apache Camel

I have created simple adapter with apache camel routes. It explains how to use camel routes in implementation level. This is a maven project produce the war file, which you can deploy on apache tomcat and subscribe to the queue. ( I hope you have understanding of use Spring Boot and Spring Profile) This sample doesn’t contain JMS client to publish messages so I’m going to use the ActiveMQ console.

You can clone the whole project in following location. https://github.com/malalanayake/camel-sample

In code level you need to create the camel route and camel message processor as you wish. See the following rout configuration and sample message processor implementation.

Follow the instruction to deploy and run the adapter.

Start Apache ActiveMQ and create the queue as “sample_queue” then change the application-dev.properties in resource folder. I used spring profile for switch the context so you need to update the default profile as follows in application.properties

Now build the WAR file and deploy the WAR on Apache Tomcat. Then you will see the WAR adapter is going to subscribe to the sample_queue

activemq

Now go to operation and do “Send To“. Now your adapter is going to consume the given message. See the logs in tomcat console.

send

 

 

after_sent

 

console

 

after_consume

The routing mechanism and routing patterns might vary with the problem domain. However the implementation perspective is similar. For example subscribe to message queue and then route the message to endpoints. I hope you got some idea how to use the camel routes.

Enjoy the integration.

 
3 Comments

Posted by on October 11, 2015 in integration, java, spring

 

Tags: , , , ,

Understanding Java pass by value


I think most of the people they are confused with this concept because it is appearing in different angles. First thing I have to say that Java is pass by Value not pass by reference. I’ll show the example to clear the concept.

First of all I’ll show the sample code, then you can see the confused point that you will drive to think that java is pass by reference. you can checkout the full source here.

package sample.passby.value;

/**
 * Point class
 * 
 * @author malalanayake
 *
 */
public class Point {
	private int x;
	private int y;

	public Point(int x, int y) {
		this.x = x;
		this.y = y;
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

}
package sample.passby.value;

/**
 * Demonstration of Java pass by value
 * 
 */
public class App {
	public static void main(String[] args) {
		int xOrginal = 0, yOriginal = 0;
		System.out.println("Original Coordinates:" + xOrginal + "," + yOriginal);
		App.getNextCoordinates(xOrginal, yOriginal);
		System.out.println("After modification of Coordinates:" + xOrginal
				+ "," + yOriginal);

		Point pOriginal = new Point(0, 0);
		System.out.println("Original Point:" + pOriginal.getX() + ","
				+ pOriginal.getY());
		App.getNextCoordinates(pOriginal);
		System.out.println("After modification of Point:" + pOriginal.getX()
				+ "," + pOriginal.getY());

	}

	public static void getNextCoordinates(int x, int y) {
		x = 12;
		y = 15;
	}

	public static void getNextCoordinates(Point point) {
		point.setX(12);
		point.setY(15);
	}
}

Output:
Original Coordinates:0,0
After modification of Coordinates:0,0
Original Point:0,0
After modification of Point:12,15

So you can see in the above example if I pass the primitives then it is not going to change the values. But if I pass the object type then if i change something on that it will reflect. The understanding point is Java every time pass by value and if it is primitive then it is just pass the value to the given argument and nothing will reflect. See the following image for understanding.
PassByValue (1)

But if we pass the Object type then java pass the “reference by value”. This is the tricky point that we need to understand.
PassByValue (2)

So you can see if we pass some Object type to some function actually its going to pass the pointer to that Object. That means if we change some thing on that it will be reflect on that. But be aware about this, You cannot change the pointer which is not in the scope. As an example if you do following coding in getNextCoordinates(Point point) method it will not reflecting anything on the original object because it is going to change the pointer of the object which is under that scope not the original object that passed to the function.

public static void getNextCoordinates(Point point) {
                point = new Point(12,15);
}
 
Leave a comment

Posted by on December 8, 2014 in java

 

Tags: , ,

Comparator and Comparable interfaces in Java


c4c3

Comparator and Comparable interfaces are heavily used in the Java development to manage the sorting of the collections. This approach will achieve the software engineering goals such as extensibility, reusability, modularity etc. In this post I like to explain this mechanism of how to use comparator and comparable interfaces. First thing is we are going to use the Collections API for sorting which is provided by Java. So we have to expose sorting comparison logic without exposing the internal structure of our custom implementation.Here you can download the source.

Lets look at how to use Comparable interface.

As an example I have Employee class which is created by me and need to sort the collection of employees according to the employee age.

  • First we need to implement the Comparable interface in Employee class and override the compareTo method
  • Then we can pass the employee collection to the Collections.sort() API to do the sorting.
  • Underneath what will happen Collections.sort() method will access the compareTo implementation and get the decision according to the return value.

See the code sample below to get clear understanding.

package sample.common;

/**
 * Employee Class
 *
 * @author malalanayake
 *
 */
public class Employee implements Comparable<Employee> {
	private int id;
	private String name;
	private int age;
	private int salary;

	public Employee(int id, String name, int age, int salary) {
		this.id = id;
		this.name = name;
		this.age = age;
		this.salary = salary;
	}

	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 int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public int getSalary() {
		return salary;
	}

	public void setSalary(int salary) {
		this.salary = salary;
	}

	public int compareTo(Employee o) {
		if (o.getAge() == this.age) {
			return 0;
		} else if (o.getAge() > this.age) {
			return -1;
		} else {
			return 1;
		}
	}

	@Override
	public String toString() {
		return "[Employee ID:" + this.getId() + " Name:" + this.getName()
				+ " Age:" + this.getAge() + " Salary:" + this.getSalary() + "]";
	}

}
package sample.app;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import comparator.sample.app.SalaryComparator;
import sample.common.Employee;

/**
 * Application Class
 *
 * @author malalanayake
 *
 */
public class App {
	public static void main(String[] args) {
		List<Employee> employees = new ArrayList<Employee>();

		Employee emp_dinuka = new Employee(101, "Dinuka", 27, 95000);
		employees.add(emp_dinuka);

		Employee emp_malalanayake = new Employee(100, "Malalanayake", 27, 85000);
		employees.add(emp_malalanayake);

		Employee emp_Thanuja = new Employee(305, "Thanuja", 23, 150000);
		employees.add(emp_Thanuja);

		Employee emp_Damith = new Employee(204, "Damith", 20, 75000);
		employees.add(emp_Damith);

		System.out.println("=======Before Sorting=====");
		for (Employee emp : employees) {
			System.out.println(emp.toString());
		}

		Collections.sort(employees);
		System.out.println("=======After Sorting=====");
		for (Employee emp : employees) {
			System.out.println(emp.toString());
		}
	}
}

You can see in the above case we can have only one sorting logic over the employee class. Lets think about sometimes if I need to sort the Employee by their salaries and sometimes I need to sort by their age. Then you can see we don’t have space to put that logic in my Employee class because already I have method implementation according to the age. In this kind of situation Comparator comes to the picture to solve the problem.

Lets look at how to use Comparator

  • So first you have to have comparator implementation class. In above case I have created SalaryComparator class which is provide the salary comparison.
  • Then you can pass the employee collection to overloaded method in collections api to sort the given collection according to the given comparator.
package comparator.sample.app;

import java.util.Comparator;

import sample.common.Employee;

/**
 * Salary Comparator
 *
 * @author malalanayake
 *
 */
public class SalaryComparator implements Comparator<Employee> {

	public int compare(Employee o1, Employee o2) {
		if (o1.getSalary() > o2.getSalary()) {
			return 1;
		}

		if (o1.getSalary() < o2.getSalary()) {
			return -1;
		}
		return 0;
	}

}
package sample.app;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import comparator.sample.app.SalaryComparator;
import sample.common.Employee;

/**
 * Application Class
 *
 * @author malalanayake
 *
 */
public class App {
	public static void main(String[] args) {
		List<Employee> employees = new ArrayList<Employee>();

		Employee emp_dinuka = new Employee(101, "Dinuka", 27, 95000);
		employees.add(emp_dinuka);

		Employee emp_malalanayake = new Employee(100, "Malalanayake", 27, 85000);
		employees.add(emp_malalanayake);

		Employee emp_Thanuja = new Employee(305, "Thanuja", 23, 150000);
		employees.add(emp_Thanuja);

		Employee emp_Damith = new Employee(204, "Damith", 20, 75000);
		employees.add(emp_Damith);

		SalaryComparator comparator = new SalaryComparator();
		Collections.sort(employees, comparator);
		System.out.println("=======After Sorting By Salary=====");
		for (Employee emp : employees) {
			System.out.println(emp.toString());
		}
	}
}

So If you have multiple sorting logics then you have to go for the Comparator because then only you can have multiple logics. Otherwise you can encapsulate the logic inside your custom implementation class by using the Comparable interface. I hope you got the idea of how to use the comparator and comparable interfaces.

 
Leave a comment

Posted by on December 5, 2014 in java, Other

 

Tags: , , , ,

JSP, Servlet, Scope variables and Init Parameters


If you are getting involved in Java EE development you have to have good knowledge about the JSP and Servlets. Servlets are server side components that provide a powerful mechanism for developing server side programs. JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pages based on HTML, XML, or other document types.

First look at how request and response handle in servlet container. Servlet container create one instance from each servlet but its going to serve for multiple threads. See the following diagram. You can see HTTP Request comes to the container and it will create the HTTPServletRequest, HTTPServletResponse objects. Finally put those two objects in new thread and let the thread to access the instance of specified servlet.

Servlet Conatiner

According to the above process you can see we have to be careful of the thread safety of instance variable in servlet. Because each and every thread is gong to access the single Servlet instance. If you have some instance variable in the servlet which is going to modify with in the thread you have to make it thread safe.

Look at the Servlet life cycle

init() – this method is going to run only one time
service() – this method is going to run each time the request comes to the servlet. And it will identify either doGet or doPost to execute according to the request.

Servlet Life Cycle

JSP life cycle is same as Servlet, only additional thing is its going to translate to the servlet. Ultimately its acts as Servlet. JSP you can override two methods which is jspInit() and jspDestroy(). But you cannot override the jspService() method.

Lets talk about Scope variables.

1. Application Context  – In other words we can say this is servletContext. You can use servletContext to store the global data which is going to share through out the application. This is not thread safe. You can easily access this context as follows.

request.getServletContext();
request.getServletContext().setAttribute("attribute_name","value");

2. Session Context – Session management is handling by the servlet container and you can store the user specific data on session. This object is not thread safe.

request.getSession(); //going to create the session if session is not exist.
request.getSession(false); // Not going to create the session.

3. Request Attributes – You can use this scope to carry the data in server side from one resource to another. As an example while you are doing the request forwarding. This is thread safe because one request is handle by one thread.

request.setAttribute("attribute_name","value");
request.getAttribute("attribute_name"); // return the Object you have to cast it

Config Parameters

We have two different types of init parameters. One is available for the whole application and the other one is only for specific servlet. These parameters are deployment time constants. That means once the application is deployed you cannot change it. These parameters are going to declare in web.xml

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/config/springmvc-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <context-param>
  	<param-name>ApplicationName</param-name>
  	<param-value>ApplicationName</param-value>
  </context-param>
</web-app>

1. Global init parameter 

getServletContext().getInitParameter("ApplicationName");

2. Specified int parameter

getServletConfig().getInitParameter("contextConfigLocation");
 
Leave a comment

Posted by on October 10, 2014 in java, web

 

Tags: , , , ,

 
%d bloggers like this: