Monday, June 14, 2010

How to get time zone as IST instead of GMT+05:30

this will display time zone in short like "IST","GMT" etc

TimeZone.getDefault().getDisplayName(false, TimeZone.SHORT)

Configure Tomcat for Debug

Configure Tomcat for Debug:

1. Open your tomcat admin console: /bin/tomcat5w.exe
C:\Apps\tnl\Tomcat5\bin\tomcat5w.exe

2. Click the Java Tab
Add the following arguments to the Java Options

-Xdebug
-Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n

3. Click the Startup Tab
Add the arguments (on two separate lines, in the order below):
jpda
start
Select Mode -> JVM


After doing above step just run You application in Debug mode

Wednesday, January 27, 2010

jndi configuration with tomcat

Jndi configuration with tomcat example:

http://tomcat.apache.org/tomcat-4.1-doc/jndi-datasource-examples-howto.html

Thanks,
Shekhar.

Monday, January 11, 2010

Can an Innerclass be instantiated in Spring?

Dont be surprise but the answer is yes..

package com.src;
public class MyClass{
public static class InnerClass{
}
}

In spring.xml it Innerclass can be instantiated as:

< bean id="myclass" class="com.src.MyClass$InnerClass">

Wow !! this is good , spring is amazing.The innerclass should be public and static only.

Wednesday, January 6, 2010

Configuring a DataSource in Tomcat

Tomcat makes it easy to set up a connection pool so that servlets and JSPs can efficiently share database connections. In web sites that have many simultaneous users, a connection pool improves efficiency by sharing existing database connections, rather than creating a new connection and tearing it down every time an application has to use the database.

Another benefit of configuring a connection pool is that you can change the database system that a servlet or JSP is using without touching the Java code, because the database resource is configured outside of the servlet or JSP.

Here are the steps for configuring a DataSource with Tomcat:

1. Create a Resource
and a ResourceParams element in server.xml, or in the XML file that you have placed in Tomcat's webapps directory. These elements describe the JNDI object you are creating in order to provide your servlets or JSPs with a DataSource.

2. Add a resource-ref
element to web.xml, which allows the components in the associated web application to access the configured DataSource.

Example below shows the Resource and a ResourceParams elements in server.xml. This example describes a DataSource that connects with an Oracle 8i database.
The resource element in server.xml

"Shareable" type="javax.sql.DataSource" auth=
"Container" description="Home Oracle 8i Personal Edition"/>




driverClassName
oracle.jdbc.driver.OracleDriver



url
jdbc:oracle:thin:@192.168.0.2:1521:ORCL



username
scott



password
tiger



Create a Resource and ResourceParams element for each database that your application uses. Example below shows the resource-ref element associated with the Resource specified by example above.
A resource-ref element specifies a DataSource in web.xml




jdbc/oracle-8i-athletes

javax.sql.DataSource

Container



The JNDI path to this DataSource, which you use in a JNDI lookup (see the next recipe), is jdbc/oracle-8i-athletes.

Monday, January 4, 2010

Implementing hashCode() and equals()

The methods hashCode() and equals() play a distinct role in the objects you insert into Java collections. The specific contract rules of these two methods are best described in the JavaDoc. Here I will just tell you what role they play. What they are used for, so you know why their implementations are important.

equals()

equals() is used in most collections to determine if a collection contains a given element. For instance:

List list = new ArrayList();
list.add("123");

boolean contains123 = list.contains("123");

The ArrayList iterates all its elements and execute "123".equals(element) to determine if the element is equal to the parameter object "123". It is the String.equals() implementation that determines if two strings are equal.

The equals() method is also used when removing elements. For instance:

List list = new ArrayList();
list.add("123");

boolean removed = list.remove("123");

The ArrayList again iterates all its elements and execute "123".equals(element) to determine if the element is equal to the parameter object "123". The first element it finds that is equal to the given parameter "123" is removed.

As you can see, a proper implementation of .equals() is essential for your own classes to work well with the Java Collection classes. So how do you implement equals() "properly"?

So, when are two objects equal? That depends on your application, the classes, and what you are trying to do. For instance, let's say you are loading and processing Employee objects stored in a database. Here is a simple example of such an Employee class:

public class Employee {
protected long employeeId;
protected String firstName;
protected String lastName;
}

You could decide that two Employee objects are equal to each other if just their employeeId's are equal. Or, you could decide that all fields must be equal - both employeeId, firstName and lastName. Here are two example implementation of equals() matching these criterias:

public class Employee {
...
public boolean equals(Object o){
if(o == null) return false;
if(!(o instanceof) Employee) return false;

Employee other = (Employee) o;
return this.employeeId == other.employeeId;
}
}

public class Employee {
...
public boolean equals(Object o){
if(o == null) return false;
if(!(o instanceof) Employee) return false;

Employee other = (Employee) o;
if(this.employeeId != other.employeeId) return false;
if(! this.firstName.equals(other.firstName)) return false;
if(! this.lastName.equals(other.lastName)) return false;

return true;
}
}

Which of these two implementations is "proper" depends on what you need to do. Sometimes you need to lookup an Employee object from a cache. In that case perhaps all you need is for the employeeId to be equal. In other cases you may need more than that - for instance to determine if a copy of an Employee object has changed from the original.

hashCode()

The hashCode() method of objects is used when you insert them into a HashTable, HashMap or HashSet. If you do not know the theory of how a hashtable works internally, you can read about hastables on Wikipedia.org.

When inserting an object into a hastable you use a key. The hash code of this key is calculated, and used to determine where to store the object internally. When you need to lookup an object in a hashtable you also use a key. The hash code of this key is calculated and used to determine where to search for the object.

The hash code only points to a certain "area" (or list, bucket etc) internally. Since different key objects could potentially have the same hash code, the hash code itself is no guarantee that the right key is found. The hashtable then iterates this area (all keys with the same hash code) and uses the key's equals() method to find the right key. Once the right key is found, the object stored for that key is returned.

So, as you can see, a combination of the hashCode() and equals() methods are used when storing and when looking up objects in a hashtable.

Here are two rules that are good to know about implementing the hashCode() method in your own classes, if the hashtables in the Java Collections API are to work correctly:

1. If object1 and object2 are equal according to their equals() method, they must also have the same hash code.
2. If object1 and object2 have the same hash code, they do NOT have to be equal too.

In shorter words:

1. If equal, then same hash codes too.
2. Same hash codes no guarantee of being equal.

Here are two example implementation of the hashCode() method matching the equals() methods shown earlier:

public class Employee {
protected long employeeId;
protected String firstName;
protected String lastName;

public int hashCode(){
return (int) this.employeeId;
}
}

public class Employee {
protected long employeeId;
protected String firstName;
protected String lastName;

public boolean equals(Object o){
return (int)this.employeeId *
firstName.hashCode() *
lastName.hashCode();
}
}

Notice, that if two Employee objects are equal, they will also have the same hash code. But, as is especially easy to see in the first example, two Employee objects can be not equal, and still have the same hash code. In the first example the hash code is the employeeId is rounded down to an int. That means that many employee id's could result in the same hash code, but these Employee objects would still not be equal, since they don't have the same employee id.

Complete generic examples

Generic examples available here(check all example in right side index)

http://tutorials.jenkov.com/java-generics/generic-list.html

Tuesday, December 29, 2009

What is difference between HashMap and HashTable?

Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are

1. Access to the Hashtable is synchronized on the table while access to the HashMap isn’t. You can add it, but it isn’t there by default.

2. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t. If you change the map while iterating, you’ll know. • Fail-safe – “if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException”

3. HashMap permits null values and only one null key, while Hashtable doesn’t allow key or value as null.

Use of hashcode() and equals() in java

Use of hashCode() and equals().

Object class provides two methods hashcode() and equals() to represent the identity of an object. It is a common convention that if one method is overridden then other should also be implemented.

Before explaining why, let see what the contract these two methods hold. As per the Java API documentation:

*
Whenever it is invoked on the same object more than once during an execution of a Java application, the hashcode() method must consistently return the same integer, provided no information used in equals() comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
*
If two objects are equal according to the equals(object) method, then calling the hashCode() method on each of the two objects must produce the same integer result.
*
It is NOT required that if two objects are unequal according to the equals(Java.lang.Object) method, then calling the hashCode() method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

Now, consider an example where the key used to store the in Hashmap is an Integer. Consider that Integer class doesn’t implement hashcode() method. The code would look like:

map.put(new Integer(5),”Value1″);
String value = (String) map.get(new Integer(5));
System.out.println(value);
//Output : Value is null

Null value will be displayed since the hashcode() method returns a different hash value for the Integer object created at line 2and JVM tries to search for the object at different location.

Now if the integer class has hashcode() method like:

public int hashCode(){
return value;
}

Everytime the new Integer object is created with same integer value passed; the Integer object will return the same hash value. Once the same hash value is returned, JVM will go to the same memory address every time and if in case there are more than one objects present for the same hash value it will use equals() method to identify the correct object.

Another step of caution that needs to be taken is that while implementing the hashcode() method the fields that are present in the hashcode() should not be the one which could change the state of object.

Consider the example:

public class FourWheeler implements Vehicle {



private String name;

private int purchaseValue;

private int noOfTyres;

public FourWheeler(){}



public FourWheeler(String name, int purchaseValue) {

this.name = name;

this.purchaseValue = purchaseValue;

}

public void setPurchaseValue(int purchaseValue) {

this.purchaseValue = purchaseValue;

}



@Override

public int hashCode() {

final int prime = 31;

int result = 1;

result = prime * result + ((name == null) ? 0 : name.hashCode());

result = prime * result + purchaseValue;

return result;

}

}

FourWheeler fourWObj = new FourWheeler(“Santro”,”333333);
map.put(fourWObj,”Hyundai);
fourWObj.setPurchaseValue(“555555)
System.out.println(map.get(fourWObj));
//Output: null

We can see that inspite of passing the same object the value returned is null. This is because the hashcode() returned on evaluation will be different since the purchaseValue is set to ‘555555’ from ‘333333’. Hence we can conclude that the hashcode() should contain fields that doesn’t change the state of object.

One compatible, but not all that useful, way to define hashCode() is like this:

public int hashcode(){
return 0;
}

This approach will yield bad performance for the HashMap. The conclusion which can be made is that the hashcode() should(not must) return the same value if the objects are equal. If the objects are not equal then it must return different value.

Overriding equals() method

Consider the example:

public class StringHelper {



private String inputString;



public StringHelper(String string) {

inputString=string;

}



@Override

public int hashCode() {

return inputString.length();

}





public static void main(String[] args) {



StringHelper helperObj = new StringHelper(“string”);

StringHelper helperObj1 = new StringHelper(“string”);

if(helperObj.hashCode() == helperObj1.hashCode()){

System.out.println(“HashCode are equal”);

}

if(helperObj.equals(helperObj1)){

System.out.println(“Objects are equal”);

}else{

System.out.println(“Objects are not equal”);

}



}



public String getInputString() {

return inputString;

}



// Output:
HashCode are equal
Objects are not equal

We can see that even though the StringHelper object contains the same value the equals method has returned false but the hashcode method has return true value.

To prevent this inconsistency, we should make sure that we override both methods such that the contract between both methods doesn’t fail.

Steps that need to be taken into consideration while implementing equals method.

1. Use the == operator to check if the argument is a reference to this object. If so, return true. This is just a performance optimization, but one that is worth doing if the comparison is potentially expensive.

2. Use the instanceof operator to check if the argument has the correct type.

If not, return false. Typically, the correct type is the class in which the method occurs. Occasionally, it is some interface implemented by this class. Use an interface if the class implements an interface that refines the equals contract to permit comparisons across classes that implement the interface. Collection interfaces such as Set, List, Map, and Map.Entry have this property.

3. Cast the argument to the correct type. Because this cast was preceded by an instanceof test, it is guaranteed to succeed.

4. For each “significant” field in the class, checks if that field of the argument matches the corresponding field of this object. If all these tests succeed, return true; otherwise, return false

5. When you are finished writing your equals method, ask yourself three questions: Is it symmetric? Is it transitive? Is it consistent?

The correct implementation if equals method for the StringHelper class could be:

@Override

public boolean equals(Object obj) {

if (this == obj)

return true;

if (obj == null)

return false;

if (getClass() != obj.getClass())

return false;

final StringHelper other = (StringHelper) obj;

if (inputString == null) {

if (other.inputString != null)

return false;

} else if (!inputString.equals(other.inputString))

return false;

return true;

}

How HashSet works?

Yes, earlier i wasnt sure how HashSet is created internally and which data structure is used. But when I looked at the class implemenation i was surprised because of following features i noticed:

Hashset is used to store the unique elements, in which their is no gurantee of the iteration order.

Hashset internally use HashMap .

Elements passed to Hashset are stored as a key of the HashMap with null as value. Since the objects passed to set are key so no extra check is done to identify duplicates. For eg after adding integer 1 and 2 if i add 1 again, no check is performed to identify whether 1 is present or not. The hashset simply performs the put with the same value( ‘1′) in this case as key.

Similariy when an element is removed from the Set the internal HashMap remove method is called.

So HashSet data structure is nothing but a HashMap with objects as key.

HashSet Implemenation from java.util package

1. public HashSet() {
map = new HashMap();
}
2. public boolean add(E o) {
return map.put(o, PRESENT)==null;
}
3. /**
* Removes the specified element from this set if it is present.
*
* @param o object to be removed from this set, if present.
* @return true if the set contained the specified element.
*/
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}

How to create Immutable Class?

mmutable class is a class which once created, it’s contents can not be changed and cannot be inherited. Immutable objects are the objects of immutable class whose state can not be changed once constructed. e.g. String class

To create an immutable class following steps should be followed:

1. Create a final class.
2. Set the values of properties using constructor only.
3. Make the properties of the class final and private
4. Do not provide any setters for these properties.
5. If the instance fields include references to mutable objects, don’t allow those objects to be changed:
1. Don’t provide methods that modify the mutable objects.
2. 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.

E.g.
public final class FinalPersonClass {

private final String name;
private final int age;

public FinalPersonClass(final String name, final int age) {
super();
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}

All wrapper classes in java.lang are immutable –
String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger

java.lang.OutOfMemoryError while doing ant build?

While doing an ant build sometimes it happen that a user may get the OutOfMemoryError. This is mainly because the heap size of Java JVM is less. This heap size can be increased. But caution that the heap size of java JVM which is running through Ant has to be increased and not of the JVM of Jdk 1.x .

To increase the heap size of JVM in ant ,open the file ant.cmd present in Ant/bin folder.

Change following line

“%_JAVACMD%” %ANT_OPTS% -classpath “%ANT_HOME%\lib\ant-launcher.jar” “-Dant.home=%ANT_HOME%” org.apache.tools.ant.launch.Launcher %ANT_ARGS% -cp “%CLASSPATH%” %ANT_CMD_LINE_ARGS%

“%_JAVACMD%” -Xms512m -Xmx1024m %ANT_OPTS% -classpath “%ANT_HOME%\lib\ant-launcher.jar” “-Dant.home=%ANT_HOME%” org.apache.tools.ant.launch.Launcher %ANT_ARGS% -cp “%CLASSPATH%” %ANT_CMD_LINE_ARGS%
Rate This

Tuesday, November 17, 2009

Quartz security

Batch solutions are ideal for processing that is time and/or state based:

* Time-based: The business function executes on a recurring basis, running at pre-determined schedules.
* State-based: The jobs will be run when the system reaches a specific state.

Batch processes are usually data-centric and are required to handle large volumes of data off-line without affecting your on-line systems. This nature of batch processing requires proper scheduling of jobs. Quartz is a full-featured, open source job scheduling system that can be integrated with, or used along side virtually any Java Enterprise of stand-alone application. The Quartz Scheduler includes many enterprise-class features, such as JTA transactions and clustering. The following is a list of features available:
Skip to Sample Code

* Can run embedded within another free standing application
* Can be instantiated within an application server (or servlet container).
* Can participate in XA transactions, via the use of JobStoreCMT.
* Can run as a stand-alone program (within its own Java Virtual Machine), to be used via RMI
* Can be instantiated as a cluster of stand-alone programs (with load-balance and fail-over capabilities)
* Supoprt for Fail-over
* Support for Load balancing.

The following example demonstrates the use of Quartz scheduler from a stand-alone application. Follow these steps to setup the example, in Eclipse.

1. Download the latest version of quartz from opensymphony.
2. Make sure you have the following in your class path (project-properties->java build path):
* The quartz jar file (quartz-1.6.0.jar).
* Commons logging (commons-logging-1.0.4.jar)
* Commons Collections (commons-collections-3.1.jar)
* Add any server runtime to your classpath in eclipse. This is for including the Java transaction API used by Quartz. Alternatively, you can include the JTA class files in your classpath as follows
1. Download the JTA classes zip file from the JTA download page.
2. Extract the files in the zip file to a subdirectory of your project in Eclipse.
3. Add the directory to your Java Build Path in the project->preferences, as a class directory.
3. Implement a Quartz Job: A quartz job is the task that will run at the scheduled time.

public class SimpleJob implements Job

4.

{

5.

public void execute(JobExecutionContext ctx) throws JobExecutionException {

6.

System.out.println("Executing at: " + Calendar.getInstance().getTime() + " triggered by: " + ctx.getTrigger().getName());

7.

}

8.

}

SimpleJob.java
9. The following piece of code can be used to run the job using a scheduler.

public class QuartzTest {

10.

public static void main(String[] args) {

11.

try {

12.

// Get a scheduler instance.

13.

SchedulerFactory schedulerFactory = new StdSchedulerFactory();

14.

Scheduler scheduler = schedulerFactory.getScheduler();

15.

long ctime = System.currentTimeMillis();

16.

// Create a trigger.

17.

JobDetail jobDetail = new JobDetail("Job Detail", "jGroup", SimpleJob.class);

18.

SimpleTrigger simpleTrigger = new SimpleTrigger("My Trigger", "tGroup");

19.

simpleTrigger.setStartTime(new Date(ctime));

20.

// Set the time interval and number of repeats.

21.

simpleTrigger.setRepeatInterval(100);

22.

simpleTrigger.setRepeatCount(10);

23.

// Add trigger and job to Scheduler.

24.

scheduler.scheduleJob(jobDetail, simpleTrigger);

25.

// Start the job.

26.

scheduler.start();

27.

} catch (SchedulerException ex)

28.

{ ex.printStackTrace();

29.

}

30.

}

31.

}