Anything that interests me finds place here. Software dominates my interests and hence a good part of this blog as well.
Thursday, September 30, 2010
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
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).
Saturday, August 28, 2010
The most important part of your life
- Lost
We can't let other people decide who you are
you have to decide that for yourself
-Lost
Sunday, August 22, 2010
Superiority should be such a big burden to carry
Wednesday, August 04, 2010
Java Generics - Part 1
Generics were introduced in JDK 5.0. Generics help write re-usable code without losing type safety. Type safety helps write robust programs. The most common usage of generics is in the collections API.
Prior to generics, a Collection could theoretically hold values of various types. Like so:
import java.util.Collection;
import java.util.LinkedList;
class Generics1
{
public static void main(String[] args)
{
Collection nameList = new LinkedList();
nameList.add( new Integer(0) ); // 1 Integer added to collection
nameList.add( "test" ); // 2 String added to collection
System.out.println( nameList );
}
}
Compiling the above code with JDK 5.0 and above will result in a “warning”. But the class file does get generated. Like so:
$ javac Generics1.java
Note: Generics1.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Running the class file does give the following output:
$ java Generics1
[0, test]
But now we have a Collection with a Integer and a String. Its highly un-likely that a programmer would expect to see a Integer in a nameList.
To enforce type safety that the nameList can only hold String instances, change the declaration of nameList like so:
import java.util.Collection;
import java.util.LinkedList;
class Generics1
{
public static void main(String[] args)
{
Collection<String> nameList = new LinkedList<String>();
nameList.add( new Integer(0) ); // Violation (Integer added to String collection) caught by compiler.
nameList.add( "test" );
System.out.println( nameList );
}
}
Now, the compiler checks each operation on the Collection and ensures that only Strings find place in the Collection (type correctness). Compilation fails if there are violations (like above):
$ javac Generics1.java
Generics1.java:8: add(java.lang.String) in java.util.Collection<java.lang.String> cannot be applied to (java.lang.Integer)
nameList.add( new Integer(0) );
^
1 error
Since all Collection elements are held as java.lang.Object in a non-generic Collection, all fetches must be cast to the appropriate type. Failing to do so will result in a compilation failure. Like so:
import java.util.List;
import java.util.LinkedList;
class Generics1
{
public static void main(String[] args)
{
List nameList = new LinkedList();
nameList.add( "test" );
String firstName = nameList.get(0);
System.out.println( firstName );
}
}
$ javac Generics1.java
Generics1.java:9: incompatible types
found : java.lang.Object
required: java.lang.String
String firstName = nameList.get(0);
^
Note: Generics1.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
This issue can be resolved by explicitly casting the assignment or typing the collection with generics like so:
List<String> nameList = new LinkedList<String>();
$ java Generics1
Test
In the above case, List is a generic interface with a type parameter.
Thursday, July 22, 2010
A friend who cares
“When we honestly ask ourselves which person in our lives mean the most to us, we often find that it is those who, instead of giving advice, solutions, or cures, have chosen rather to share our pain and touch our wounds with a warm and tender hand. The friend who can be silent with us in a moment of despair or confusion, who can stay with us in an hour of grief and bereavement, who can tolerate not knowing, not curing, not healing and face with us the reality of our powerlessness, that is a friend who cares.”
- Henri J.M. Nouwen
Friday, July 09, 2010
JSF request processing lifecycle in brief
1. Restore View Phase: For a new/fresh request, this phase creates a component tree starting with the UIViewRoot. For a post back request (a request from a previously generated JSF response), the component tree is restored (when state saving method is client, the tree is de-serialized from the request. When state saving method is server, the tree is restored from the server’s cache).
2. Apply Request Values Phase: The values held in the request are fetched and set on the appropriate components. At the end of this phase, the component tree has all the value submitted in the request. The server invokes processDecodes() on UIViewRoot and that call trickles down the entire tree invoking the decode() method on each component. ValueHolder and EditableValueHolder components update the component values and AcionSource components queue an ActionEvent for processing in further phases. If immediate attribute is “true”, validation happens at this phase.
3. Process Validation Phase: All component in the tree convert and validate their values (that was set in step 2). The server invokes processValidators() on the UIViewRoot (and that in-turn recursively invokes processValidators() on each component). Each component’s processValidators() invokes the converter and validators associated with the component. If a component fails conversion or validation, its valid property is set to false and a FacesMessage is queued (and rendered in render response phase).
4. Update Model Values Phase: The backing beans are updated with validated values in the component tree. The server invokes processUpdates() on UIViewRoot which invokes processUpdates() on each component. The processUpdates() method of UIInput types will invoke updateModel() which will update the backing bean.
5. Invoke Application Phase: Any action method or actionListener methods are invoked in this phase. In phase 2 these components would have queued an ActionEvent. The server invokes the processApplication() on UIViewRoot. This method will invoke the broadcast() method on each ActionSource in the component tree for each queued ActionEvent.
6. Render Response Phase: The encodeXX() method on each component is invoked. Each method uses its renderer to generate response and persist the component state so that it can restored in a future request.
Wednesday, July 07, 2010
ui:debug to inspect JSF component tree and UI state
On several occasions, it would be handy to view the component tree and view state.
The <ui:debug..> makes this possible. Using the plain tag with no attributes specified is the most simplest usage:
<ui:debug />
To view the The component tree, load the page holding this tag and press Ctrl+shift+d. This should bring up a new window. But Ctrl+shift+d happens to be a browser shortcut for “Organize bookmarks” in Firefox and the “Bookmark Manager” in Google Chrome. So we need to change the default hotkey which is done as follows:
<ui:debug rendered="true" hotkey="o"/>
Now reload the page and press Ctrl+shift+o. Now a new window opens with the “Component Tree” and “Scoped Variables”.
1. The component tree gives a inundated lists all UI components starting with UIViewRoot.
2. The scoped variables lists various beans in various scopes (e.g. Request Parameters, View Attributes, Request Attributes, Session Attributes, Application Attributes)
The rendered attribute can be used to turn off this feature in production.
Tuesday, July 06, 2010
String.split() trivia
The String.split() method converts a given string to an array based on a regular expression.
Examples:
System.out.println( Arrays.toString( "0:1::::".split( "[:]" ) ) ); // Output: [0, 1]
System.out.println( Arrays.toString( "::::4:5".split( "[:]" ) ) ); // Output: [, , , , 4, 5]
System.out.println( Arrays.toString( "0:1::::".split( "[:]", -1 ) ) ); // Output: [0, 1, , , , ]
As the documentation notes, “blah”.split(“:”) is the same as “blah”.split(“:”, 0) which does not include trailing empty strings.
Tuesday, June 29, 2010
Internet connection speeds
Internet connectivity technologies – fastest to slowest
1. Fiber optics
2. Cable
3. DSL
4. Dish
5. Dial-up
Friday, June 25, 2010
Unchecking a html radio button
Given the following code,
<input type="radio" value="PG" name="courseType" /> Post Graduate </input>
<input type="radio" value="UG" name="courseType" /> Under Graduate </input>
To check the "PG" html radio button in jQuery:
jQuery(blahBlahBlah).attr('checked', 'true');
To uncheck it:
jQuery(blahBlahBlah).removeAttr('checked');
Note: the following will **NOT WORK**
jQuery(blahBlahBlah).attr('checked', 'false');
jQuery(blahBlahBlah).attr('checked', '');