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.

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