Monthly Archives: May 2017

Design Patterns in Java – Introduction

In the next few posts, I will write a series of posts to discuss design patterns in Java. I will give an introduction to design patterns. What design patterns are? How to use them? I will describe design patterns in Java.

What are design patterns?

Firstly, design patterns are programming and design strategies. These are independent of programming languages. Design patterns are mostly used to build a solution for common object-oriented programming problems. Secondly, one of the major benefits of design patterns is that most code is reusable and easily maintainable. However, a design pattern is a repeatable solution to a commonly occurring problem in software design.

Design patterns speed up the process of development. Nevertheless, the design patterns differ in their complexity. Hence, using them takes some practice. Overusing design patterns can complicate the design and your system. Especially, design patterns should simplify the design and not complicate it.

Example of design pattern in the real world?

Therefore, to understand what exactly design patterns are, let’s consider a real-life example. Suppose we have an animal class. The subclasses for the animal class will be Elephant, Dog, Cat. I show these classes below.

Likewise, 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

Consequently, based on their purpose, design patterns are divided into three types of patterns creational, structural, and behavioral. Moreover, each of these design patterns has sub-types.

Creational Design Pattern

  • Singleton Design Pattern
  • Factory Pattern
  • Absolute factory Pattern
  • Builder Pattern
  • Prototype Pattern

Structural Design Pattern

  • Adapter Pattern
  • Composite Pattern
  • Proxy Pattern
  • Flyweight Pattern
  • Facade Pattern
  • Bridge Pattern
  • Decorator Pattern

Behavioral Design Pattern

  • Template Method Pattern
  • Mediator Pattern
  • Chain of responsibility Pattern
  • Observer Pattern
  • Strategy Pattern
  • Command Pattern
  • State Pattern
  • Visitor Pattern
  • Interpreter Pattern
  • Iterator Pattern
  • Memento Pattern

So, 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 conclusion, we discussed an introduction to design patterns. Besides, there is some criticism about design patterns that I have not talked about.  Furthermore, I will build actual design patterns to show how design patterns work. If you enjoyed this post, subscribe to my blog here.

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 uncaught 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 of uncaught exceptions

Firstly, 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. Showing such stack trace on web page to end user is a bad example from programming perspective.

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 conclusion, we showed how to map all unhandled exceptions into JSON format for a nice 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 maybe the most argued topic of strings in programming languages. This post will cover how to use strings in Java.

Question

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

Solution

The 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 the 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 checks happen 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 is not thread-safe, but they offer better performance than StringBuffer. You can say StringBuffer is 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. If you enjoyed this post, subscribe to my blog. If you want to read more about Strings, you can read here.

 

How to consume OAuth secured SOAP Webservice

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

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 a 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 it?

Firstly, 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;
   }
}

We are using a WebServiceTemplate to marshal a request and send it to a SOAP endpoint. SoapActionCallback is a callback which allows changing the marshalled message and sends to an endpoint and then it will retrieve a response.

Secondly, 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)
     {
      throw new RuntimeException("I/O Error", e);
     }
    return conn;
  }
}

Now we build our bean for the client to use this message sender. Then we will assign a 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 with OAuth 1.0a. I am sure we can add a similar solution if the service producer secures it with OAuth 2.0, but that will be another post.

Conclusion

In conclusion, I showed how to send OAuth signed SOAP message to SOAP webservice.

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/