Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Protobuf for lazy Java coders.

Sometimes you are just plain lazy and would rather have Maven create the Java files out of .proto. The alternative would have been to download the protoc, fire up the terminal and issue one simple command. Not a big deal at all. But as I said sometimes you are just plain lazy.

So how do you go about it. Follow the steps given below.

Think up a super critical message that you want to send across over the wire.
If you dont know how to write a .proto file, perhaps one of the links below would help.
https://developers.google.com/protocol-buffers/docs/proto
https://developers.google.com/protocol-buffers/docs/proto3
The one below is the super critical hello world that I want to send across.

#1

Create a vanilla maven project. 
Say thanks to open source and add protoc-jar-maven-plugin to the project. 

#2

This would create the java files.
However they will complain that the google libraries are not around. 
So you will have to add the protobuf libraries. 

#3

The proof of the pudding is in eating it. 
Let's write a test to serialize and deserialize the super critical message. 

#4

That's it. You have a Java project that does the basic steps i.e. serialization / deserialization using protobuf. Hope that is helpful. If you know a easier, quicker way please share as well. 

Either ways your comments will be appreciated. Please take a couple of minutes and write back. 

One jar to rule them all.

Trip down the memory lane

Back in 1998, when I was a C/C++ developer, trying my hands on Java, a few things about the language were, to put it mildly - irritating - for me. I remember fretting about these quite a lot
  1. Why isn't there a decent editor for this? C/C++ had quite a few. All that I had for Java was the good old notepad. 
  2. Why do I have to make a class, when all I want is a function? Why wasn't a function an object as well? 
  3. Why can't I just package everything into one zip/jar and let the end user launch with a double click? 
and a few others.

Back then, I found me frequently chiding myself for not being able to let go of my "C/C++ way of thinking" and embracing "Java way" of doing things. Now, writing this article in 2013, about a decade and a half later, surprisingly all of those early irritations are gone. Not because I have embraced "Java" way, but because java has changed.

Idle chit chatting aside, the point of this article is to talk about one of these questions - "Why can't I just package everything into one zip/jar and let the end user launch with a double click?".

Why do we need this - one zip/jar - that is executable? 

If you are a developer, coding away happily on your IDE (I despise you all who have coded java on Eclipse, NetBeans from day one and have not had to code on Notepad :) ), assisted by Google (I positively totally hate all of you all who did not have to find stuff on internet before Google :) :) ), there is probably no convincing case.

However, have you faced a situation when
  1. You have been pulled into the data centre because the guy there have followed your deployment steps  but your application / website will simply not work? 
  2. All of a sudden the environment variables are all messed up, when "nobody at all so much as touched" the production boxes, and you are the one who has to "just make it work". 
  3. You are sitting with your business stakeholder and staring incredulously at a "ClassNotFound exception" and were convinced that Java did not like you at all.
In short, what I am trying to say is, when you are in the "relative" sanity of your dev box / environment, a one executable jar does not really do anything for you. But the moment you step into the twilight zone of unknown servers and situations (sans the IDE and other assortment of tools) you start appreciating just how much a single executable jar could have helped. 

Ok, I get it. But, what's the big deal? We can make such a package / zip / jar in a jiffy if we have to. Isn't that so. 

In all my naivety, I thought so and found out the answer the hard way. Let me walk you through it. Fire up your editors folks. Let's create a executableJar project. I use jdk1.7.0, STS, Maven 3.0.4. If you are new to Maven or just not hands on, I recommend you read this and this

File: C:\projects\MavenCommands.bat
ECHO OFF
REM =============================
REM Set the env. variables.
REM =============================
SET PATH=%PATH%;C:\ProgramFiles\apache-maven-3.0.4\bin;
SET JAVA_HOME=C:\ProgramFiles\Java\jdk1.7.0
REM =============================
REM Standalone java application.
REM =============================
call mvn archetype:generate ^
-DarchetypeArtifactId=maven-archetype-quickstart ^
-DinteractiveMode=false ^
-DgroupId=foo.bar ^
-DartifactId=executableJar001
pause
After you run this batch file, you will have a fully compilable standard java application. Go ahead compile it and build a jar (mvn -e clean install). You will end up with a executableJar001-1.0-SNAPSHOT.jar at C:\projects\executableJar001\target. Now lets go "java -jar jarFileName". And here you stumble the first time. In geeky vocabulary it tells you that there were no class with a main method and hence it did not know what to execute. 

Fortunately this is an easy one. There are standard java process to solve it. And there is a Maven plugin to solve it. I will use the latter. 

Updated File: /executableJar001/pom.xml
...
 
 ...
 

 
  
   
   
    org.apache.maven.plugins
    maven-jar-plugin
    2.4
    
     
      
       foo.bar.App
      
     
    
   

  
 
 ...

You can compile and assemble the application again (mvn -e clean install). It is will create a jar file in target folder. Try running the jar from command line again. This time you will get intended result. So, we are all sorted, right?

Wrong. Very wrong.

Why? Everything seems fine. 

Let's dig in a bit deeper and we will find why everything is not as sorted as it looks at the moment. Let's go ahead and add a dependency e.g. let's say we want to add logging and for that we want to use a third party jar i.e. logback. I will let Maven handle dependencies in the development environment. 

Updated File : /executableJar001/pom.xml 
...
 
  
  
   ch.qos.logback
   logback-classic
   1.0.9
  
 
 

 
  ... 
 

Updated File: /executableJar001/src/main/java/foo/bar/App.java
package foo.bar;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class App 
{
 private final static Logger logger = LoggerFactory
   .getLogger(App.class);
 
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
        logger.debug("Hello world from logger.");
    }
}
Now let's compile and run the jar from command prompt using jar command. Did you see what happened? 
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
Basically it is saying that the class (i.e the actual code) of the LoggerFactory (i.e. the 3rd party jar that we had added in development environment) was not found. 

Oh, but surely we should be able to tell java to pick up the 3rd party libraries from some folder.

Definitely. It is almost a certainty - if you are asking that question - that for most of your applications you tell the JVM where the 3rd party / dependency libraries are. You tell this by setting classpath. You could possibly be using some application server e.g. Tomcat / Jetty and that could be picking up some dependencies itself. And that is exactly where the problem originates. 

As a developer, I provide a x.jar that works. However, for it to work, it depends on a.jar (which in turn might depend upon b.jar and c.jar ... you get the point). When I, as a developer, bundle up my deliverable, a x.jar, there is a dependency - on whoever I am handing this out to - to make sure that the classpath is correctly set in the other environment where x.jar is supposed to work. 

It is not that big a deal, mostly. However, it is not trivial either. There are multitude of ways that the dependencies on target environment could get messed up. There might be routine updates. There might be some other application deployed in the same production box, that needed an update on a jar that nobody thought would impact yours. We can discuss and debate the multitude of ways that these kind of mishaps can be stopped, but bottom line is x.jar (the developers responsibility) has dependencies (that the developer do not directly control). And that leads to mishaps. 

Of course, if you add into this mix the whole lot of variables that comes in because of different versions, different application servers, etc etc. the existing solution of providing x.jar only, quickly starts looking very fragile. 

So, what do we do? 

Say thanks to Dr. P. Simon Tuffs. This gentleman explains how he catered to this problem in this link. It is a good read, I recommend it. What I have explained in very laymen terms (and have barely scratched the surface), Simon takes a deep dive into the problem and how he solved it. Long story short, he coded a solution and made it open source.  

I am not going to replay the same information again - read his article, it is quite informative - but I will call out the salient point of his solution. 
  1. It allows folks to create a single jar that contains everything - your code, resources, dependencies, application server (potentially) - everything. 
  2. It allows the end use to run this entire humongous jar by the simple java -jar jarFileName command. 
  3. It allows developers to develop the same way they have been developing e.g. if it is a web application, the war file structure, remains same. So there are no changes in the development process. 
Fine. So how do we go about doing it? 

There are many places where it is detailed out. The One-JAR website. Ant with One-JARMaven with One-JAR

Let's see it in action on our dummy code. Thankfully there is also a Maven plugin for this. Sadly it is not in the Maven Central repository (Why? Folks why? You have put in 98% of work. Why be sluggish about the last 2%?). It comes with nice usage instructions

Updated file: /executableJar001/pom.xml
...
 
 
  ... 
 

 
  
   
   ...

   
   
    org.dstovall
    onejar-maven-plugin
    1.4.4
    
     
      
       one-jar
      
     
    
   
  
 
 
 
 
  
   onejar-maven-plugin.googlecode.com
   http://onejar-maven-plugin.googlecode.com/svn/mavenrepo
  
 


Now all you need to do is run mvn -e clean package. You will get, apart from the normal jar, a fat self sufficient jar as well. Go ahead, do the java -jar jarFileName from command prompt again. It should work. 

Hmm.. that sounds good. Why isn't everybody going for this? And this One-JAR seems to be around since 2004. Why are we not seeing more players in this market? 

You know what they say about free lunches? There are none. While the concept is quite neat and very practical, it does not mean that every other player have decided to join in. So if your website "needs" to be hosted on one of the biggie paid application servers (I don't know why you want to keep paying for those proprietary software and folks that understand them. Should you not pay for only quality folks and rely on the open source apps that do not lock you in) One-JAR might not be a feasible solution for you. Also, I hear unconfirmed murmurs about how things might get sluggish (during load up  if your app is big. So, before you decide to commit to using this, I recommend you do a POC and make sure that other bits of your techstack are not unhappy with One-JAR.

My personal opinion is, 2004 was perhaps a little too early for this kind of thing. People were still struggling with stuff like standardization of  build and release process, getting clear player in ORM area, closing on a clear player for MVC framework etc. Not that those questions have been answered yet, or will be any-time soon. But I think the flavour of current problems in IT world are around 
  1. How to make DevOps work. 
  2. How to make the entire build and release automated. 
  3. How to leverage the open source libraries to provide solid dependable software while ensuring there are no heavy proprietary software causing lock-in and hence make the solution less agile for future business requirement. 
And in my mind, One-JAR plays very nicely in that area. So, I definitely expect to see more of this tool and / or more tools around this concept.

And, to be fair, there are more players in this area.

Thanks to Christian Schlichtherle for pointing this out. There is Maven Assembly Plugin and Maven Shade Plugin which cater to this exact same problem. I have not tried them yet but from the documentation they look quite alright, feature wise.

Dropwizard, although not the same thing, but in essence is very similar. They have extended the whole one jar concept with embedded app server, out of the box support for REST, JSON, Logback, sort of in a nice neat package, that  you could just use straight off the shelf. 

So, as I keep saying, these are nice exciting times to be in technology business, particularly if you like tinkering around with software. 

Hope you enjoyed reading this article. Please leave a comment if you have any suggestions and / or feedback. If you want to get in touch, you can look me up at Linkedin or Google+ .

Java and Database.

Every once in a while I tend to put on some music, switch off distractions (emails, phones) and redo some basic programming. Things that I know and I have done a handful of times. The intent is to practice, get back to basics and hope to get some new insight. I later read about CodeKata and realized that what I had been doing was not entirely unheard of. For anyone who treats building software as a craft, I can safely recommend this practice.

Enough rambling. In this article I am going to talk about using Java to connect to database. Elementary, you say. Absolutely, I concur. I highly recommend the links Connecting to an Oracle DatabaseClosing Database Connections in Java for a clear, concise read, in case you were looking to get those answers. However, if you are interested in a little more detailed, hands on, journey through the subject, I suggest you read on.

Tools 

Oracle. I have worked with a variety of RDBMS and/or NoSql (link) based applications and have no sweeping opinion for / against any of those. However, I tend to choose Oracle (express edition) even for my development environment. Call me old fashioned, but till I don't get to log into a "database server" and run queries to confirm that what I "think" my app did in database, I don't feel confident about my code.

Maven + Eclipse. I would tend to agree with anyone who says Maven is an overkill for simple applications (under 10 classes). But again, it's my gut. I don't feel confident if I don't use tools that I will use in any enterprise grade application in my codekatas (for the lack of a better name). After all, when you practise your skills, if you don't use the proper tool set, the practise session is a bit pointless, isn't it.

Getting warmed up

As I mentioned I use Maven. I have a batch file with the basic Maven commands (read more about it) that I use to create any new java application and then import it in Eclipse. Minus all the noise, this is how the batch file looks like.

File: \MavenCommands.bat
REM =============================
REM Set the env. variables. 
REM =============================
SET PATH=%PATH%;C:\ProgramFiles\apache-maven-3.0.4\bin;
SET JAVA_HOME=C:\ProgramFiles\Java\jdk1.7.0

REM =============================
REM Standalone java application. 
REM =============================
call mvn archetype:generate ^
    -DarchetypeArtifactId=maven-archetype-quickstart ^
    -DinteractiveMode=false ^
    -DgroupId=foo.bar ^
    -DartifactId=javadb001

This creates a complete java application, with a dummy class, a test case etc. The pom file contains most of the details. I tend to add a few standard elements in the pom file before I try anything else. In this case I will add the oracle thin client as well.

File:\javadb001\pom.xml
<properties>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>


<dependencies>

 <!-- Unit test. -->
 <dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.10</version>
  <scope>test</scope>
 </dependency>

 <!-- Logging -->
 <dependency>
  <groupId>ch.qos.logback</groupId>
  <artifactId>logback-classic</artifactId>
  <version>1.0.7</version>
 </dependency>

 <!-- Oracle database driver. -->
 <dependency>
  <groupId>ojdbc</groupId>
  <artifactId>ojdbc</artifactId>
  <version>14</version>
 </dependency>

</dependencies>

<build>

 <!-- Compile and run with current Java version -->
 <plugins>
  <plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-compiler-plugin</artifactId>
   <version>2.5.1</version>
   <configuration>
    <source>1.6</source>
    <target>1.6</target>
   </configuration>
  </plugin>
 </plugins>
</build>

If you run this "mvn -e clean install" this should download all dependencies and compile just fine.

The code (finally) 

In this case I think a JUnit test case would work just fine. We just need to create an instance of the driver (to connect to Oracle), give it some standard data, attempt a connect and then attempt a disconnect.

File: /javadb001/src/test/java/foo/bar/database/TestConnection.java
public class TestConnection {
 private final static Logger logger = LoggerFactory
   .getLogger(TestConnection.class);

 @Test
 public void test() {

  Connection connection = null;
  try {
   // Load the JDBC driver
   String driverName = "oracle.jdbc.driver.OracleDriver";
   Class.forName(driverName);

   // Create a connection to the database
   String serverName = "127.0.0.1";
   String portNumber = "1521";
   String sid = "XE";
   String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber
     + ":" + sid;
   String username = "funngames";
   String password = "funngames";
   connection = DriverManager.getConnection(url, username, password);
   assertNotNull(connection);
   logger.debug("All well");

  } catch (ClassNotFoundException e) {
   logger.debug(e.getMessage());
  } catch (SQLException e) {
   logger.debug(e.getMessage());
  } finally {
   if (connection != null) {
    try {
     connection.close();
    } catch (SQLException e) {
     logger.debug(e.getMessage());
     fail("The connection could not be closed.");
    }
   }
  }
 }
}

You will note that although it is the most basic (and useless functionality wise) piece of code, it is quite well behaved. It catches the required exceptions, and it attempts to close the connection. What is perhaps not as easily seen is that it is a well behaved code in enterprise applications scenario as well. It uses a standard and robust logging mechanism i.e. Logback. It uses a standard build, release (and more) tool i.e. Maven.

In a nutshell if you could think of a sort of virtual shelf, where your software engineers could walk up to and pick standard code templates, this is one of those. Impractical in it's present form but I hope you get the concept.

For those, who are still with me (congratulations by the way), and are interested in the whole codekata concept that I referred to at the beginning of the article, there is a wee bit more.

Can we bring down the boilerplate code?

I like Java for all it's stability and stuff. But, being a lazy human, I hate writing code that "feels like" could have been handled by the language itself. In this current code, multitude of try-catches are an eyesore. I understand why I need them but that does not necessarily mean I like writing them. Perhaps you have guessed already that I am referring to better resource management  introduced by Project Coin.

In a nutshell, Java 7 promises to handle the closing of resources i.e. Connection in this case, by itself. Let's give that a shot.

We need to tell maven that we want to use jdk 7.

File: /javadb001/pom.xml
<!-- Compile and run with current Java version -->
<plugins>
 <plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>2.5.1</version>
  <configuration>
   <source>1.7</source>
   <target>1.7</target>
  </configuration>
 </plugin>
</plugins>

And we need to update our test case to create Connection within a try to let java close it by itself.

public void test() throws SQLException {
 String driverName; 

 try {
  // Load the JDBC driver
  driverName = "oracle.jdbc.driver.OracleDriver";
  Class.forName(driverName);
 } catch (ClassNotFoundException e) {
  logger.debug(e.getMessage());
  e.printStackTrace();
 }
 // Create a connection to the database
 String serverName = "127.0.0.1";
 String portNumber = "1521";
 String sid = "XE";
 String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber
   + ":" + sid;
 String username = "funngames";
 String password = "funngames";
 try(Connection connection = DriverManager.getConnection(url, username, password)){
  assertNotNull(connection);
  logger.debug("Connection made.");   
 }    
}

If you compare this piece of code with the previous one, we have got rid of at least three try-catch blocks. But this code is useless in a practical scenario, you say. Totally, I agree. As I had mentioned earlier, the intent is to practice writing code - something mundane - but in multiple (hopefully new ways) and learn by practising. The intent is not to produce production ready, reusable components.  The quality of the code, the craftsmanship is important in this context. The benefit will be in terms of more skilful engineers in the organization and the associated benefit to business.

Finally, my litmus test... 

this supposedly nice, high quality code, how good is it when we run it 10,000 times in 5 threads. I hate to break the news to you but it is not too good at all. It crashes after 20 - 25 executions. Why? And how to fix that? I have discussed the problem and solution at stackoverflow. I hope you find it interesting.

Re-factor

This article is getting longish and I should wrap up now. Let's re-factor this code to a position where stuff are not in unit tests any more. The code ought to be in some classes where they could be used by client code. How does the updated test code looks to you.

File: /javadb001/src/test/java/foo/bar/database/TestConnection.java
 
@Test
@PerfTest(invocations = 100, threads = 1)
@Required(max = 1200, average = 1000)
public void testConnectionFactoryAndUtil(){
 Connection connection = ConnectionFactory.getConnection(); 
 assertNotNull(connection); 
 Util.closeConnection(connection);  
}

Compare this with the earlier test. That was 24 lines. Assuming you are convinced that this is a better looking test, how do we refactor to make this happen. It's your call really and you could do it multiple ways. Here is my take.

File:/javadb001/src/main/java/foo/bar/database/ConnectionFactory.java

public class ConnectionFactory {
 private final static Logger logger = LoggerFactory
   .getLogger(ConnectionFactory.class);

 public static Connection getConnection() {
  return getConnection("oracle.jdbc.driver.OracleDriver", "127.0.0.1",
    "1521", "XE", "funngames", "funngames");
 }

 public static Connection getConnection(String driver, String host,
   String port, String sid, String user, String pass) {
  Connection connection = null;
  try {
   // Load the JDBC driver
   Class.forName(driver);
   String url = "jdbc:oracle:thin:@" + host + ":" + port + ":" + sid;
   connection = DriverManager.getConnection(url, user, pass);
   logger.info("Connection opened [{}]", connection.toString()); 
  } catch (ClassNotFoundException e) {
   logger.debug(e.getMessage());
   e.printStackTrace();
  } catch (SQLException e) {
   logger.debug(e.getMessage());
   e.printStackTrace();
  }
  return connection;
 }
} 

File:/javadb001/src/main/java/foo/bar/database/Util.java

public class Util {
 private final static Logger logger = LoggerFactory.getLogger(Util.class);

 public static void closeConnection(Connection connection){
  if (connection != null) {
   try {
    logger.info("Attempting connection close [{}]", connection.toString()); 
    connection.close();
    Thread.sleep(500); 
    logger.info("Connection succesfuly closed."); 
   } catch (SQLException e) {    
    logger.debug(e.getMessage());
    e.printStackTrace();
   } catch (InterruptedException e){
    logger.debug(e.getMessage());
    e.printStackTrace();
   }
  }
 }
}

Needless to say, any of this code is hardly new or ground breaking. You might want to check out this class for a much more comprehensive set of utility functions to close connection and related resources. Feel free to use that utility (it is from Apache) or roll your own.

With this I will close this article. If you want to get in touch, you can look me up at Linkedin or Google+.

Bit by bit

My first ever software programming language was C. Almost two decades later, in weird unexpected ways I find myself understanding software concepts, subconsciously in C.

Recently I had some really interesting conversation around how hashcode() in Java is critical for efficient storage and retrieval from HashMaps. One thing lead to another and the conversation veered onto bit operators, and its use in overriding hashcode(). Here, I was in for a bit of shock. I realized that my understanding of bitwise operators in Java was sketchy to say the least. I just recalled what I had done in my C days. I did not recall having actually tried out bitwise operators in Java ever. I am sure I would have, but I did not recall it.

Now this is something that had to be fixed. Immediately after the chat I went back to my machine and set out to play with the Java bitwise operators. Thankfully it was indeed the exact same as C (or at least the way I recollect them). I ended up writing some code to printout the bits (given an integer) and proceeded to play with integers and bitwise operators. Following is an example output of my code, for integer 256 where the code tries out different bitwise operators on it.

00000000000000000000000100000000[256]
& 00000000000000000000000000000010[2]
========================================
 00000000000000000000000000000000[0]

 00000000000000000000000100000000[256]
| 00000000000000000000000000000010[2]
========================================
 00000000000000000000000100000010[258]

 00000000000000000000000100000000[256]
^ 00000000000000000000000000000010[2]
========================================
 00000000000000000000000100000010[258]

~ 00000000000000000000000100000000[256]
========================================
 11111111111111111111111011111111[-257]

 00000000000000000000000100000000[256<<2]
========================================
 00000000000000000000010000000000[1024]

 00000000000000000000000100000000[256>>2]
========================================
 00000000000000000000000001000000[64]

 00000000000000000000000100000000[256>>>2]
========================================
 00000000000000000000000001000000[64]

Following is the same code for anyone else interested, to play with.
private static void printBinaryOperations(int operand1, int operand2){

System.out.printf("\t%s[%d]\n", toBinaryString(operand1), operand1) ;     
System.out.printf("&\t%s[%d]\n", toBinaryString(operand2),operand2) ;
System.out.printf("========================================\n") ;
System.out.printf("\t%s[%d]\n\n", toBinaryString(operand1 & operand2), (operand1 & operand2)) ;

System.out.printf("\t%s[%d]\n", toBinaryString(operand1), operand1) ;     
System.out.printf("|\t%s[%d]\n", toBinaryString(operand2),operand2) ;
System.out.printf("========================================\n") ;
System.out.printf("\t%s[%d]\n\n", toBinaryString(operand1 | operand2), (operand1 | operand2)) ;

System.out.printf("\t%s[%d]\n", toBinaryString(operand1), operand1) ;     
System.out.printf("^\t%s[%d]\n", toBinaryString(operand2),operand2) ;
System.out.printf("========================================\n") ;
System.out.printf("\t%s[%d]\n\n", toBinaryString(operand1 ^ operand2), (operand1 ^ operand2)) ;

System.out.printf("~\t%s[%d]\n", toBinaryString(operand1),operand1) ;
System.out.printf("========================================\n") ;
System.out.printf("\t%s[%d]\n\n", toBinaryString(~operand1), (~operand1)) ;

System.out.printf("\t%s[%d<<%d]\n", toBinaryString(operand1), operand1,operand2) ;
System.out.printf("========================================\n") ;
System.out.printf("\t%s[%d]\n\n", toBinaryString(operand1<<operand2), (operand1<<operand2)) ;

System.out.printf("\t%s[%d>>%d]\n", toBinaryString(operand1), operand1,operand2) ;
System.out.printf("========================================\n") ;
System.out.printf("\t%s[%d]\n\n", toBinaryString(operand1>>operand2), (operand1>>operand2)) ;

System.out.printf("\t%s[%d>>>%d]\n", toBinaryString(operand1), operand1,operand2) ;
System.out.printf("========================================\n") ;
System.out.printf("\t%s[%d]\n\n", toBinaryString(operand1>>>operand2), (operand1>>operand2)) ;

}

And here is the function that prints the bits of any given integer. There is a similar function in Integer class and I had started off with that, but I found that it chops off the leading 0s and that was not good enough for me.
private static String toBinaryString(int number) {
 char[] buf = new char[32];
 int charPos = 32;
 int mask = 1 ; 
 do {
  buf[--charPos] = ((number & mask)==0)? '0':'1'; 
     number >>>= 1;
 } while (charPos != 0);

 return new String(buf);
}

For further reading 
I found this article quite good. It gives a few neat usage of bitwise operators. Also I borrowed heavily from toUnsignedString(int i, int shift) in Integer class of Java.

If you want to get in touch, you can look me up at Linkedin or Google + .