Monday 26 December 2016

Unknown facts about Date Format Validation in Java

Have you ever think of validating a date given in string form whether it's a valid date or not?
e.g. :
30-11-2016(dd-MM-yyyy)  --> Valid date
31-11-2016(dd-MM-yyyy)  --> Invalid date, since November has only 30 days

Now you think what is there, it's pretty simple. Now you can think of using any 3rd party utility library (like apache-common-util) to validate this.

But the point here is, how these utility libraries do this validation ? Now the java.text.SimpleDateFormat class in java core API comes to our mind.

Let's see an example how can we validate using this class :
Example - 1

SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy");
Date date = format.parse("31-JAN-2016");
System.out.println(date);

/*O/P---Sun Jan 31 00:00:00 IST 2016 */

Example - 2


SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy");
Date date = format.parse("31-JEN-2016");
System.out.println(date);

/*O/P---Exception in thread "main" java.text.ParseException: Unparseable date: "31-JEN-2016"
    at java.text.DateFormat.parse(DateFormat.java:366)
    at Solution.main(Solution.java:21)    ...
 */

Here we can see the validation is pretty simple and straight forward. But let's see some other use cases and will decide whether the validation is really such straight forward ?

Example - 3

SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy");
Date date = format.parse("32-JAN-2016");
System.out.println(date);

/*O/P--- Mon Feb 01 00:00:00 IST 2016 */

Here you see even the input string is an invalid date but the formatter can parse it and returning the next valid date by incrementing the day. (from 32-JAN to 01-FEB).
Now you are confused that, "how can we validate in a correct way ?".

Here is the secret of SimpleDateFormat:

SimpleDateFormat extends java.text.DateFormat which having this below method
This above method uses the heuristics to interpret the given input. So make sure to disable 
this property by setting as formater.setLenient(false);

Example - 3 modified



Now it validated properly as we want.






Saturday 20 August 2016

Detect Deadlock Programmatically in Your Applicaion

What is a Deadlock ?

It is a condition where two or more threads are blocked forever because they are waiting for each other to get the lock/resource. And it happens because of the inappropriate use of mutual exclusion locks.
So let's see a sample of code where a deadlock situation is created intensionally for demonstrate purpose.
 
Output :


Here you can observe both th threads are waiting for each other to get the lock.

How to detect deadlock threads in your application?

Well, so Java has given default tools with the JDK package; using those we can detect the thread dumps which are in deadlock state. And also there are so many 3rd party tools available in market you can use for the same. 

Here we will discuss about Java's default tool and how programmatically we can detect deadlock.

Detect deadlock programmatically :

OK, so let's create a daemon thread which runs in background and detects if there is any deadlock thread and prints.
This is a thread which runs in background as daemon thread till the JVM is alive and repeatedly detects deadlock in every 5 seconds. 

Java 5 introduced new classes under package java.lang.management
ThreadMXBean : The management interface for the thread system of the Java virtual machine.
ManagementFactory : This is a factory class to get ThreadMXBean instance.
ThreadInfo : This class contains basic thread info like thread ID and thread name.

Now let's add the detector thread to the main program :
Output:
 

 

Detect deadlock using Java's default tools :

Using jconsole :
Java has provided jconsole tool in .../<jdk_home_dir>/bin
Step - 1: ../bin/$ jconsole

Step 2 : Select process name with PID and click Connect

Step - 3 : Select Thread tab and click Detect Deadlock

Final output window:
 

Using jstack :

Java has provided jstack  tool in .../<jdk_home_dir>/bin
Step - 1: ../bin/$ jstack <PID>
Ex : ../bin/$ jstack 17472 
Output:


That's all for this post. Please feel free to give your comment/suggestion. Thank you.
 

Wednesday 17 August 2016

Why enum is the best approach to implement a Singleton class ?

In my previous blog (Implement SIngleton class in an efficient way), we have already discussed about all the approaches to implement a singleton class and concluded with the enum type implementation. As mentioned earlier enum is completely safe from reflection and serialization attack.

Now we will see in details that,
- Is enum really safe
- Whether we can break an enum from singleton with either reflection or serialization.

Before proceeding to this let's know more about enum in depth.

OK, what you think about this simple enum ? What is exactly an enum ?

Well, an enum is a simple class which extends java.lang.Enum class. Believe me this is the truth behind enum keyword. Java compiler plays the main role here while compiling the enum; it converts the enum to a normal class and extends that class directly from Enum class rather than Object class. Now let's check the truth.

So, the compiler injects 3 more elements (2 methods and 1 static block).

Let's try to instantiate an enum using java Reflection API.

Test class
Output
 
Here the exception is because of private constructor. Since public/protected constructors are not allowed inside an enum, the default access scope of a constructor is private inside an enum. So it fails to instantiate directly.
Let's try by modifying the access scope of constructor.
Output

Now this time the exception is because, inside java.lang.reflect.Constructor.newInstance(Object ... initargs), there is a condition check like below :

 So there is no way to instantiate an enum using reflection.

Let's try to make copy of an enum instance.
Test class
Output
 
Now you can observe few things:
- hash code f both the objects are same
- state of the object got changed after it being serialized, but the changes are reflected in the deserialized object. So it is clear that the state of an enum instance is not serialized but the name by calling java.lang.Enum.name(). And while deserializing it gets only the name of the instance and by calling java.lang.Enum.valueOf() method it gets the actual enum instace.

Conclusion : enum type is a special class which can not be instantiated outside of the enum class in all possible way.


Please feel free to give your comment/suggestion. Thank you.

Tuesday 16 August 2016

Implement Singleton class in an efficient way

Singleton design pattern

This is one of the creational patterns described by GoF. This pattern ensures that a class must have one and only one instance provided a global access point to it and also with lazy initialization (initialization on first use).

So, to meet the above requirements, few steps of implementation are coming into our mind :
  • define private no-argument constructor
  • declare private static variable of the class type as instance and initialize
  • define a public static method as access point of the instance and return the instance
Approach -  1 (Eager Initialization)

This is the simplest implementation of a singleton class. But the concerns here are :
1. Eager initialization
2. Missing exception handling if there is chances of getting any exception during object construction

Approach - 2 (Eager Initialization with Exception handling)
Here the exception handling is included but still is an eager initializsation. To achieve lazy initialization, we have to instantiate the object on demand (on first access). 

Approach - 3(Lazy Initialization with Exception handling)

Here both above concerns are addressed (lazy initialization and exception handling) and the code looks fine. But it doesn't mean this is the efficient implementation. This implementation has so many concerns :
1. Not thread safe
2. Can be broken by serialisation if the class is serializable 

For thread safe, that we can achieve through synchronisation (either by defining synchronized method or synchronized block with double check lock while instantiating the object). 
Approach - 4
And in the previous approach (Approach - 1 and Approach - 2), during the eager initialization, the implementation is completely safe in multi threaded environment as the object is instantiated during the class loading. But we can't achieve the lazy initialization in this approach. To overcome this Bill Pugh came up with a new approach to create singleton class using a static inner class. 
Approach - 5 (Bill Pugh's approach using static inner class to achieve thread safety and lazy loading)
Here SingletonHelper class is a static inner class. And this will not be loaded with the Singleton class. When ever the Singleton.getInstance() method will be invoked, and the SingletonHelpet.instance will be access for the first time,  the helper class will be loaded at the same time. Using this approach the lazy initializaton is achieved easily and also thread safe.

Now, let's discuss about the other concern - "Can be broken by serialisation if the class is serializable". Here we can apply Java's magic method trick to resolve these kind of problems. Java provided some hidden and tricky method ( readResolver() ) for developer to replace the deserialized object with the required object.
Approach - 6 
The readResolve() is called when ObjectInputStream reads the object from stream and trying to return to the caller. Here we have returned the SingletonHelper.instance, so the deserialized object will be replaced by this instance.

After all these approach, you might have decides already to go with the Approach - 6 as it overcomes all the concerns :
1. No more eager initialization
2. Thread safe in multi threaded environment
3. Safe with Serialization

After all looks fine, now we will discuss about the real devil for all these approaches that is Java Reflection. This is the mechanism by which any kind of class (even with private constructor, private members)  are also can be accessed by creating new instance of that class. So the above approach can be broken with this mechanism. 

To overcome this, we have to go for the best approach for implementing singleton class proposed by Joshua Bloch in Effective Java "a single-element enum type is the best way to implement a singleton".
Approach - 7 (The best for Serialization/Reflection attacks but eager initialization)
 
Here in this above example I have demonstrated the same previous required singleton class using enum type. 

The below are the reasons why this approach is the best to implement a singleton class.
     1. Java gives guarantee that enum can not be broken by Reflection API : We can not create 
         instance of an enum using Reflection API
     2. Serialization process is different for enum than a normal class : During serialization,         
         ObjectOutputStream writes the value returned by enum constant's name() method. And to      
         deserialize an enum constant, ObjectInputStream reads the constant name from the stream; the 
         deserialized constant is then obtained by calling the java.lang.Enum.valueOf method, passing 
         the constant's enum type along with the received constant name as arguments.  

Above all benefits, still enum type approach has the concern of eager initialization. We can not achieve Lazy Initialization in this approach but more robust for serialization/reflection attack. If you have more concerns about eager initialization, then you can go with Approach - 6 but again the devil (reflection API) can pull it down.



Please feel free to give your comment/suggestion. Thank you.

Monday 8 August 2016

Power of Lambda Expression and Function Programing in Java 8

Functional Programing is the most powerful concept introduced in Java 8. And this can be only achieved by Lambda Expression.

Now, you may get W2H in your mind. Hold on, "W2H" is not any chemistry terminology. I just refer as W2H means (What, Why and How). I mean you are now thinking about "What is Lambdas, Why Lambdas, and How to use Lambdas ?".

Before discussing on Lambdas in details, I just want you to feel the power of it using some examples. Each example here I have prepared with 2 snippet of codes, first is without Java 8 and followed by Java 8 style implementation.

I have a list of employees here with members(id, name, salary, doj, location, dept, permanent/contractor).
Employee{empId='EMP001', name='Mr. Alpha', salary=24000.0, deptName='Product Development', isPermanent=true, doj=Mon Dec 12 00:00:00 IST 2011, location='Chennai'}
Employee{empId='EMP002', name='Mr. Beta', salary=43000.0, deptName='Support', isPermanent=false, doj=Mon Jul 02 00:00:00 IST 2012, location='Chennai'}
Employee{empId='EMP003', name='Mr. Gama', salary=66000.0, deptName='Product Development', isPermanent=false, doj=Mon Dec 30 00:00:00 IST 2013, location='Bangalore'}
Employee{empId='EMP004', name='Mr. Theta', salary=54000.0, deptName='Quality Engineer', isPermanent=true, doj=Wed Sep 12 00:00:00 IST 2012, location='Hyderabad'}
Employee{empId='EMP005', name='Mr. Delta', salary=58000.0, deptName='Support', isPermanent=true, doj=Tue Apr 23 00:00:00 IST 2013, location='Hyderabad'}


These examples are demonstrated the power of Lambda Expression and Functional style of programming. We will discuss in depth how it works for better understanding.  

Stay tuned for more updates.....

Friday 5 August 2016

Folder Watcher using java.nio.file.WatcherService

A simple folder inspector/watcher which logs the user action into a file.
User actions includes :
- Create
- Modify
- Delete

Here we are going to discuss on few new classes introduced as part of java.nio package with Java 1.7
- java.nio.file.Path : This represents typically represent a system dependent file path to locate a file in a file system.
- java.nio.file.WatchService : It a service that watches registered objects for changes and events. For example a file manager may use a watch service to monitor a directory for changes so that it can update its display of the list of files when files are created or deleted.
- java.nio.file.WatchEvent : An event for an object that is registered with a WatchService.
- java.nio.file.WatchKey : A token representing the registration of a watchable object with a WatchService. Here Path is a watchable object which will be watched by WatchService.
- java.nio.file.FileSystems : Factory methods for file systems.
- java.nio.file.FileSystem : It is an interface to a file system and is the factory for objects to access files and other objects in the file system.

FolderWatcher.java

Output:dir-log.txt


Thursday 7 April 2016

Sudoku Solver : Solve any level of Sudoku

Sudoku Solver :
This is implemented by simple back-tracking algorithm (Backtracking Ref) in Javacript.

Simple steps to solve your Sudoku :
     1. Download the file  Sudoku Solver
     2. Make sure the downloaded file should be save as .html  file, else rename it to <filename>.html
     3. Open downloaded file in browser

Algorithm :
Input : A 2D 9x9 array (arr) with having valid and solvable input values.
            Valid - No number (1-9) is repeated in a same row, same column or same 3x3 box.
            Solvable - Even though the input is valid, but there is a chance of not having the solution for a                               particular input if that is randomly generated.

boolean solveSudoku(arr[9][9])
               Find an EMPTY cell (r, c) from the array 
               If no EMPTY cell found then
                         return TRUE ; // i.e the array is filled i.e. solved
               else
                         for num from 1 to 9
                                 check if arr[r][c] is SAFE to put num
                                 if SAFE then
                                            arr[r][c] = num; //update cell with num, consider this is a part of the goal
                                            // call recursively solveSudoku(arr) to solve next EMPTY cell
                                            result = solveSudoku(arr) 
                                            if result is FALSE then   // No solution  exist with arr[r][c] = num 
                                                      arr[r][c] = 0;  // Revert back the considered solution
                                            else
                                                      return TRUE; // We reached at the goal by taking arr[r][c] =num
                       end for
                       return FALSE;   // No solution exists, since no number from 1 to 9 can be placed at(r,c)

For SAFE checking :
boolean isSafe(arr[9][9], roe, col, num)
        if num is present in same row or same column or same inner 3x3 box then
                 return FALSE
        else
                return TRUE


Get Source Code here.


Thank You for Visiting the blog.

Saturday 2 April 2016

Text to Speech in Java

Converting text-to-speech is very simple, just by using FreeTTS library.

Include library by maven dependency :
<dependency>
<groupId>org.mobicents.external.freetts</groupId>
<artifactId>freetts</artifactId>
<version>1.0</version>
</dependency>

OR
Download library (jar file) from here and include into project directly.

How to use FreeTTS API ?
Step - 1 : Get the instance of com.sun.speech.freetts.VoiceManager class.
               VoiceManager provides access to all voices available in FreeTTS
               VoiceManager voiceManager = VoiceManager.getInstance();

Step - 2 : Get com.sun.speech.freetts.Voice instance using voiceManager by supplying the voice name
               Voice voice = voiceManager.getVoice("kevin16");
               Here "kevin16" is one of the voice name available in FreeTTS library.
               You can also get all available voice names like below :
               
              Voice voices1[] = voiceManager.getVoices();  
              System.out.println("Available Voices");
              for (int i = 0; i < voices1.length; i++)
            System.out.println(voices1[i].getName());

Step - 3 : Set voice rate (i.e no of words per minute)
              voice.setRate(120);

Step - 4 : call speak( ) method by providing the text to speech
              voice.speak("<text to speech>");
              This speak( ) is overloaded to support various types of inputs like text, inputStream etc.
              You can also read a file by providing the fileInputStream as below : 
              FileInputStream fileInputStream = new FileInputStream("d:/ttsInput.txt");
              voice.speak(fileInputStream);

Here is the complete code to convert a text file to speech : 
import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
import java.io.FileInputStream;

public class TextToSpeech {
    private static final String voiceName = "kevin16"; // this is one of the voice name available in default
    private static void doSpeak() {
        try {
            VoiceManager voiceManager = VoiceManager.getInstance();
            Voice voice = voiceManager.getVoice(voiceName);

            if (voice != null) {
                voice.allocate();
                // Set 120 words per minute
                voice.setRate(120);
                FileInputStream fileInputStream = new                                                                FileInputStream("d:/ttsInput.txt");
                voice.speak(fileInputStream);
                voice.deallocate();
            } else {
                System.out.println("No Voice Available");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        doSpeak();
    }
}

Here is a demonstration of a Speaking Alarm Clock application using this FreeTTS library.
Functionalities of application : 
1. class AlarmClockThis class creates the alarm clock UI using Java Swing API, having feature to set alarm for a specific time and triggers the TimeSpeaker to speak the time on the time for which alarm is set.
2. class TimeSpeaker : This class converts any time into word form
                            e.g  05:15 -> quarter past five
                                  03:30 -> half past three
                                  11:40 -> twenty minutes to twelve
3. class TextToSpeech : This is the class responsible of converting text to speech using freetts (Free Text To Speech) library

Download OR fork complete project from here .


Thank You for Visiting the blog. Please feel free to share yout comment/suggestion. 

Thursday 10 March 2016

Be Careful while overriding hashCode() and equals() methods inside an Inner class

I know couple of questions coming into your mind before coming here.
    1. What is the new or different things while overriding hashCode() and equals() methods inside an inner class?
    2. Is there really any difference while overriding in a normal class and an inner class?

To answer these questions, let's see an example :

 Output








Here observe the output carefully, we have added 4 task executors into the set and then executing all one by one. But only 2 executors are executed. Because here taskExecutor1 and taskExecutor3 having same data/state and the hashCode() and equals() method identify both the objects as equal. Similarly for  taskExecutor2 and taskExecutor4 also.

Even though the state of the executor objects taskExecutor1 and taskExecutor2 are same, but they are associated with 2 different outer class objects service1 and service2 having different state/data. As a result somewhere if the inner class object depends on the outer class object's state, it may behave different. So the inner class objects should not be treated as equal objects if they are associated with different outer class objects regardless of its own state.

Let's modify the overriden equals() method inside the inner class in such a way that it should check the equality of the outer class objects also.

So while overriding equals() method inside inner class, it is most important to check the equality of the objects of the enclosed outer class. 

Output with the modified code :
 Note : If the outer class have non-static member(s), then it is mandatory to check the equality of the objects of the enclosing outer class.


Thank You for Visiting the blog. Please feel free to share yout comment/suggestion. 

Saturday 27 February 2016

ORM (Object Relational Mapping) is Not a Magic at ALL

How ORM works in background?
From the name itself, it says that

  • Map the object with relational database and keep the meta data(mapping informations). e.g. class against table name, fields of the class against columns of the table
  • Generate SQL on demand in background using the meta data and Java Reflection API. e.g. for saving an object it generates INSERT query corresponding to the table and fields for which the object is mapped. Similarly to find, update and delete, it generates SELECT, UPDATE and DELETE queryies respectively.

Here I have demonstrated how Hibernate(one of the ORM implementations) works internally using Java core API(including Reflection API) and JDBC API (not Hibernate API). Download/Fork project  from https://github.com/PrabhatKJena/HibernatePOC

First of all let's see how the code looks like when we are working with ORM.
Test.java
Output:
Here you can observe the code looks like Hibernate code but there is no hibernate API used. 

Now let's have a look into the code in background.
This is the config file (like hibernate-configuration) where JDBC connection details are configured. 

These are our custom annotations similar to @Entity@Column in Hibernate.

This is the Configuration class which is responsible for loading JDBC driver and set JDBC properties to SessionFactory (nothing but a JDBC Connection Factory)

This class is like a JDBC Connection factory which creates and returns JDBC Connection as a Session object.

This is the important class (same as Session in Hibernate) which provides methods to persist, update, get and delete an entity.

 This is a helper class which contains the meta data (mapping informations) about the entity class.


This is the most important helper class which is responssible for the antire secret behind ORM. 
  • Introspects the enity class and stores the meta data(mapping infromations) 
  • Generates the SQL on demand for every operations like insert, update, find, delete using Java Reflection API
The entire framework works with Reflection and Annotation API.




Thank You for Visiting the blog. Please feel free to share yout comment/suggestion.