Category Archives: Core Java

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

 

 

Avoid common mistakes when handling exceptions

During vulnerability scanning, we figured out there were a lot of exceptions handled through the print statement. That’s not a very efficient way of handling exceptions.

Print statements are still better than not writing anything to handle. That’s known as swallowing an exception. A good approach to handle exceptions is to write some way to log those exceptions or throw those exceptions with stack trace during runtime. In this post, I showed some ways of handling exceptions.

What are the exceptions?

Exceptions are error events. These events happen during the runtime of a program. This generally disrupts the flow of the program.

There are three components to exception handlers – try, catch, and finally.

try – This part of exception handling contains code that will be executed during every flow.

catch – If code in try part throws a runtime exception, that will be caught in catch part.

finally – This contains the code you want to execute after trying part of the execution is done. This ensures that finally block is executed even when unexpected exceptions occur. It is mostly used to clean up resources.

Types of Exceptions 

  • Unchecked Exceptions – Exception types that are direct or indirect subclasses of a class RuntimeException , those are the unchecked exceptions.
  • Checked Exceptions – Exceptions that inherit Exception class are known as checked exceptions. RuntimeException are also extended from Exception , but client code doesn’t have to handle them, while Checked exceptions have to be handled by catch or throws clause.

How to handle Exceptions

What exceptions to use? Checked or Unchecked?

In case the code doesn’t know what to do if an exception is thrown, it should be an unchecked exception. If code using an exception knows what to do to recover from that exception along with logging that information, that should be checked exception.

Preserve encapsulation

Don’t propagate an exception from the data access layer to the business object layer.
Example – SQLException is a RuntimeException. If the data access layer throws this exception in the following manner, the catch block will not do anything but will suppress it.

public void dataAccessCode()
{
    try
    {

    }
    catch (SQLException ex)
    {
        ex.printStacktrace();
     }
}

On the other hand, to preserve encapsulation, the same runtime exception can be converted into another unchecked exception like below

public void dataAccessCode()
{
    try
   {

   }
   catch (SQLException ex)
   {
      throw new RuntimeException(ex);
    }
}

Best practices for Exceptions

1) Use finally block for cleaning the code
2) Do not ignore or suppress an exception
3) Log exceptions once
4) Do not use exceptions for flow control

References

  1. Best Practices for Exceptions
  2. Checked Vs Unchecked Exceptions