Setting up the DB2 database on Ubuntu and testing JDBC connectivity

I got my DB2 database installation running on a Ubuntu 11.10 machine recently, and have documented the steps I carried out below.

Downloading DB2

The express edition is free, and can be downloaded from Download DB2 Express-C. You’ll need to register for an IBM id if you don’t already have one.

Download DB2 Express C Using HTTP

Extracting and installing

Use the command tar -zvxf db2exc_975_LNX_x86.tar.gz to extract the gzipped file. Run the installer using sudo ./db2setup, and choose “Install a Product” on the left menu. The installation process is quite straightforward after this point.

DB2 Setup Launchpad - Install a Product as root

Troubleshooting ‘not found’ when running db2setup

I faced the following problem when I ran the setup script:

$ sudo ./db2setup
   The required library file is not found on the system. 
   Check the following web site for the up-to-date system requirements
   of IBM DB2 9.7  
  Aborting the current installation ...
  Run installation with the option "-f sysreq" parameter to force the installation.

To fix it, I had to run sudo apt-get install libaio-dev to install the missing package.

Verifying the Installation

The following command verifies the db installation and configured instances:

sudo /opt/ibm/db2/V9.7/bin/db2val -a

Creating a database

Switch to the user account that is the owner of the instance (db2inst1 is the default).

$ su db2inst1

Switch to the bash shell if necessary:

$ bash

Under this user account, you can run DB2 commands as illustrated below. Note that the create database command takes time – it took several minutes on my machine.

$ db2 create database test
DB20000I  The CREATE DATABASE command completed successfully.
$ db2 connect to test

   Database Connection Information

 Database server        = DB2/LINUX 9.7.5
 SQL authorization ID   = DB2INST1
 Local database alias   = TEST

$ db2 "create table test.technonstop(id int, username varchar(200))"
DB20000I  The SQL command completed successfully.
$ db2 "INSERT INTO test.technonstop VALUES(1, 'abdullah')"
DB20000I  The SQL command completed successfully.


If you’re unable to run any db2 command, the db2 environment variables may not have been sourced. To do it, run the following command at the terminal, replacing db2inst1 with the instance owner.

. /home/db2inst1/sqllib/db2profile

Java Program to Test JDBC Connectivity

I use the following Java program to test to see if JDBC connectivity works from a Java program, after assigning appropriate values to the constants at the beginning:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class PrintSQLTable {

	final static String dbdriver = "";
	final static String dburl = "jdbc:db2://localhost:50000/test";
	final static String dbuser = "db2inst1";
	final static String dbpassword = "myPassword";
	final static String dbtable = "test.technonstop";
	public static void main(String[] args) throws ClassNotFoundException,
			SQLException {
		Connection connection = DriverManager.getConnection(dburl, dbuser,
		Statement statement = connection.createStatement();
		ResultSet resultSet = statement
				.executeQuery("SELECT * FROM " + dbtable);

		StringBuilder tableContents = new StringBuilder("");
		ResultSetMetaData metaData = resultSet.getMetaData();
		int noOfColumns = metaData.getColumnCount();

		for (int i = 1; i <= noOfColumns; i++) {
			tableContents.append(metaData.getColumnName(i) + " \t ");

		int sbLength = tableContents.length();
		for (int i = 0; i < sbLength; i++)

		while ( {
			for (int i = 1; i <= noOfColumns; i++) {
				tableContents.append(resultSet.getString(i) + " \t ");

		if (tableContents.length() == 0)
			tableContents.append("No data found");



Run the program with the db2jcc.jar file in the classpath, as shown below:

$ java -cp /opt/ibm/db2/V9.7/java/db2jcc.jar:. PrintSQLTable
1 	 abdullah 	


List of Shortcuts for the Eclipse Java IDE

Here’s a cheat sheet of Eclipse shortcuts I’ve put together to help me work really fast with the IDE. The shortcuts have been categorized into two sections – one that most people know about, and another section that contains the lesser known ones. You should be able quickly scan through the first section, and learn any of the ones that you don’t currently know.

The second section might take longer, and you may want to bookmark this page for future reference.

Easy Shortcuts

Search in files

Use CtrlH to search in all files across the workspace or project.

Search Dialog in Eclipse Juno

Open Resource

CtrlShiftR opens a resource quickly – without the time it spends for indexing. This makes it especially fast when you’ve just opened a workspace, in comparison to the Open Type shortcut below.

Open Resource Dialog in Eclipse Juno

Open Type

Use CtrlShiftT to open a Java type.

Open Type Dialog in Eclipse Juno

While I prefer CtrlShiftR to search for files, CtrlShiftT works better if you want to search for Java classes or interfaces.

Open the Type Hierarchy

Use CtrlT to get a popup window with the type hierarchy for the type under your cursor.

Type hierarchy popup - Eclipse Juno

This is tremendously useful to see inherited types, sub-types, and implemented interfaces.

Press CtrlT again to toggle between super-types and sub-types.

Display members and inherited members

Pressing CtrlO displays the class members, pressing it again displays the inherited members too!

Eclipse class members popup

Focusing on the tooltip

Press F2 to get the tooltip for the item currently under the cursor.

F2 Tooltip Eclipse Juno

Correcting Indentation of Selected Text

Use CtrlI to correct indentation.


Use F5 to Step into, F6 to Step over, F7 to step out, and F8 to resume. See below for more shortcuts on debugging.

New File Wizard

Use CtrlN to start the new File Wizard.

New File Wizard - Eclipse Juno

Lesser Known Shortcuts

CtrlTab to Switch Between Windows

Go to General->Keys to see all shortcuts.

Setting Eclipse Juno shortcut for switching between editor windows

Change the binding of Next Editor and Previous Editor to use Tab instead of F6 – this makes it incredibly easy to switch between open editors. I often dislike changing keyboard shortcuts so that it’s easy to work on someone else’s machine too, but I couldn’t resist this one.

Cycle through tabs in the current view

Similar to the above, but still slightly different: Use CtrlPgUp and CtrlPgDn to switch between tabs in your current viewwithout showing you the complete list of available tabs.

Scroll without using the mouse

Use CtrlUp and CtrlDown to scroll, while keeping your cursor in the same position!

Move a line or lines

Use AltUp and AltDown to move selected lines, or the current line.

Jump to matching bracket

CtrlShiftP on a bracket, brace or parenthesis moves the cursor to its matching bracket, brace or parenthesis.

Progressively Select Blocks

Use ShiftAltUp / ShiftAltDown to progressive select blocks.

Find references

CtrlShiftG will find references to the item under the cursor.

Find declarations (Only C++/Javascript)

CtrlG finds declarations of the item under the cursor.

Open Declaration

F3 opens the declaration for the item under the cursor.

Find previous and next, based on selection

Use ShiftCtrlK and CtrlK to find the previous and next occurrences of the item under the cursor.

I had to set CtrlK for “Find next” in Preferences->General->Keys, but the shortcut for “Find previous” was there by default.

CamelCase Code Completion

If you have a class that has a VeryLongName, simply type VLN and press CtrlSpace to see VeryLongName as one of the suggestions.

Automatically Insert Braces and Semicolons at the correct position

This isn’t a shortcut – but a useful productivity boost. Setting semicolons and braces to be automatically inserted in the correct position allows you to type them in from anywhere but they actually appear at the end of the line. Escaping text in string literals is another useful option.

Eclipse Juno preferences - automatic insertion of braces and semicolons at correct position and escaping pasted strings

Quick Access Menu

Quickly access any menu, command, editor, etc by typing in Ctrl3 and then the initial letters of the item you want.

Eclipse Juno quick access menu


Use AltLeft and AltRight to navigate between your editor history items. This is equivalent to using the history icons on the toolbar.

Eclipse Juno history toolbar buttons

Quick Fix

Use Ctrl1 to get to the quick fix menu and quickly fix compile-time issues.

Eclipse Ctrl-1 quick fix menu


Use CtrlR to run to the current line. Use CtrlShiftB to toggle a breakpoint. F11 debugs the last run program, while CtrlF11 runs it.


ShiftAltR renames an item and updates all references. Use ShiftAltL to extract code to a local variable, and ShiftAltM to move code to a method.

The Best of them all!

And finally, which one’s the greatest shortcut of all? Use CtrlShiftL to get a list of all available shortcuts!!

Eclipse Juno list of shortcuts



Reflection Proofing the Java Singleton Pattern when using Lazy Loading

The singleton design pattern in Java is one that I found over the years to be both tricky and interesting. There are many ways to break this pattern – and developers keep writing about different techniques to break it. One powerful way to break this pattern is to use reflection to access the private constructor and instantiate the class as many times as you want. The underlying idea is that you can call private members of any class using theAccessibleObject.setAccessible(true) reflection method.

There are available techniques to prevent such reflection attacks. One of them is using the old way of writing your Singleton class, that is, not using lazy initialization, and, in addition to that, throwing an exception in the constructor if it’s asked to create a second instance. Any client attempting to illegally execute the constructor after an instance is created will be thrown an exception. Listing 1 below illustrates this:

Listing 1: JavaSingleton class

package server;

public class JavaSingleton {
  private static final JavaSingleton INSTANCE = new JavaSingleton();
  private JavaSingleton() {
    if (INSTANCE != null) {
      throw new IllegalStateException("Inside JavaSingleton(): JavaSingleton " +
                                                        "instance already created.");
    System.out.println("Inside JavaSingleton(): Singleton instance is being created.");
  public static final JavaSingleton getInstance() {
    return INSTANCE;

Listing 2: JavaSingleton client

import server.JavaSingleton;
import java.lang.reflect.*;

public class TestSingleton {
  public static void main(String[] args) throws ReflectiveOperationException {
    System.out.println("Inside main(): Getting the singleton instance using getInstance()...");
    JavaSingleton s = JavaSingleton.getInstance();

    System.out.println("Inside main(): Trying to use reflection to get another instance...");
    Class<JavaSingleton> clazz = JavaSingleton.class;
    Constructor<JavaSingleton> cons = clazz.getDeclaredConstructor();
    JavaSingleton s2 = cons.newInstance();


When you run this client, you will get following output:

C:\singleton>java TestSingleton
Inside main(): Getting the singleton instance using getInstance()...
Inside JavaSingleton(): Singleton instance is being created.
Inside main(): Trying to use reflection to get another instance...
Exception in thread "main" java.lang.reflect.InvocationTargetException
  at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
  at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
  at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
  at java.lang.reflect.Constructor.newInstance(Unknown Source)
  at TestSingleton.main(
Caused by: java.lang.IllegalStateException: Inside JavaSingleton(): JavaSingleton instance already created.
  at server.JavaSingleton.<init>(
  ... 5 more

Nice stuff! But there’s one that noticeable here. This technique is possible only with early initialization, and not while using lazy initialization.

Lazy initialization, also known as on demand initialization, is often a requirement for reducing start up time of an application.

I wanted to write a singleton that addresses both the requirements of lazy initialization and defending against an attack in which a client creates a second a instance of the singleton.

My knowledge of Java Security gained while working on Websphere came in handy.

A Possible Use Case for this Requirement

Suppose we have a Java based service, in which clients get an instance via the getInstance() method, and we’d like to protect against multiple instances being created to avoid concurrency or memory related issues. Also, the start-up time needs to be short, so the method described above won’t work. The reason is that if we are throwing an exception in the constructor, we’d need to be certain that the first call to the constructor comes from within the class, or else the single instance could belong to a wrong class.

Design for the Reflection-Proof Lazily Initialized Singleton

  1. Allow ONLY the same class to access the constructor: We’ll need to do two things for this:
    1. Add code in the constructor that checks to see if the caller has access
    2. Create a policy file that defines which callers have access.
  2. There is one more thing, however. The Java Security Mechanism will check for the caller permissions for all callers present in the entire stack trace. Because of this, we need to wrap the call to our constructor in a doPrivleged block so that permissions are checked only from that point itself.

Modified Code for Lazy Initialization and Reflection Access Checks

Listing 3: Server JavaSingleton class

package server;

import java.lang.reflect.ReflectPermission;

public class JavaSingleton {

  private static JavaSingleton INSTANCE = null;
  private static int count = 0;

  private JavaSingleton() {
    ReflectPermission perm = new ReflectPermission("suppressAccessChecks", "");
    System.out.println("Singleton Constructor Running. Instance #" + count);

  synchronized public static final JavaSingleton getInstance() {
    if (INSTANCE == null) {
      AccessController.doPrivileged(new PrivilegedAction<Object>() {
        public Object run() {
          INSTANCE= new JavaSingleton();
          return null;
    return INSTANCE;

}//end of class

Listing 4: Client class

import java.lang.reflect.*;
import server.JavaSingleton;
public class TestSingleton {

  public static void main(String[] args) throws ReflectiveOperationException {
    System.out.println("Using getInstance...");
    JavaSingleton s = JavaSingleton.getInstance();

    System.out.println("Trying to use reflection to instantiate Java Singleton...");
    Class<JavaSingleton> clazz = JavaSingleton.class;
    Constructor<JavaSingleton> cons = clazz.getDeclaredConstructor();
    JavaSingleton s2 = cons.newInstance();      
  }//end of main

}//end of class

Policy File Changes and Invocation

Creating a policy file

  1. Start the policy tool present in your JDK bin folder, and click “Add Policy Entry”Policy tool - first screen
  2. Enter the path to your Singleton class in the code base, the format of a URL. Do not include the package folder, and make sure your client classes reside in a different folder. For example, “file:/C:/singleton/server_code/”.CodeBase in policy tool
  3. Click “Add Permission” and select ReflectPermission from the Permission drop down and then select suppressAccessChecks from the Target Name drop down, and click OK.Permission added in policy tool for supressAccessChecks
  4. Click DonePolicy tool after adding permission
  5. Click File->Save, and provide a file name like

Your file should look similar to the following:

/* AUTOMATICALLY GENERATED ON Sun Nov 06 22:05:42 AST 2011*/

grant codeBase "file:/C:/singleton/server_code/" {
  permission java.lang.reflect.ReflectPermission "suppressAccessChecks";

Important: Keep the client and server code in separate code bases, otherwise the client code will have reflective access to the server code that it shouldn’t have. I placed the client class file in C:/singleton, and the server class files in C:/singleton/server_code. That is, the two server class files were present in C:/singleton/server_code/server (since they are in the “server” package).

Invoking the program

Invoke the program using a VM arg that specifies the location of the policy file:

C:\singleton>java  -cp .;server_code TestSingleton
Using getInstance...
Singleton Constructor Running. Instance #1
Trying to use reflection to instantiate Java Singleton...
Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at TestSingleton.main(
Caused by: access denied ("java.lang.reflect.ReflectPermission" "suppressAccessChecks")
        at Source)
        at Source)
        at server.JavaSingleton.<init>(
        ... 5 more

Looking at the above output, we can see that our malicious client was denied access when trying to call the constructor directly. Thus, this example illustrates how we can implement a singleton that uses lazy initialization and protects against reflective attacks.




Upgrade from Ubuntu 11.04 to 11.10, and a pleasant user interface greets you. Does the good news end there?

UPDATE (18th Nov, 2011): I carried out a clean installation from a USB drive, and no longer have the purple/blank screen problem while loading the 3.0.0-12-generic kernel. I can conclude that a problematic web upgrade process prevented the newer kernel from loading. Possible fixes are being discussed on various forums, but none of them have worked for me.

I’ve been running Ubuntu 11.04 (Natty Narwhal) for several months and have been satisfied with the experience. In October 2011, the newest stable Ubuntu 11.10 version (Oneiric Ocelot) was announced.

The upgrade to the new distro can be carried out by running the command:

sudo do-release-upgrade

You could also enable automatic updates, like I did, and have Natty Narwhal prompt you to upgrade. Simply go to System -> Administration -> Update Manager, click on the ‘Settings…’ button, and in the ‘Updates’ tab, turn on the checkbox for automatic updates. Also ensure that the release upgrade option is set to “Normal releases”.

To me, it was a surprise that I didn’t have to go to fetch Ubuntu 11.10 or run a command to get it – it came straight to me!

Welcome to Ubuntu 11.10 Oneiric Ocelot

Fast and easy install? Well, the upgrade certainly did not go on unattended and repeatedly questioned me about replacing some old configuration files.

My machine, incidentally, isn’t so dated – it runs an AMD Athlon X2 2.5 GHz processor with 2 GB RAM and an Nvidia GeForce7050PV graphics card.

After a lengthy download of over 850 MB – the size may vary for you, depending on the number of packages needed – and an install process which wasn’t without hiccups, I had to restart, only to find a blank purple screen and no hard disk activity.

Enough to cause my heart to sink.

Doing a hard reboot took me to a menu with a list of options to choose from:

  1. Ubuntu, with Linux 3.0.0-12-generic
  2. Ubuntu, with Linux 3.0.0-12-generic (recovery mode)
  3. Previous Linux versions
  4. Memory test (memtest86+)
  5. Memory test (memtest86+, serial console 115200)

If I’d choose the first option, I’d be back to square one. Choosing the second option would result in a kernel panic.

I went to “Previous Linux versions” and found these options:

  1. Ubuntu, with Linux 2.6.38-8-generic
  2. Ubuntu, with Linux 2.6.38-8-generic (recovery mode)

I chose the first one and was greeted by a glossy LightDM login screen, followed by a beautiful new Ubuntu desktop.

An Exciting New Linux – But not everything’s Smooth Sailing

It turned out that Ubuntu 11.10 was failing to load the new Linux 3.0.0-12-generic kernel. I decided to install the startup manager from the synaptic package manager, and set the default operating system to the older Linux 2.6.38-8-generic to allow my system to function.

Startup Manager

A big thank you to the posters discussing this issue on the thread that helped me!

As for the user interface, much of it is revamped. The action of dragging and docking folders is nicely animated. My Atheros chip based Wi-Fi adapter now connects me to the Internet almost instantly, unlike the case with Natty Narwhal, where I had to wait for several tens of seconds before connectivity would be established. The processes of both starting up and shutting down the computer take only slightly longer.

There’s a prominent launcher that appears when hovering the cursor on the left side of the screen, to help you open your favorite application almost instantly.

Clicking the dash on the top-left corner reveals a translucent box to help navigate to various parts of your machine fairly fast. There’s a Mac OSX-style spotlight for instant searches. However, critics are furious that Ubuntu is trying a lame copy of Mac’s stunning user interface and falling short.

Accessing the most frequently used and other installed applications through the dash was never easier, not least due to the Filters feature that is clearly a leap over the basic offerings of Ubuntu 11.04.

Ubuntu 11.10 Desktop

What worries me is that the dash once became unstable and disappeared.

Switching applications is facilitated by pressing either the Alt+Tab or Alt+Grave buttons and choosing a running program from a frosted-glass box. However, this seems to cause my computer to hang after using it for several seconds, calling for a hard reboot.

I haven’t really tried many of the applications that came pre-bundled with Ubuntu 11.04 or were available for download, since I spend most of my time on the Internet. The few I did try from the math, engineering and graphic designing sections failed to impress me, and I won’t be surprised if Ubuntu 11.10 is not very different on this front.

The Conclusion?

Well, there still seem to be issues that Canonical has to address. Ubuntu 11.10 with its default Unity interface surely has an unprecedented, elegant look and feel. But there’s got to be more than skin-deep beauty – Canonical should definitely have done better testing on the upgrade process and its end result.