Tag Archives: Java

Design Patterns – Factory Pattern – Part III

In this article, we will see how to use a factory pattern. Factory pattern is a creational type of design pattern, in short it provides a way to create objects. Another important point to note about this design pattern is that client who uses factory pattern is not aware of the implementation of factory pattern.

Even in our previous post Spring Boot REST CRUD API, we have used factory pattern to implement managers at service level. As part of this post, we will show another example of factory pattern. Factory pattern mainly used in cases when client just needs a class/object that can handle the job of doing the work at runtime without knowing any details of how it was implemented.

To show how to implement factory pattern, let’s assume we have different types of vehicles and we want to know what their maximum speed is.

Create an interface –

Our interface of vehicle will have a method to return a max speed of vehicle.

package com.betterjavacode.designpatterns.factoryexample;

public interface Vehicle {

void speed();


Now, we will have different classes (car, truck,bus,motorcycle) that will implement this interface to return their maximum speed. For article purposes, we will only be showing one class.

package com.betterjavacode.designpatterns.factoryexample;

public class Car implements Vehicle {

 public void speed() 

   System.out.println("Max Speed of this car is 100 mph");


To get an instance of an object, we will create a factory class that will return me appropriate instance of vehicle object based on what vehicle type I pass.

package com.betterjavacode.designpatterns.factoryexample;

public class VehicleFactory {

public Vehicle getVehicle(String vehicleType)
   if (vehicleType == null) 
      return null;
   if (vehicleType.equalsIgnoreCase("car")) {
     return new Car();
   if (vehicleType.equalsIgnoreCase("bus")) {
     return new Bus();
   if (vehicleType.equalsIgnoreCase("motorcycle")) 
     return new Motorcycle();
   if ( vehicleType.equalsIgnoreCase("truck")) 
     return new Truck();
    return null;


A factory pattern demo class will get any of object of type vehicle at runtime.

package com.betterjavacode.designpatterns;

import com.betterjavacode.designpatterns.factoryexample.Vehicle;
import com.betterjavacode.designpatterns.factoryexample.VehicleFactory;

public class FactoryPatternDemo {

public static void getSpeed(String vehicleType) {
 VehicleFactory vehicleFactory = new VehicleFactory();

Vehicle veh1 = vehicleFactory.getVehicle(vehicleType);



In this example, we have shown how to implement a design pattern type factory pattern. The code for this is available design patterns.


  1. Factory Pattern Example
  2. Factory Pattern

Design Patterns – Singleton Pattern – Part II

In this post, we will discuss Singleton Pattern which is of Creational type design pattern. You can checkout the introductory post about design patterns here.

Singleton Design Pattern

Singleton design pattern is the simplest design patterns in software engineering. As Singleton is a creational type of design pattern, it is used to create an object.

In this design pattern, a single class creates an object , but also makes sure that only a single object is created. This class provides a way to access the object, so to avoid the need to instantiate the object.


In this design pattern a class will have a private constructor and a static method to provide access to static member of the class instance. Most of the time singleton pattern is used in logger and configuration classes implementation.

package com.betterjavacode.designpatterns;

public class SingletonDemo {

private static SingletonDemo demo;

private SingletonDemo()



public static SingletonDemo getInstance()

if (demo == null)
demo = new SingletonDemo();

return demo;

public void printSingletonDemo()

System.out.println(" This is a singleton design pattern demo ");


Now any client code who wants to use SingletonDemo class, can do this with SingletonDemo.getInstance(). Major advantage of Singleton design pattern is it allows only one instance of object is created.


Code for this post is available to download design patterns.

Design Patterns in Java – Introduction

In coming next few posts, we will build a series of posts to discuss design patterns in Java. In this introductory post, we will give a brief idea about design patterns.

What are design patterns?

Design patterns are programming strategies independent of programming language to build a solution for common object-oriented programming problems. One of the major benefits of design patterns is that the most code is reusable and easily maintainable.

Example of design pattern in real world?

To understand what exactly design patterns are, let’s consider a real life example. Suppose we have an animal class. All the subclasses for animals like Elephant, Dog, Cat can be built by using methods to make these objects.

An abstract factory is a design pattern, that can be used in this example.

abstract class AbstractAnimalFactory


public Elephant makeElephant() {

return new Elephant();


public Dog makeDog(){

return new Dog();




abstract class Animal{



class Elephant extends Animal{



class Dog extends Animal{




Types of design patterns

Based on their purpose, design patterns are divided into three types of patterns creational, structural and behavioral. Further, each of these design patterns have sub-types.

Creational Design Pattern

  1. Singleton Design Pattern
  2. Factory Pattern
  3. Absolute factory Pattern
  4. Builder Pattern
  5. Prototype Pattern

Structural Design Pattern

  1. Adapter Pattern
  2. Composite Pattern
  3. Proxy Pattern
  4. Flyweight Pattern
  5. Facade Pattern
  6. Bridge Pattern
  7. Decorator Pattern

Behavioral Design Pattern

  1. Template Method Pattern
  2. Mediator Pattern
  3. Chain of responsibility Pattern
  4. Observer Pattern
  5. Strategy Pattern
  6. Command Pattern
  7. State Pattern
  8. Visitor Pattern
  9. Interpreter Pattern
  10. Iterator Pattern
  11. Memento Pattern

In coming posts, we will discuss each design pattern with a production-ready example.

Advantages of design patterns

  1. Reusable in multiple projects
  2. Capture the complete experience of software engineering
  3. Provide clarity to system architecture


In this post, we discussed a simple introduction to design patterns. In coming posts, we will build actual design patterns to show how design patterns work.


  1. Design patterns in Java
  2. Design Patterns Brief Introduction

How to compare Strings in Java and more about Strings

Yes, I will be talking about one of the favorite topics or may be the most argued topic of strings in programming languages. This post will not cover any other programming languages, but Java.


One of the beginner question in Java is how to compare Strings in java?


Short answer is .equals compare the values of two strings and see if they are equal or not. Operator == compare the two string objects and see if they are referring to same memory address.


String str1 = new String(“test”);

String str2 = new String(“test”);

str1.equals(str2) – This will return true.

str1 == str2 – This will return false.


Despite Java supports operator == for strings, it is not used for string comparison often. Object reference check happens rarely. Another anomaly to this is if two strings are null.


String str1 = null;

String str2 = null;

str1 == str2 – this will return true.

str1.equals(str2) – this will throw null pointer exception (NPE).

Java offers another method called compareTo for String comparison. This can be used in following way


String str1 = “test”;

String str2 = “test”;

str1.compareTo(str2) == 0 – This will return true.

More about Strings

We all have seen StringBuffer, StringBuilder, StringWriter, StringTokenizer or just plain String. What are all these different aspects of String and when to use? Isn’t this too much to know when you just want to use a simple String object. This post will cover some information about all these different classes that Java offers.


StringBuffers are thread-safe, they are just synchronized version of StringBuilder. StringBuffer offers some helpful methods like append and reverse.


StringBuffer sb = new StringBuffer();

sb.append(“first string”);



StringBuilder are not thread-safe, but they offer better performance than StringBuffer. You can say StringBuffer are thread-safe version of StringBuilder.


StringTokenizer is completely different from StringBuffer and StringBuilder as it is mainly used for splitting strings into token at a delimiter. StringBuffer and StringBuilder are used to build strings.


StringWriter is a character stream that collects the output in a string buffer. In short, you can say it uses StringBuffer underneath. This is an IO stream, very similar to File IO, but you can still access StringWriter even after stream has been closed.


StringWriter sw = new StringWriter();

sw.write(“this is first string”);



In this article, we showed String comparison and different forms of String building.

How to consume OAuth secured SOAP web service

I faced the issue where I had to consume a SOAP service which was secured by OAuth1.0a. And Spring doesn’t provide any direct solution for consumer OAuth secured SOAP service.

In Producing and Consuming SOAP web service and Consuming SOAP web service over HTTPS, we saw how to consume a SOAP web service. In this post, we will go little beyond this and implement a solution to consume OAuth secured SOAP web service. Securing a web service is general trend and you must secure a web service if you are letting others consume it. This is a secure way to transfer data between producer and consumer without compromising customer data.


  1. Spring web services
  2. OAuth library and knowledge

How to implement?

Below is a code that shows how to send a SOAP request call to a web service if it is not OAuth secured.

public class UserClient extends WebServiceGatewaySupport
    public GetUserResponse getUserById (int userid)
       GetUserRequest userrequest = new GetUserRequest();
       GetUserResponse response = (GetUserResponse)getWebServiceTemplate().marshalSendAndReceive(userrequest, new SoapActionCallback("https://localhost:8443/benefits/endpoints/getUserResponse"));
       return response;

Basically, we are using a WebServiceTemplate to marshal a request and send it to SOAP endpoint. SoapActionCallback  is callback which allows to change the marshalled message before it can be sent to endpoint and a response can be retrieved.

As part of this solution, we will implement a class SignedMessageSender that will sign the request with OAuth consumer key and secret.

public class SignedMessageSender extends HttpComponentsMessageSender
    private final CommonsHttpOAuthConsumer consumer;

    public SignedMessageSender(CommonsHttpOAuthConsumer consumer)
      this.consumer = consumer;

    public WebServiceConnection createConnection(URI uri)
       HttpComponentsConnection conn = null;
          conn = (HttpComponentsConnection)super.createConnection(uri);
       catch (IOException e | OAuthException e)
       return conn;

Now we build our bean for client to use this message sender, we will assign consumer key and consumer secret. This also uses JAXB marshaller. The code for this will look like below


public UserClient getUserClient(Jaxb2Marshaller marshaller)


UserClient us = new UserClient();




String consumerkey = "";

String secretkey = "";

CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(consumerkey,secretkey);

SignedMessageSender signedMessageSender = new SignedMessageSender(consumer);

signedMessageSender.createConnection(new URL("https://localhost:8443/benefits/endpoints/users.wsdl").toURI());


return us;



This shows how we can implement a solution to consume a SOAP web service secured by OAuth 1.0a. I am sure we can add similar solution if the service is secured by OAuth 2.0, but that will be another post.


In this post, we showed how to add OAuth signed SOAP message to SOAP service which would return a response to consumer.


  1. Add Header to SOAP message
  2. SOAP WS-addressing
  3. https://www.avisi.nl/blog/2012/11/22/consuming-oauth-secured-soap-webservices-using-spring-ws-axiom-signpost/


Guidelines to avoid null check statements

Have you ever seen a code like below?

Object obj = anotherobj.getObject();
if(obj != null)
    // do something with obj

Imagine if you have to write such if-statement block for every object or variable you retrieve from different contract objects in your code, it would make the code cumbersome and unreadable. Also it gives an impression of naivety of developer in such cases.

I am writing this post based on a heavy discussion happening on stackoverflow Avoiding Null Statements. I am only using this post as a reference and writing my own guidelines based on my own experience. Answers to that post on stackoverflow are worth to checkout.

Guidelines to avoid checking null statements

  1. If callee keeps a contract of never returning a null, then caller doesn’t have to add any check statement for null value. But this is basic premise a developer should follow when writing methods.
  2. Most of the time, the issue is not method returning null, but the logic implemented in these methods is not accurate. If business logic of a method knows a way to handle errors in cases when it can return the right data, it should return an error instead of returning null.
public String getEmployeeInformation(String empcode) 
   if (empcode == null) 
      // instead of returning null, throw an error
      throw new IllegalArgumentException(" empcode is null "); 

3.  Java 8 offers a new keyword optional 

public Optional<Employee> getEmployeeInfoWithSSN(String ssn)




So if the employee information with particular SSN is not found, then caller of this method has to explicitly think about type system.

4.  Intellij Idea offers Java annotations like @Nullable and @NotNull

5.  Write junit test cases for your classes which check for assertNotNull()

6.  Java 7 offers a utility method for Objects , Objects.requireNonNull();


References –

  1. Avoid null check statements
  2. Optional keyword

Consuming a SOAP webservice over HTTPS

In the previous post, we talked about producing and consuming a SOAP web service here. This post will be a sequel to that post since recently I faced a similar issue during my project. In this post, we will talk about how to consume a SOAP web service over https. Since this will be a small post, we will not be posting any code on github.

Problem –

While consuming a SOAP web service which is behind SSL, if you don’t handle SSL certificates, you will run into following error

sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
 at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
 at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
 at sun.security.validator.Validator.validate(Validator.java:260)
 at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
 at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
 at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
 at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1351)
 at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:156)
 at sun.security.ssl.Handshaker.processLoop(Handshaker.java:925)
 at sun.security.ssl.Handshaker.process_record(Handshaker.java:860)
 at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1043)
 at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1343)
 at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:728)
 at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
 at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:138)
 at SSLPoke.main(SSLPoke.java:31)
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
 at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:145)
 at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:131)
 at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
 at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
 ... 15 more

Solution –

Basically this error is happening if your SOAP web service is on SSL and the client is trying to connect to web service, web service doesn’t recognize the client and throws this error.

To resolve this error, you can download a SSL certificate from the server where you are hosting SOAP web service and import that certificate on your client machine’s keystore. In production environment, you should have a way to access this keystore when a call is made to the web service.

Let’s assume that our webservice from post is on SSL, like https://localhost:8943/benefits/endpoints/users.wsdl. If you access this URL in browser, you will be able to see the SSL certificate. Export this SSL certificate in base 64 format file, example sslcertificate.crt. Import this certificate in

keytool -import -alias sslcertificateofserver -keystore truststore.jks -storepass changeit -file sslcertificate.crt

Now, we will change the configuration class we wrote to configure web service components.

package com.betterjavacode.benefits.views;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;

public class ClientAppConfig
   private Resource getKeyStore()

   private String getKeystorePassword()

   public Jaxb2Marshaller marshaller()
     Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
     return marshaller;

    public UserClient userClient(Jaxb2Marshaller marshaller) {
        // WSDL URL - http://localhost:8080/benefits/endpoints/users.wsdl
        UserClient uc = new UserClient();

        FileInputStream fis = new FileInputStream(getKeyStore());
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(fis, getKeyStorePassword().toCharArray());

        try {
        } catch (IOException e) {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(ks, keyStorePassword.toCharArray());

        FileInputStream fisTS = new FileInputStream(getKeyStore());
        KeyStore ts = KeyStore.getInstance("JKS");
        ts.load(fisTS, trustStorePassword.toCharArray());

        try {
        } catch(IOException e) {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

        HttpsUrlConnectionMessageSender messageSender = new HttpsUrlConnectionMessageSender();

        HostNameVerifier hv = new HostNameVerifier(){
           public boolean verify(    String hostname,    SSLSession session){
                  return true;
        return uc;

This change should fix the error about PKIX path building failed. I will post the code for this article on github in next few days.

Conclusion –

In short, we showed how to consume a SOAP web service over SSL by adding keystore and truststore check during runtime.