Tuesday, February 15, 2011

Failure and Guilt

When failure results from effort and you did everything within your
ability, then you do not (and should not) have guilt. But how do you
find your ability? By trying.

- Jeff Hunt (Paraphrased)

You become strong at whatever you repeat

Whatever it is that you repeat, you become strong. If you take more
decisions influenced by your virtues, you will become a more stronger
person. If you take more decisions influenced by your weakness or evils
you will become a weaker person.

So choose to take decisions influenced by your virtues.

- Jeff Hunt (paraphrased)

Sunday, February 13, 2011

Fetching database rows using ResultSet in JDBC

The basic approach to fetching rows from DB:

Connection con = // Secure a connection using this approach
Statement stat;
try
{
stat = con.createStatement();
ResultSet rs = stat.executeQuery("select * from emp");
while ( rs.next() ) // Move cursor 1 row forward, false returned means last row
{ // next | previous | first | last | beforeFirst | afterLast |
// relative (int) | absolute(int)
String empName = rs.getString("EMP_NAME"); // or getString()
int empId - rs.getInt("EMP_ID");
..
}
} catch( SQLException e)
{
...
} finally
{
stmt.close();
}

ResultSet types:

TYPE_FORWARD_ONLY [DEFAULT]: Only scroll forward (not backward) - insensitive to changes made by others (Contains results as they existed at query execution time or as rows are retrieved - depends on how db generated results)

TYPE_SCROLL_INSENSITIVE: Scrolls back, forward and to absolute or relative position. insensitive to changes made by others (Contains results as they existed at query execution time or as rows are retrieved - depends on how db generated results)

TYPE_SCROLL_SENSITIVE: Scrolls back, forwards and to absolute or relative position. Changes made by others at the data source are reflected in the ResultSet.

ResultSet concurrency:

CONCUR_READ_ONLY [DEFAULT]: No support for updates using ResultSet Interface
CONCUR_UPDATABLE: Supports updates using ResultSet. Not supported by all JDBC drivers. Call DatabaseMetaData.supportsResultSetConcurrency to know support.

E.g.:

Statement stmt =
con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT a, b FROM EMP");
rs.next();
rs.updateString("NAME", "NewName"); // Update EMP set Name="NewName";

Cursor Holdability:
When connection.commit() is invoked, all ResultSets opened as part of the transaction are, by default, closed. If they are not to be closed, then the ResultSet object's holdability needs to be changed.

HOLD_CURSORS_OVER_COMMIT: When connection.commit() is invoked, do not close the ResultSet objects opened during the connection. Useful with read only result sets.
CLOSE_CURSORS_AT_COMMIT: On connection.commit() close ResultSets. Some applications get performance improvements in doing do.

Use JDBCTutorialUtilities.cursorHoldabilitySupport to determine support for holdability.

These are specified in Connection methods.

Friday, February 11, 2011

Links in Linux

Links help replicate a file to multiple location without creating redundant copies. The links point to the source file (as opposed to copying the file-contents). Any changes done to source file (after linking) are reflected in the links. Dangling links can be created to non-existent files.

There are 2 types of links: Hard links and Symbolic links.

Hard Links
Symbolic Links
Each hard link is a reference to the same i-node number (a key in the i-node table - inode entry for a file can be viewed using stat<<filename>>).
Each symbolic link contains the pathname of the source file.
Source cannot be a directory
Source can be a directory
Source & destination must be in the same file systems (because inode numbers are unique only within one file system)
Source and destination can reside anywhere


e.g.:
~/temp$ ls --inode source.txt # List file with inode number
2131296 source.txt

~/temp$ cp --link source.txt link-copied.txt # a hard link

~/temp$ cp --symbolic-link source.txt symbolic-link-copied.txt # a symbolic link

~/temp$ ls --inode source.txt link-copied.txt symbolic-link-copied.txt
2131296 link-copied.txt 
2131296 source.txt # hard link: i-node numbers of source and destination files are same
2133544 symbolic-link-copied.txt # symbolic link: i-node numbers differ

Tuesday, February 08, 2011

Simple Spring bean configuration

Singular property

Simple property

Class Singer implements Performer

{

private String name;

public Singer(String n)

{

this.name = n;

}

}

<bean

id=”xyz”

class=”com.Singer”>

<constructor-arg

value=”xyz”/>

</bean>

Class Singer implements Performer

{

private String name;

public void setName(String n)

{

this.name = n;

}

}

<bean

id=”xyz”

class=”com.Singer”>

<property

name=”name”

value=”xyz”/>

</bean>

Property referencing another bean

Class Drummer implements Performer

{

private Drum drum;

public Drummer(Drum d)

{

this.drum = d;

}

}

<!-- Tabla implements Drum -->

<bean

id=”tabla”

class=”com.Tabla”>

</bean>

<bean

id=”xyz”

class=”com.Drummer”>

<constructor-arg

ref=”tabla”/>

</bean>


OR


<bean

id=”xyz”

class=”com.Drummer”>

<constructor-arg>

<!-- nested bean -->

<bean

class=”com.Tabla”>

</constructor-arg>

</bean>



Class Drummer implements Performer

{

private Drum drum;

public void setDrum(Drum d)

{

this.drum = d;

}

}

<!-- Tabla implements Drum -->

<bean

id=”tabla”

class=”com.Tabla”>

</bean>

<bean

id=”xyz”

class=”com.Drummer”>

<property

name=”drum”

ref=”tabla”/>

</bean>


OR


<bean

id=”xyz”

class=”com.Drummer”>

<property

name=”drum”>


<!-- nested bean -->

<bean

class=”com.Tabla”>

</property>

</bean>

Plural Property

Collections



Class Drummer implements Performer

{



// REFERENCE TYPE

private Collection<Drum> drums;

OR

private List<Drum> drums;

OR

private Set<Drum> drums;

public setDrums(

Collection<Drum> drums)

{

this.drums = drums;

}






// SIMPLE TYPE

private Collection<String> names;

public setNames(Coll... names)

{

this.names = names;

}

}

<bean id=”drum1” … />

<bean id=”drum2” … />

<bean

id=”xyz”

class=”com.Drummer”>


<!-- REFERENCE TYPE -->

<property

name=”drums”>

<list or set>

<ref bean=”drum1” />

<ref bean=”drum2” />

<bean

class=”com.ADrum”/>

<null />

</list or set>

</property>


<!-- SIMPLE TYPE -->

<property

name=”names”>

<list or set>

<value>Name1</value>

<value>Name2</value>

<null />

</list or set>

</property>

</bean>

Name value pairs



Class Drummer implements Performer

{


// Key and values are objects

private Map<String, Drum> drums;

public setDrums(Map... drums)

{

this.drums = drums;

}








// key & values are strings

private Properties notes;

public setNotes(Properties note)

{

this.notes = note;

}

}

<bean id=”drum1” … />

<bean id=”drum2” … />

<bean

id=”xyz”

class=”com.Drummer”>


<property

name=”drums”>

<map>

<entry

key or key-ref=”drum1”

value or value-ref=”drum1”/>

<entry

key=”drum2”

value-ref=”drum2”/>

</map>

</property>

<property

name=”notes”>

<prop

key=”Note1”>

lala

</prop>

<prop

key=”Note21”>

lolo

</prop>

</property>

</bean>

Monday, February 07, 2011

Iterable interface and "for each" loop

Since Java SE 5.0, the new "for each" loop is supported.

To iterate a Collection, one had to go through the long way as follows:

import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;

class IterationUsingIterator
{
    public static void main(String[] args)
    {
        Collection<String> names = new ArrayList<String>();
        names.add( "Jack" );
        names.add( "Jill" );

        Iterator<String> nameIterator = names.iterator();
        while( nameIterator.hasNext() )
        {
            System.out.println( nameIterator.next() );
        }
    }
}

The same loop using "for each" syntax:

import java.util.Collection;
import java.util.ArrayList;

class IterationUsingForEach
{
    public static void main(String[] args)
    {
        Collection<String> names = new ArrayList<String>();
        names.add( "Jack" );
        names.add( "Jill" );

        for( String name : names)
        {
            System.out.println( name );
        }
    }
}


Question: When can a collection (Collection, Array etc...) participate in "for each" syntax?
Answer: When the collection implements Iterable (with a single method Iterator<T> interator()). These includes Collection, List, Set, SortedSet, Queue and a few more collection sub-interfaces (refer to the javadocs). Arrays also support "for each" syntax. But they do not have a "Is A" relationship with Iterable.

Categorized list of Collection interface methods

Collection interface methods categorized:

Boolean

add(E o)

Methods to add elements to collection

Boolean

addAll(Collection<? Extends E> c)

Void

Clear()

Methods to remove elements from collection

Boolean

remove(Object o)

Boolean

removeAll(Collection<?> c)

Boolean

retainAll(Collection<?> c)

Boolean

contains(Object o)

Methods to check if specific element(s) exist in collection.

Boolean

containsAll(Collection<?> c)

Boolean

IsEmpty()

Methods to check collection at a higher level

Int

Size()

Iterator<E>

Iterator()

Methods to transform the whole collection to other representations

Object[]

ToArray()

<T> T[]

toArray(T[] a)


Saturday, February 05, 2011

Eclipse versions and release years

Helios - 3.6.0 - Released 2010

Galileo - 3.5.2 - 2009

Ganymede - 3.4.2 - 2008

Europa - 3.3.2 - 2007

A treasure chest of mind control techniques based on buddhism

Zencast.org - A treasure chest of mind control techniques based on buddhism

Saturday, January 29, 2011

Sacrifices for change

Sacrifices are needed for change. It is the difficulty/pain that one has in the current situation that makes the sacrifice doable.

Thursday, January 27, 2011

The most happy man

The most happy man is he who knows how to bring into relation the end and beginning of his life.” ~ Johann Wolfgang von Goethe

Abstraction & Encapsulation

Abstraction is the process of coining an interface that specifies all the
essential external behavior of an Object for a given client. This
interface is the external contract upon which the object's client depend
on. Abstraction focuses on the external view of an object and serves to
separate an object's behavior from its implementation.

Abstraction is based on concept of invariance - a boolean condition that
should be true at all times. Each method defines pre-conditions
(invariants the method assumes) and post-conditions (invariants that the
method satisfies).

Encapsulation is hiding of the implementation details of an object. An
object's client is not interested in the implementation details as long
as the implementation complies to the external contract.

Abstraction and Encapsulation are complementary concepts. Abstraction
focuses on the external behavior and encapsulation focuses on the
implementation that gives rise to the external behavior.

Sunday, January 09, 2011

Choosing a path

Choosing a path meant having to miss out on others. She had a whole life to live, and she was always thinking that, in the future, she might regret the choices she made now.
“I’m afraid of committing myself,” she thought to herself.
She wanted to follow all possible paths and so ended up following none. After her first romantic disappointment, she had never again given herself entirely. She feared pain, loss, and separation.
These things were inevitable on the path to love, and the only way of avoiding them was by deciding not to take that path at all.
In order not to suffer, you had to renounce love. It was like putting out your own eyes not to see the bad things in life.

Ever since time began, people have recognized their true Love by the light in their eyes.

“When you find your path, you must not be afraid. You need to have sufficient courage to make mistakes. Disappointment, defeat, and despair are the tools God uses to show us the way.”

“Don’t bother trying to explain your emotions. Live everything as intensely as you can and keep whatever you felt as a gift from God. The best way to destroy the bridge between the visible and invisible is by trying to explain your emotions.”

“But how will I know who my Soulmate is?” Brida felt that this was one of the most important questions she had ever asked in her life.
“By taking risks” she said to Brida. ‘ By risking failure, disappointment, disillusion, but never ceasing in you search for Love. As long as you keep looking, you will triumph in the end.”

Nothing is completely wrong. Even a broken watch is right twice a day.

BRIDA is the real story of a young girl learning to follow the Tradition of the Moon.

- Paulo Coelho

Friday, December 31, 2010

Nicest and sweetest days

“I believe the nicest and sweetest days are not those on which anything very splendid or wonderful or exciting happens, but just those that bring simple little pleasures, following one another softly, like pearls slipping off a string.”

- L. M. Montgomery through Julie911

One-to-one mapping in Hibernate

Introduction:



Using Shared Primary Key:


Using Foreign Key:


Using Join Table:

Thursday, December 09, 2010

You need to keep finding yourself, a little more each day, that real, unlimited you.

You need to keep finding yourself, a little more each day, that real, unlimited Fletcher Seagull. He’s your instructor. You need to understand him and to practice him.

 

-          Richard Bach in “Jonathan Livingston Seagull”

Practice and see ... the good in every one... and to help them see it in themselves

“I don’t understand how you manage to love a mob of birds that just tried to kill you.”

 

“Oh, Fletch, you don’t love that! You don’t love hatred and evil, of course. You have to practice and see the real gull, the good in every one of them, and to help them see it in themselves. That’s what I mean by love. It’s fun, when you get the knack of it.”

 

-          Richard Bach in “Jonathan Livingston Seagull”

Freedom is the very nature of ... being...whatever stands against that freedom must be set aside, be it ritual or superstition or limitation in any form

Freedom is the very nature of ... being...whatever stands against that freedom must be set aside, be it ritual or superstition or limitation in any form

 

-          Richard Bach in “Jonathan Livingston Seagull”

 

You have the freedom to be yourself, your true self, here and now, and nothing can stand in your way. It is the Law

You have the freedom to be yourself, your true self, here and now, and nothing can stand in your way. It is the Law

 

-          Richard Bach in “Jonathan Livingston Seagull”

We're free to go where we wish and to be what we are

…Jonathan said the time had come to return to the Flock.

 

“We’re not ready!... We’re not welcome! We’re Outcast! We can’t force ourselves to go where we’re not welcome, can we?”

 

“We’re free to go where we wish and to be what we are,” Jonathan answered

Easier to practise high performance than it was to understand the reason behind it.

Jonathan’s students found “it was easier… to practice high performance than it was to understand the reason behind it”.

 

-          Richard Bach in “Jonathan Livingston Seagull”

The gull sees furthest who flies highest

“…Those gulls who you came from are standing on the ground, squawking and fighting among themselves. They’re a thousand miles from heaven …they can’t see their wing tips! Stay here. Help the new gulls here, the ones who are high enough to see what you have to tell them.” Jonathan replied “What If Chiang (the master expert gull) had gone back to his old worlds? Where would you have been today?”

Meaning of flight beyond a way of travel to get a breadcrumb

…Jonathan found himself thinking time and again of the Earth from which he had come. If he had known there just a tenth, just a hundredth, of what he knew here, how much more life would have meant! He stood on the sand and fell to wondering if there was a gull back there who might be struggling to break out of his limits, to see the meaning of flight beyond a way of travel to get a breadcrumb from a rowboat. Perhaps there might even have been one made Outcast for speaking his truth in the face of the Flock. And the more Jonathan practiced his kindness lessons, and the more he worked to know the nature of love, the more he wanted to go back to Earth. For in spite of his lonely past, Jonathan Seagull was born to be a instructor, and his own way of demonstrating love was to give something of truth that he had seen to a gull who asked only a chance to see truth for himself.

Perfection

“It’s strange. The gulls who scorn (to despise) perfection for the sake of travel go nowhere, slowly. Those who put aside travel for the sake of perfection go anywhere, instantly….”

 

-          Richard Bach in “Jonathan Livingston Seagull”

Tuesday, November 23, 2010

Good instincts

Good instincts usually tell you what to do long before your head has figured it out.

 

-          Michael Burke

Friday, November 19, 2010

Letting go and holding on

“All the art of living lies in a fine mingling of letting go and holding on.”

- Henry Ellis through Julie911

I walk in peace

“The mind can go in a thousand directions, but on this beautiful path, I walk in peace. With each step, the wind blows. With each step, a flower blooms.”

- Thich Nhat Hanh through Julie911

Monday, October 11, 2010

Slow down and enjoy life

“Slow down and enjoy life. It’s not only the scenery you miss by going too fast — you also miss the sense of where you are going and why.”

- Eddie Cantor through Julie911

Thursday, October 07, 2010

Why is patience so important? Because it makes us pay attention.

“Why is patience so important? Because it makes us pay attention.”

- Paulo Coelho through Julie911

Thursday, September 30, 2010

You’re never given a dream without also being given the power to make it true

“You’re never given a dream without also being given the power to make it true.”

- Richard Bach through Julie911

How people treat you is their karma; how you react is yours.

“How people treat you is their karma; how you react is yours.”

- Wayne W. Dyer through Julie911

The most significant gifts

“The most significant gifts are the ones most easily overlooked. Small, everyday blessings: woods, health, music, laughter, memories, books, family, friends, second chances, warm fireplaces, and all the footprints scattered throughout our days.”

- Sue Monk Kidd

Losing, in a curious way is winning.

“That’s what learning is, after all; not whether we lose the game, but how we lose and how we’ve changed because of it, and what we take away from it that we never had before, to apply to other games. Losing, in a curious way is winning.”

- “The Bridge Across Forever” by Richard Bach through Julie911

Monday, September 27, 2010

Viewing the maven dependency tree

mvn dependency:tree

 

to see the dependency tree of a project

Thursday, September 23, 2010

An introduction to the default maven build lifecycle and the compiler plugin

Download word document file here.

Frequently used mvn targets

Target

Purpose

compile

generate class files from .java files

test

Run test cases. If need be compile main and test source (all source in ${base-dir}/src/test/java confirming to **/*Test.java, **/Test*.java  **/*TestCase.java and excludes **/Abstract*Test.java and **/Abstract*TestCase.java

test-compile

Compile only test source and not execute it

package

Make the jar/war/ear, deploy into target directory

install

deploy the jar/war/ear (build if necessary) into the local repository (~/.m2/repository)

clean

Removes target directory

eclipse:eclipse

Generate eclipse .project files

 

 

Monday, September 13, 2010

Java Generics - Part 4

Wildcards:

 

Consider the a method that prints all the elements of a collection (pre 1.5 code):

 

private static void printCollection(Collection objectCollection)

{

      for (Object element: objectCollection)

      {

            System.out.println( element );

      }

}

 

The above code when invoked as follows:

 

 

printCollection( Arrays.asList( new String[] {"test", "another test"} ) );

 

 

gives the following output:

 

 

test

another test

 

 

Lets write the same method using generics:

 

private static void printCollection(Collection<Object> objectCollection)

{

      for (Object element: objectCollection)

      {

            System.out.println( element );

      }

}

 

But now the same invocation ( printCollection( Arrays.asList( new String[] {"test", "another test"} ) ); ) will lead to a compile time error! :

 

PrintCollection.java:8: printCollection2(java.util.Collection<java.lang.Object>) in PrintCollection cannot be applied to (java.util.List<java.lang.String>)

                 printCollection2( Arrays.asList( new String[] { "test", "another test" }) );

                 ^

1 error

 

This is because when the String[] is converted to a List, it returns a List<String>. And a List<String> is not a List<Object> (although String is a Object. Why? Read this)

 

To resolve this issue, we could use…wildcards as follows:

 

private static void printCollection2(Collection<?> objectCollection)

{

      for (Object element: objectCollection) // compiler error will result for objectCollection.add(anything). Because Collection<?> specifies an unknown element type<terminology>. And the compiler has no way to check the type of “anything” against the unknown type. Null is exception.

      {

            System.out.println( element );

      }

}

 

 

Saturday, September 11, 2010

Java Generics - Part 3

List<Student> is NOT a List<Person>.

Isa relationships do not apply for generics. Why? Check the following listing:


 

1        List<String> nameList = new ArrayList<String>();

2        List<Object> objectList = nameList; // Now objectList is an alias for nameList

3     obecjtList.add( new Student() ); // a Student would have been added to a List<String>


 

Assuming the above code snippet would compile (it will not), it has introduced a Student object into a List of Strings. This violates one of the very basic reasons for having generics (type checking).  So Isa relationships do not work with generics.

BTB, the above code will fail compilation with the following compiler error:


 

NoIsaInGenerics.java:8: incompatible types

found   : java.util.List<java.lang.String>

required: java.util.List<java.lang.Object>

               List<Object> objectList = nameList; // Now objectList is an alias for nameList

                                         ^

NoIsaInGenerics.java:9: cannot find symbol

symbol  : variable obecjtList

location: class NoIsaInGenerics

               obecjtList.add( new Student() ); // a Student would have been added to a List<String>

               ^

2 errors


 

Java Generics - Part 2

A custom parametrized type:

Consider the following oversimplified DAO interfaces:


 

public interface StudentDAO

{

   Student getStudent( Long studentId );

}

 

class Student

{

        private Long id;

        private String name;

        // accessors and mutators

}


 

The above interface is specific for Student. But the same interfaces will hold good for other entities too, like Professor, Course etc... If the interfaces like the above are to be implemented, then there would be a Professor getProfessor( Long professorId ), Course getCourse( Long courseId). This is redundant, violates the DRY (Do not Repeat Yourself) principle. Since there is a getEntity() method is all the cases, the above interface can be written using generics as follows:

 


 

public interface DataAccessInterface<T> // 1 Parameterized type 2 T is formal type paramter

{

        T getEntity( Long EntityKey ); // 3 T can be used where ordinary types can be used

}


The above DAO interface will be used as follows:


 

        DataAccessInterface<Student> studentDAO; // 4 Student is actual type argument


 

Now, DataAccessInterface<T> is a parameterized type, T is the name of the formal type paramter. After T has been declared in the interface declaration, it can be used instead of normal types throughout the interface declaration.

When a reference to a parameterized type is declared (at 4 above), the actual type to be passed to the formal types is also specified. At this time, all occurrences of the formal type (T) will be replaced by the actual type (Student).