Friday, June 22, 2012

User Defined Immutable Class - in short


/**
 * Code snippet to make user defined class as Immutable.
 *
 * Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
 * Make all fields final and private.
 * Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final.
 * A more sophisticated approach is to make the constructor private and construct instances in factory methods.
 * If the instance fields include references to mutable objects, don't allow those objects to be changed:
Don't provide methods that modify the mutable objects.
Don't share references to the mutable objects. Never store references to external,
mutable objects passed to the constructor; if necessary, create copies, and store references to the copies.
Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
 */
package com;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Thanooj
 *
 */

final class MyImmutableClass {

private final String firstName;
private final String lastName;
private List namesList;

public MyImmutableClass(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.namesList = new ArrayList();
this.namesList.add(this.firstName);
this.namesList.add(this.lastName);
}

public MyImmutableClass(String afirstName, String aLastName, String agender) {
this.firstName = afirstName;
this.lastName = aLastName;
this.namesList = new ArrayList();
if (agender.equalsIgnoreCase("MISS")) {
this.namesList.add("Miss.");
} else if (agender.equalsIgnoreCase("MISSES")) {
this.namesList.add("Misses.");
} else if (agender.equalsIgnoreCase("M")
|| agender.equalsIgnoreCase("MALE")) {
this.namesList.add("Mr.");
} else {
// nothing TO DO
}
this.namesList.add(this.firstName);
this.namesList.add(this.lastName);
}

public final String getFirstName() {
return firstName;
}

public final String getLastName() {
return lastName;
}

public final List getNamesList() {
/**
* Returns an unmodifiable view of the specified list. This method
* allows modules to provide users with "read-only" access to internal
* lists. if still we try to add elements into this List then it will
* throw an Exception - java.lang.UnsupportedOperationException at java
* .util.Collections$UnmodifiableCollection.add(Collections.java:1018)
*/
return Collections.unmodifiableList(namesList);
}

@Override
public String toString() {
StringBuilder nameBuilder = new StringBuilder();
for (String name : namesList)
nameBuilder = nameBuilder.append(name + " ");
return nameBuilder.toString();
}

}

public class ImmutableObjects {

/**
* @param args
*/
public static void main(String[] args) {

MyImmutableClass myImmutableClassOne = new MyImmutableClass("Srirama",
"Raghu", "M");
System.out.println(myImmutableClassOne);
MyImmutableClass myImmutableClassTwo = new MyImmutableClass("seeta",
"Raghu", "MISSES");
System.out.println(myImmutableClassTwo);
MyImmutableClass myImmutableClassThree = new MyImmutableClass(
"Lakhmana", "Raghu");
System.out.println(myImmutableClassThree);

  List names = myImmutableClassOne.getNamesList();
/**
* trying to add an element to an UnmodifiableCollection.
*/
names.add("throwAnException");

}

}
                                                           // Output :

Wednesday, June 13, 2012

write a Marker interface

package com.example;
interface MarkerInterface {}
Here you have one. Just copypaste it into com/example/MarkerInterface.java, compile and use it!
Here's an usage example:

class SomeClass implements MarkerInterface {
    // ...
}

But, 
You cannot create a marker interface that will have meaning to the JVM, like the java.io.Serializable interface does. However you could create a marker interface that you check for in your own code using instanceof.
However using marker interfaces in this manner is generally discourage now that we have annotations. Marking class methods and fields in various ways for later processing at compile time using the Annotation Processing Tool (apt) or at runtime using reflection is what annotations were created for.
So rather than creating a marker interface and using it like so:
class MyClass implements MyMarkerInterface {
}
You should probably create an annotation and use it like so:
@MyAnnotation
class MyClass {
}
 
---------------------------
The JRE wouldn't know anything about your marker 
interface, so any special treatment would have to happen in the code you
 write. Probably in sections such as 
"if (someObject instanceof 
ExampleMarker) { ... }".

 

 You shouldn't create marker interfaces, though. 
That's what annotations are used for these days.
                             

Tuesday, June 12, 2012

Garbage Collection - finalize()

Syntax (JDK 1.3)
protected void finalize() throws Throwable {}
  • every class inherits the finalize() method from java.lang.Object
  • the method is called by the garbage collector when it determines no more references to the object exist
  • the Object finalize method performs no actions but it may be overridden by any class
  • normally it should be overridden to clean-up non-Java resources ie closing a file
  • if overridding finalize() it is good programming practice to use a try-catch-finally statement and to always call super.finalize() (JPL pg 47-48). This is a saftey measure to ensure you do not inadvertently miss closing a resource used by the objects calling class

protected void finalize() throws Throwable { try {

close  (); // close open files} finally { super.finalize(); }
}


any exception thrown by finalize() during garbage collection halts the finalization but is otherwise ignored
  • finalize() is never run more than once on any object

Sunday, May 27, 2012

spring3 + Tiles2 + Form Validation + I18N

This the Sample Login page Application which includes spring3 + Tiles2 + Form Validation + I18N
download

Thursday, April 26, 2012

Simple Logging Facade for Java (SLF4J)

             The Simple Logging Facade for Java or (SLF4J) serves as a simple facade or abstraction for various logging frameworks, e.g. java.util.logging, log4j and logback, allowing the end user to plug in the desired logging framework at deployment time.
Before you start using SLF4J, we highly recommend that you read the two-page SLF4J user manual.

Note that SLF4J-enabling your library implies the addition of only a single mandatory dependency, namely slf4j-api.jar. If no binding is found on the class path, then SLF4J will default to a no-operation implementation.

SLF4J and and binding against a backend logger
You can only bind against one backend logging framework. With no binding framework on the classpath, the silent logger (NOP) will be used by default.
The frameworks supported by SLF4J:
  • Logback-classic
  • Log4J
  • java.util.logging (JUL)
  • Simple
  • NOP
  • Jakarta Commons Logging (JCL)
The preferred backend logging framework with SLF4J is Logback.

//TestSlf4jClient.java
 


Check all the Project Explorer:
Note: slf4j-api-X.x.x.jar API only exposed to Application by abstracting the back-end logging framework.

 Logback
Logback is written by the same people who have written SLF4J. It natively implements the SLF4J API.
Their description of the framework:
The logback-classic module can be assimilated to a significantly improved version of log4j
A nice feature with Logback is that you can see which jar file that contains a class in the stacktrace. And if the jar file contains an Implemented-Version property in the /META-INF/MANIFEST.MF file, then you can see the version number to the right for the jar file name.

Check out all back-end logging framework outputs:
Logback-Output :
Log4J-Output:

Simple-Output: 
 NOP-Output:
  java.util.logging (JUL)-Output: