Monday, April 28, 2014

Difference between Connected vs Disconnected RowSet in Java JDBC | RowSetProvider, RowSetFactory Example

RowSet interface is another key interface from JDBC API, which extends the ResultSet interface to provide support for the JavaBean component model. Along with convenient methods to set connection parameters e.g. setUrl(), setUsername(), setPassword() and setCommand(), it also defines getters and setters for different data types e.g. getLong() and setLong(). Another feature of RowSet is that it supports event listeners. You can attach listeners to RowSet object to listen for events, much like Observer design pattern. RowSet acts as Subject and notifies Observer on events like change in cursor location, change in row or change in the entire RowSet. There are two types of RowSet available in JDBC 4.1 API, connected and disconnected. A connected RowSet always keeps connection with database, while a disconnected RowSet connects to database, get the data and then close the connection. This doesn't prevent from working with data though, you can still change data in disconnected state, but to commit, connection needs to be re-established by RowSet. Java provides five different types of RowSet, JdbcRowSet, JoinRowSet, CachedRowSet, FilteredRowSet and WebRowSet. Out of these five only JdbcRowSet is connected RowSet, rest of them are disconnected row sets. It's very important to understand these new concepts form JDBC API, there are very popular JDBC Interview questions based upon these concepts e.g. difference between RowSet and ResultSet and difference between Connected vs Disconnected RowSet. Once you are familiar with key concept of RowSet class, you should be able to answer these question by your own.

Friday, April 25, 2014

How to Convert Byte Array to InputStream and OutputStream in Java

Are you stuck with your coding because you have a byte array and next method in chain needs an InputStream? don't worry Java has solution for that, You can use ByteArrayInputStream to convert byte array to InputStream in Java. This class takes a byte array as source and since it's a sub-class of InputStream, you can easily pass this to any method, which accepts InputStream as parameter. Though most of the API like JDBC and File API allows you to read directly from InputStream, because this allows you to process an arbitrary content with limited heap space. You should take advantage of this and directly read from InputStream instead of getting byte array and then converting them back to InputStream. It's only for those situation, where you have a legacy code, which is no more maintained and updated. Similarly converting byte array to OutputStream is trivial. Since we use OutputStream to write something, it allows you to directly write byte array in it. Say you have got some messages from TCP socket and want to persist in file system, you can use OutputStream and FileOutputStream to write byte array directly. Earlier we had seen how to convert InputStream to byte array, In this article, we will see opposite of that by creating a simple example of converting byte array to InputStream in action.

Tuesday, April 22, 2014

Difference between State and Strategy Design Pattern in Java

In order to make proper use of State and Strategy design Pattern in Core Java application, its important for a Java developer to clearly understand difference between them. Though both State and Strategy design patterns has similar structure, and both of them are based upon Open closed design principle, represents 'O' from SOLID design principles, they are totally different on there intent. Strategy design pattern in Java is used to encapsulate related set of algorithms to provide runtime flexibility to client. Client can choose any algorithm at runtime, without changing Context class, which uses Strategy object. Some of the popular example of Strategy pattern is writing code, which uses algorithms e.g. encryption, compression or sorting algorithm. On the other hand, State design pattern allows an object to behave differently at different state. Since real world object often has state, and they behave differently at different state, e.g. a Vending Machine only vend items if it's in hasCoin state, it will not vend until you put the coin on it. You can now clearly see the difference between Strategy and State pattern, there intent is different. State pattern helps object to manage state, while Strategy pattern allows client to choose different behaviour. Another difference, which is not easily visible is, who drives change in behaviour. In case of Strategy pattern, it's client, which provides different strategy to Context, on State pattern, state transition is managed by Context or State itself. Also, if you are managing state transition in State object itself, it must hold reference of Context e.g. Vending Machine, so that it can call setState() method to change current state of Context. On the other hand, Strategy object never held reference of Context, it's client which passes Strategy of there choice to Context. As difference between state and strategy pattern is one of the popular Java design pattern question on Interviews, In this Java design pattern article, we will take a closer look on this. We will explore some similarity and difference between Strategy and State design pattern in Java, which will help to improve your understanding on both of these patterns.

Tuesday, April 15, 2014

10 JDK 7 Features to Revisit, Before You Welcome Java 8

It's been almost a month Java 8 is released and I am sure all of you are exploring new features of JDK 8. But, before you completely delve into Java 8, it’s time to revisit some of the cool features introduced on Java 7. If you remember, Java 6 was nothing on feature, it was all about JVM changes and performance, but JDK 7 did introduced some cool features which improved developer's day to day task. Why I am writing this post now? Why I am talking about Java 1. 7, when everybody is talking about Java 8? Well I think, not all Java developers are familiar with changes introduced in JDK 7, and what time can be better to revisit earlier version than before welcoming a new version. I don't see automatic resource management used by developer in daily life, even after IDE's has got content assist for that. Though I see programmers using String in Switch and Diamond operator for type inference, again there is very little known about fork join framework,  catching multiple exception in one catch block or using underscore on numeric literals.  So I took this opportunity to write a summary sort of post to revise these convenient changes and adopt them into out daily programming life. There are couple of good changes on NIO and new File API, and lots of other at API level, which is also worth looking. I am sure combined with Java 8 lambda expression, these feature will result in much better and cleaner code.

Saturday, April 12, 2014

How to fix org.hibernate.MappingException: Unknown entity Exception in Java

If you have used Hibernate with JPA and using annotation to declare your entity bean then you might have seen this confusing error called "org.hibernate.MappingException: Unknown entity". This error message is so misleading that you could easily lose anywhere between few minutes to few hours looking at wrong places. I was using Spring 3 and Hibernate 3.6 when I got this error,which occurs when addEntity() method was executed. I checked everything, from Spring configuration file applicationContext.xml, Hibernate config file, my Entity class and DAO class to see whether my Entity class is annotated or not, but I was still getting this error message. After some goggling I eventually find that, it was an incorrect import which was causing this error. Both hibernate and JPA has @Entity annotation and some how Eclipse was automatically importing org.hibernate.annotations.Entity instead of javax.persistence.Entity annotation. Once I fixed this import issue, everything went smooth. Unfortunately, this error is not easy to spot, the org.hibernate.annotations.Entity import seemed completely appropriate to many programmers. For a newbie Java or hibernate developer it’s really hard to understand which Entity annotation to use, shouldn't be in org.hibernate.annotations.Entity, but instead it's javax.persistence.Entity. By the way, if you are using auto-complete functionality of Eclipse IDE, then you can blame it them, alternatively you can configure your preferred import in Eclipse.

Thursday, April 10, 2014

Difference between FileInputStream and FileReader in Java | InputStream vs Reader

Before going to explain specific difference between FileInputStream and FileReader in Java, I would like to state fundamental difference between an InputStream and a Reader in Java, and when to use InputStream and when to go for Reader. Actually, Both InputStream and Reader are abstractions to read data from source, which can be either file or socket, but main difference between them is, InputStream is used to read binary data, while Reader is used to read text data, precisely Unicode characters. So what is difference between binary and text data? well everything you read is essentially bytes, but to convert a byte to text, you need a character encoding scheme. Reader classes uses character encoding to decode bytes and return characters to caller. Reader can either use default character encoding of platform on which your Java program is running or accept a Charset object or name of character encoding in String format e.g. "UTF-8". Despite being one of the simplest concept, lots of Java developers make mistakes of not specifying character encoding, while reading text files or text data from socket. Remember, if you don't specify correct encoding, or your program is not using character encoding already present in protocol e.g. encoding specified in "Content-Type" for HTML files and encoding presents in header of XML files, you may not read all data correctly. Some characters which are not present in default encoding, may come up as ? or little square. Once you know this fundamental difference between stream and reader, understanding difference between FileInputStream and FileReader is quite easy. Both allows you to read data from File, but FileInputStream is used to read binary data, while FileReader is used to read character data.

Tuesday, April 8, 2014

For Each loop Puzzle in Java

From Java 5 onwards, we have a for-each loop for iterating over collection and array in Java. For each loop allows you to traverse over collection without keeping track of index like traditional for loop, or calling hasNext() method in while loop using Iterator or ListIterator. For-each loop indeed simplified iteration over any Collection or array in Java, but not every Java programmer is aware of some useful details of for-each loop, which we will see in this tutorial. Unlike other popular items from Java 5 release alias Generics, Autoboxing and variable arguments, Java developers tend to use for-each loop more often than any other feature, but when asked about how does advanced foreach loop works or what is basic requirement of using a Collection in for-each loop, not everyone can answer. This small tutorial and example aims to bridge that gap by going through some interesting foreach loop puzzles. So, without any further delay let's see our first puzzle on Java 5 for-each loop.

Sunday, April 6, 2014

Dealing with org.hibernate.LazyInitializationException: could not initialize proxy - no Session in Hibernate Java

If you are working in Hibernate framework, then you know that one of the key feature of Hibernate is "lazy initialization", which allows framework to lazily initialize dependencies, relationship or association lazily from database on need basis. For example, if you are dealing with User object, which has relationship with Permission object like one user can have multiple permissions, then Hibernate may choose not to initialize the collection which holds all permissions at the time it initialized User object and instead returns a proxy object. At this point, if you close your session and letter tries to access an attribute from Permission object, you will get "org.hibernate.LazyInitializationException: could not initialize proxy - no Session in Hibernate". Why this error comes, because hibernate needs to go database to initialize the proxy object, and connection is already closed. If you remember, what we discussed in difference between get vs load in hibernate that Proxy object is only initialized in Hibernate if you access any attribute other than id itself, that's why you would only see LazyInitializationException if you try to access an attribute other than id. In this article, we will see different scenarios on which you could possibly get "org.hibernate.LazyInitializationException: could not initialize proxy - no Session in Hibernate" and how to solve them appropriately. I have tried to explain reasons which caused the error, and explained the solution as why it will work, but if you still face issues, then feel free to post it here. By the way, good understanding of lazy initialization is also a good Hibernate interview question, so this not only help you to solve this error but also to do well during interviews.

Friday, April 4, 2014

How to replace line breaks , New lines from String in Java.- Windows, Mac or Linux

We often need to replace line terminator characters, also known as line breaks e.g. new line \n and carriage return \r with different characters. One of the common case is to replace all line breaks with empty space in order to concatenate multiple lines into one long line of String. In order to replace line breaks, you must know line terminator or new line characters for that platform. For example, In Windows operating system e.g. Windows 7 and 8, lines are terminated by \n\r  also known as CR+LF, while in Unix environment e.g. Linux or Solaris line terminator is \n, known as line feed LF. You can also get line terminator pragmatically by using Java system property line.terminator. Now question is, How can you replace all line breaks from a string in Java in such a way that will work on both Windows and Linux (i.e. no OS specific problems of carriage return/line feed/new line etc.)? Well, You can use System.getProperty("line.terminator") to get the line break in any OS and by using String replace() method, you can replace all line breaks with any character e.g. white space. replace() method from java.lang.String class also supports regular expressions, which makes it even more powerful. In next section we will learn how to replace all line breaks from Java String by following a simple code example. By the way, if you are removing line breaks from String then don't forget to store result of replace() method into same variable. Since String is immutable in Java, any change on it will always produce a new String, if you assume that call to replace() will change the original string then it's not going to happen. For example, in below code original String text will remain unchanged, even after calling replace() method.

Wednesday, April 2, 2014

Difference between Stub and Mock object in Java Unit testing - JUnit

JUnit is the most popular framework for unit testing Java code. Unit testing is used to test a single programming unit e.g. a class or a method, in-fact many Java developer write unit test on per method basis. Stub and Mock objects are two concepts which helps during unit testing, they are not real object, but act like real object for unit testing purpose. By the way, If you are absolutely beginner in Java Unit testing then you can see this post to learn how to create JUnit test in Eclipse. Coming back to Stubs and Mocks, One reason of using Stub and Mock object is dependency of one unit into another. Since in real world, most unit doesn't work in isolation, they use dependent class and object to complete there task. One of the common testing approach to test a unit, which depends on other unit is by using Stubs and Mock objects. They help to reduce complexity, which may be require to create actual dependent object. In this tutorial, we will learn few basic difference between Stub and Mock object in Java Unit testing. This post is rather small to tackle this whole topic, at best it just provide an introduction. I would suggest to follow on some good books on Java Unit testing e.g. Pragmatic Unit Testing in Java. This is one of the must read book in Java Unit testing, and my personal favourite as well. Apart from teaching basics of Unit testing it also gives a nice overview of Mock objects and mock framework. Actually, from there, I came to know about EasyMock and jMock frameworks and how useful they can be. Even if you have been using JUnit and unit testing, you can learn a lot form this book. It's like learning from basics to best practices of Unit testingMockito is another useful library enables mocks creation, verification and stubbing.