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);

veh1.speed();
 }

}

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

References

  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.

Implementation

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.

Download

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

Conclusion

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.

References

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

Handle uncaught exceptions in a Spring-Boot REST API – Part VI

Many times, we have seen exception thrown on your web page and all the stack trace of the exception. A non-technical user will not be able to understand most of the time. Also stack trace is not the best option when we can show the same exception error in nice json format with the root cause. In this post, we will show how to handle unhandled exceptions from our previous Spring REST API we built here. This particular feature will show how to handle most HTTP 500 errors which happen because of server side issues. Any errors with request or client side, those are HTTP 400 errors and they have been handled in previous post Error Handling in Spring Boot Rest API.

Problem

What happens when there is a database connection issue OR columns in your REST API are different from specified in database tables? Your API will throw a 500 error and if you don’t have any mechanism, this will display error in an html format which will not give much information to user or developer to resolve the issue.

Solution

JAX-RS provides a way to handle uncaught exceptions. This can be done by my implementing an interface for ExtendedExceptionMapper. Basically this is a contract for a provider that takes java exceptions and maps them to a response object which can be transformed into a JSON. This can be implemented as below:


package com.betterjavacode.benefits.utilities;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.glassfish.jersey.spi.ExtendedExceptionMapper;

@Provider
public class UncaughtExceptionMapper implements ExtendedExceptionMapper<Throwable> {

private static final Logger LOGGER = LogManager.getLogger(UncaughtExceptionMapper.class);

@Override
public Response toResponse(Throwable exception) {
LOGGER.info("Enter >> toResponse ");
LOGGER.debug("Exception Caught: " + exception.getMessage());
LOGGER.info("Exit << toResponse");
return Response.status(Status.BAD_REQUEST)
.entity(exception.getMessage())
.build();
}

@Override
public boolean isMappable(Throwable arg0) {
return !(arg0 instanceof WebApplicationException);
}

}

Basically this implementation shows a class UncaughtExceptionMapper implementing an interface ExtendedExceptionMapper which provides a way to map all exceptions which are not of type WebApplicationException (Most HTTP 400 errors are WebApplicationExceptions). toResponse method will help to log all the exceptions and convert exceptions into a Response object.

Conclusion

In this post, we showed how to map all uncaught exceptions into json format response. The code for this post is available at github repository.

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.

Question

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

Solution

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.

Example:

String str1 = new String(“test”);

String str2 = new String(“test”);

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

str1 == str2 – This will return false.

Comment

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.

Example:

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

Example:

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.

StringBuffer

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

Example:

StringBuffer sb = new StringBuffer();

sb.append(“first string”);

sb.toString();

StringBuilder

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

StringTokenizer

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

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.

Example:

StringWriter sw = new StringWriter();

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

sw.toString();

Conclusion

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.

Pre-requisites

  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();
       userrequest.setId(userid);
       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;
       try
       {
          conn = (HttpComponentsConnection)super.createConnection(uri);
consumer.sign(connection.getHttpPost());
       }
       catch (IOException e | OAuthException e)
       {
          e.printStackTrace();
       }
       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


@Bean

public UserClient getUserClient(Jaxb2Marshaller marshaller)

{

UserClient us = new UserClient();

us.setDefaultUri("https://localhost:8443/benefits/endpoints/users.wsdl");

us.setMarshaller(marshaller);

us.setUnmarshaller(marshaller);

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());

us.setMessageSender(signedMessageSender);

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.

Conclusion

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

References

  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)
{
&nbsp; &nbsp; // 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