Tag Archives: Java

Design Patterns – Singleton Pattern – Part II

In this post, we will discuss the Singleton Design Pattern which is of Creational type design pattern. You can check out 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,  you can create an object using it, but only a single 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 as to avoid the need to instantiate the object.

Implementation of Singleton Design Pattern

In this design pattern, a class will have a private constructor and a static method to provide access to static members 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(). The major advantage of the Singleton design pattern is it allows only one instance of an object.

Conclusion

In conclusion, among all design patterns, we started this series with a Singleton design pattern.

Download

The code for this post is available to download design patterns.

 

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

 

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/

Guidelines to avoid null check statements

If you are tired of seeing NullPointer Exception, you are not alone. In this post, I show some guidelines to avoid null check. Have you ever seen 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 the naivety of developers 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 the caller doesn’t have to add any check statement for a null value. But this is the 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 the 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 the caller of this method has to explicitly think about the 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();

Conclusion

In this post, I showed guidelines to avoid null check. Once you use these strategies, you make your life as a programmer way easier.

References

  1. Avoid null check statements
  2. Optional keyword