Wednesday, March 30, 2011

A Brief for the Defense

Sorrow everywhere. Slaughter everywhere. If babies
are not starving someplace, they are starving
somewhere else. With flies in their nostrils.
But we enjoy our lives because that's what God wants.
Otherwise the mornings before summer dawn would not
be made so fine. The Bengal tiger would not
be fashioned so miraculously well. The poor women
at the fountain are laughing together between
the suffering they have known and the awfulness
in their future, smiling and laughing while somebody
in the village is very sick. There is laughter
every day in the terrible streets of Calcutta,
and the women laugh in the cages of Bombay.
If we deny our happiness, resist our satisfaction,
we lessen the importance of their deprivation
.
We must risk delight. We can do without pleasure,
but not delight. Not enjoyment. We must have
the stubbornness to accept our gladness in the ruthless
furnace of this world. To make injustice the only
measure of our attention is to praise the Devil.
If the locomotive of the Lord runs us down,
we should give thanks that the end had magnitude.
We must admit there will be music despite everything.
We stand at the prow again of a small ship
anchored late at night in the tiny port
looking over to the sleeping island: the waterfront
is three shuttered cafés and one naked light burning.
To hear the faint sound of oars in the silence as a rowboat
comes slowly out and then goes back is truly worth
all the years of sorrow that are to come.

- Jack Gilbert

Master your senses

Master your senses

What you taste and smell
What you see
What you hear

In all things
Be a Master
of what you do
and say
and think
Be Free

Are you quiet?

Calm your body
Calm your mind

By your own efforts

Waken yourself
Watch yourself

And live Joyfully

Follow the truth of The Way

Reflect upon it

Make it your own

Live it

It will always sustain you

- Buddha

Live in Joy

Live in Joy
in Love
Even among those who hate

Live in Joy
in Health
Even among the afflicted

Live in Joy
in Peace
Even among the troubled

Look within
Be still

Free from fear and attachment
Know the sweet joy of the way

- Buddha

Tuesday, March 29, 2011

All that we love deeply becomes a part of us

“What we once enjoyed and deeply loved we can never lose, for all that we love deeply becomes a part of us.”

- Helen Keller through Julie911

Friday, March 11, 2011

Your home team

Everybody has a home team: It’s the people you call when you get a flat tire or when something terrible happens. It’s the people who, near or far, know everything that’s wrong with you and love you anyways.

These are the ones who tell you their secrets, who get themselves a glass of water without asking when they’re at your house.

These are the people who cry when you cry. These are your people, your middle-of-the-night, no-matter-what people.

- “Bittersweet” by Shauna Niequist" through Julie911


Each person deserves a day away in which no problems are confronted, no solutions searched for.

“Each person deserves a day away in which no problems are confronted, no solutions searched for.”

- Maya Angelou through Julie911

Tuesday, March 01, 2011

Class diagram notations and their Java interpretations

Inheritance:


interface list extends Collection;

class ArrayList extends AbstractList;

Realization:


class ArrayList implements List;

Dependency:

When a class has a reference to another class or interface (in instance variables, arguments, local values, return values or anywhere else) then there is a dependency



class DriverManager {
...
Connection getConnection(String url);
...
}


Association:

An association is a special type of dependency. All associations are dependencies. An association is used when the dependency is always there (as opposed to dependency existing only during the course of a method execution). Its more often (not always) used to represent a field in a class. For more information see here.


class Order {
private Customer customer;
}

Monday, February 28, 2011

The best things in life are nearest

“The best things in life are nearest: Breath in your nostrils, light in your eyes, flowers at your feet, duties at your hand, the path of right just before you. Do not grasp at the stars, but do life’s plain, common work as it comes, certain that daily duties and daily bread are the sweetest things in life.”

- Robert Louis Stevenson (1850-1894) through Julie911

Friday, February 25, 2011

Primitive types vs. Boxed Primitives

Java has primitive types like int, short, float, double etc... and reference types like String, Collection etc... Each of the primitive types also has a equivalent reference type. int has Integer, long has Long and so on. These reference types are called Boxed primitives.

Primitive types vs. Boxed Primitives
Primitive Types
Boxed Primitives
Support only functional values (1, 4.5 etc...)
Supports functional values and null
Time and space efficient
Less time and space efficient than primitive types
Have only values. 4 == 4.
Have values and an identity. new Integer(4) != new Integer(4). So avoid using == on boxed primitives

Consider the following code:

public class Test
{
    Integer i; // Initialized to null
    public static void main(String[] args)
    {
        if ( i == 45 ) // 1. auto-unbox i (convert Integer to int) 2. NullPointerException as i value is null.
        {
            System.out.println( "i is 45." );
        }
    }
}

In the above example, i is initialized to null (since its a instance variable). Subsequently, when i == 45 is encountered, i is first auto un-boxed (converted from Integer to int) and this conversion fails because i is null. Fix this by declaring i as int (instead of Integer).

Moral of the story:
Prefer using primitives over boxed types. If using boxed types follow these:
1. Must not be using == operator with boxed types (none of the operands to == must be a boxed type). If used,
a. References are compared, not values and hence results will (in most cases) be wrong.
b. If one operand is primitive and other is boxed primitive, then the boxed primitive is un-boxed. This un-boxing could throw a NullPointerException.
2.
If using boxed types with other operator (like +=), consider overhead involved in auto-boxing and un-boxing. Integer i = 10; i += 2; // un-box value of i, add 2 to unboxed value and box the result back into i. Not efficient.

Use Boxed primitives when:
1. Using parameterized types (list Collection).
Parameterized types do not permit primitives.
2. Using value as a key or value in Collections.
3. Using reflective method invocation (another don't do). e.g. class.forName("java.lang.Integer");

Source: Effective Java by Joshua Bloch

Tuesday, February 22, 2011

Harmony avoids them

Straighten yourself and you will not stand steady;
Display yourself and you will not be clearly seen;
Justify yourself and you will not be respected;
Promote yourself and you will not be believed;
Pride yourself and you will not endure.

These behaviours are wasteful, indulgent,
And so they attract disfavour;
Harmony avoids them.

- Tao Te Ching

Saturday, February 19, 2011

Liberation is sustained by

Liberation is sustained by seeing clearly.
Seeing clearly is sustained by joy, serenity & concentration,
These are sustained by confidence,
Confidence is sustained by association with good spiritual friends

- buddha

Thursday, February 17, 2011

You’ve got to get out ahead of change. You can’t be behind the curve.

"if you are governing these countries, you've got to get out ahead of change. You can't be behind the curve." - Obama on protests in Bahrain.

The lesson: If you must have control, "
you've got to get out ahead of change. You can't be behind the curve."

Wednesday, February 16, 2011

This is to have succeeded

To laugh often and much;
To win the respect of intelligent people and the affection of children;
To earn the appreciation of honest critics and endure the betrayal of false friends;
To appreciate beauty, to find the best in others;
To leave the world a bit better, whether by a healthy child, a garden patch or a redeemed social condition;
To know even one life has breathed easier because you have lived.
This is to have succeeded.

- Ralph Waldo Emerson

Tuesday, February 15, 2011

Java 6 Collection Interfaces and Abstract Classes

The following is a class diagram of Java 6 collection interfaces and abstract classes. The diagram does *not* included concrete implementations (coming soon).

Click on image for detailed view.

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.