Friday, July 30, 2010

Better way of using Lists in loops


Target audience: Beginners

As I always believe, we can think of in anyways to improve the performance of our application. In this post, I explain how we can use loops effectively for list iteration. In most of my projects, I have seen developers code list iteration as follows

for (int j = 0; j < aList.size(); j++) {
....
}

There is nothing wrong in this code can change this piece of code to perform well. If you see carefully, the aList.size() will be invoked every time before the next iteration of loop starts. So, what we can do is, we can assign the size of the list to a variable and use that variable inside the loop. Check the code bellow

int size = aList.size();
for (int j = 0; j < size; j++) {
....
}

This will improve the performance a bit. I can prove this by running the following benchmarking program.

package basics;

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

public class ListSizeExample {
public static void main(String[] args) {

long start = 0;
long end = 0;
List aList = new ArrayList();
for (int i = 0; i < 50; i++) {
aList.add(i);
}

// Using list.size() in the loop
start = System.nanoTime();
for (int i = 0; i < 100; i++) {
for (int j = 0; j < aList.size(); j++) {

}
}
end = System.nanoTime();
System.out.println("Using aList.size(): " + (end - start) / 100);

// Using size, size is assigned with value of list.size()
start = System.nanoTime();
for (int i = 0; i < 100; i++) {
int size = aList.size();
for (int j = 0; j < size; j++) {
}
}
end = System.nanoTime();
System.out.println("Using size: " + (end - start) / 100);
}
}

I have an outer loop for each benchmark code block which runs 100 times and this is just to get the average time taken for the actual loop. If you run the code, you will get an output similar to the following one

Using aList.size(): 3765
Using size: 1256

This proves that the code perform better with a assigned value of length then directly using the list.size() inside the loop

Wednesday, July 28, 2010

Improve the Application’s performance by using primitive constants


Target audience: Beginners

We use hundreds of constants in our application. It’ll be even thousands in a large scale projects. These constants are used again and again at runtime. Improving the performance of an application in any ways is advisable.So, it will be great if we can think about improving the performance while using constants.
I would suggest using primitive constants where ever it is possible than using String constants. It is advisable not only for better memory usage but also for better performance. The following benchmark program shows the difference. The most possible usage of constants is comparison. So i use comparison for benchmarking.

package basics;

public class ConstantsExample {

public static final int RED = 1;
public static final int GREEN = 2;

public static final String SRED = "RED";
public static final String SGREEN = "GREEN";

// Main methods
public static void main(String[] args) {
long start = 0;
long end = 0;
int red = 1;
String sred = "RED";

// Benchmark primitive constants
start = System.nanoTime();
for (int i = 0; i < 100; i++) {
if (RED == red) {
}
}
end = System.nanoTime();
System.out.println("Primitive comparision: "+ (end - start));

// Benchmark String constants
start = System.nanoTime();
for (int i = 0; i < 100; i++) {
if (SRED.equals(sred)) {
}
}
end = System.nanoTime();
System.out.println("String comparision: "+(end - start));
}
}

If you run this program then you will get the results similar to bellow one

Primitive comparision: 4610
String comparision: 21721

Looks good ha!

Monday, July 26, 2010

Runtime Polymorphism and Compile time Polymorphism is explained


Target audience: Beginners

Let’s look at some basics before get into details

What is polymorphism?
Polymorphism is one in many forms. That’s it. We can see lots of examples in real time. If you think about a Dog, A Dog is an Animal. A Dog can be a pet. So a Dog can be in
many forms. The Dog is Animal type and it can be another type of Pet.
Apart from types, behaviours can also take part of Polymorphism. For Example, Animals can swim. A Dog can swim, A Monkey also can swim. Dog and Monkey has their own way of swimming. Here, the swimming behavior is in many forms. A monkey can walk with two legs and also with four legs. Here, walking behaviour is in many forms. These are the examples for polymorphism in real world.

Let’s see how Polymorphism works in Java. Polymorphism allows you define a Super type and have multiple subtype implementations. There Are Two Types of Polymorphism in Java. One is compile time Polymorphism and it is sometimes referred as static Polymorphism and the other one is Runtime Polymorphism and it is sometimes referred as dynamic Polymorphism

Runtime Polymorphism
As we can have multiple subtype implementations for a super type, Java virtual machine determines the proper type to be invoked at the runtime. Method overriding is a runtime polymorphism. For example look at the following example. I have Worker interface(Super type) and have Teacher and Principal classes ( Subtypes) that implements the Worker interface .The Worker interface has a method doIt() and the subtypes implements that method.


// Worker class
interface Worker {
public void doIt();
}

// Teacher class
class Teacher implements Worker {
public void doIt() {
System.out.println("Teacher does the work");
}
}

//Principalclass
class Principal implements Worker {
public void doIt() {
System.out.println("Principal does the work");
}
}

Now I’m going to have another class which has a main method. The main method creates a List and adds a Principal instance and a Teacher instance to that list. Then it iterates through the list, refer the instances by their super type and calls the doit() method on the Super type reference

public class PolymorphismExample {

public static void main(String[] args) {
List workers = new ArrayList();

//Adding worker one
Worker worker1 = new Principal();
workers.add(worker1);

//Adding worker two
Worker worker2 = new Teacher();
workers.add(worker2);

for (Iterator iterator = workers.iterator(); iterator.hasNext();) {
Worker worker = (Worker) iterator.next();
worker.doIt();
}

}
}

If you run the PolymorphismExample class then the output will be

Principal does the work
Teacher does the work

If you see carefully, we cannot see which instance is called. We called doIt() method only on the Super type Worker but the JVM finds the proper type and called its implementation of doIt() method. This is Runtime Polymorphism. The JVM determines proper type only at runtime

Compile time Polymorphism
Method overloading is a compile time Polymorphism. As we can have multiple subtype implementations for a super type, the compiler determines which type to be invoked at the compile time. For example look at the following example. I’m going to change PolymorphismExample class to have some overloaded methods

public class PolymorphismExample {

public void doSomething(Worker worker) {
System.out.println("I'm a worker");
}

public void doSomething(Teacher teacher) {
System.out.println("I'm a Teacher");
}

public void doSomething(Principal principal) {
System.out.println("I'm a Principal");
}

public static void main(String[] args) {

PolymorphismExample example = new PolymorphismExample();
Worker principal = new Principal();
Worker teacher = new Teacher();

example.doSomething(principal);
example.doSomething(teacher);
}
}

You would expect the output as bellow, If you run the PolymorphismExample class

I'm a Principal
I'm a Teacher

WRONG, the actual output will be

I'm a worker
I'm a worker

Here the type is decided at compile time. Even though the objects are instances of Principal and Teacher, the reference is a Worker type. So the compiler picks the doSomething(Worker worker) method as it accepts the same type of reference type (Worker).
So keep it in mind when you use method overloading.

Tuesday, July 20, 2010

Instanceof operator kills Object Oriented Programming


Target audience: Beginners

Everybody knows about instanceof operator of Java. I just give a simple description about instanceof operator before get into details. The instanceof operator allows a user to check whether an object is an instance of a particular type.The type could be a class or an interface.

if (obj instanceof type) {
type new_name = (type) obj;
}

Here the obj is an instance of the type then, the condition will be true , else it will be false. This condition will also become false if obj is a null. So better to be careful while using it.

I personally feel that sometimes the instanceof operator is missused and it kind of kills the object oriented concept. Let me explain by taking a simple example similar to what we deal with everyday

Suppose we have abstact class Person and two other sub classes Student and Teacher

abstract class Person {
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

class Student extends Person {
void study() {
}
}

class Teacher extends Person {
void teach() {
}
}

Appart from the inherited methods, Student has a method study() and Teacher has a method teach(). Suppose if there is a situation that we have a list of mixed objects of Student and Teacher and we need to call their own methods. We might write a code similar to the following one.

List list = new ArrayList();
list.add(new Teacher());
list.add(new Student());

for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Object object = (Object) iterator.next();
if (object instanceof Student) {
Student obj = (Student) object;
obj.study();
} else if (object instanceof Teacher) {
Teacher obj = (Teacher) object;
obj.teach();
}
}

This is the way we use the instanceof operator. We can get rid of this if we apply some Object oriented concept.What I'm going to do is, I’m going to change the Person,Student and Teacher classes a bit

abstract class Person {
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

abstract void doYourWork();
}

class Student extends Person {

void study() {
}

void doYourWork() {
study();
}
}

class Teacher extends Person {
void teach() {
}

void doYourWork() {
teach();
}
}

I added a abstract method doYourWork() in Person class and let the sub classes Student and Teacher to implement it and call their own methods inside their implementation of doYourWork() method. Now i’m going to change the iterating part also.

List list = new ArrayList();
list.add(new Teacher());
list.add(new Student());

for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Person object = (Person) iterator.next();
object.doYourWork();
}

Wow... the instance of operator is gone and code looks pretty too. I just applied a simple OO concept and got rid of the instanceof operator. This is why i mentioned “I personally feel that sometimes the instanceof operator is missused and it kind of kills the object oriented concept.”

Monday, July 19, 2010

Return Empty Collection than null if there is nothing to return


Target audience: Beginners

Every day we come across at least a method that would return a list of objects or null.For example see the following code block.

Employee employee = ....
List children = employee.getChildren();
if (children != null) {
for (Child child : children) {
// do something....
}
}

Here, the getChildren() of Employee is prone to error because it would return null object. The caller always need to check null before proceeding the returned list. We can try to reduce these situation by returning an empty list if there are nothing to return when a list is expected to be returned. Suppose if the getChildren() return empty list if there is nothing to return, then the caller’s code will be as bellow

Employee employee = ....
List children = employee.getChildren();
for (Child child : children) {
// do something....
}

This looks neat and reduces the possibilities to make errors.

Some people might say that creating an Empty list and returning every time if there is nothing to return, will be costly and unnecessarily creating objects. True, and we are not going to create empty object every time. Collections API has static final empty list which can be used to return instead. Look at code shown bellow to know how it can be done

class Employee {
public List getChildren() {
...
if(children == null){
return Collections.EMPTY_LIST;
}
....
}
...
}
This style can be used for any other collections and of course arrays too. It's not restricted only to List

Saturday, July 17, 2010

How to use ThreadLocal


Target audience: Beginners and Intermediates

ThreadLocal is a class provides way to hold thread local variables and provide access to get and set values. in other words, it allows you to have copy of variables per thread and these variables will be garbage collected when the associated thread dies. ThreadLocal instances are advised to be private static fields in classes.For example, check the Audit class bellow
class Audit {
private static ThreadLocal auditDetails = new ThreadLocal();

public static String get() {
return (String) auditDetails.get();
}

public static void set(String details) {
auditDetails.set(details);
}
}

Here, auditDetails is a thread local variable. The set(String) method of Audit class sets a value in thread local variable auditDetails. As auditDetails is a static, it will be shared with multiple threads but the value which is set will belong to only the current thread.The JVM finds the current thread and associate the value. And when get(String) method of Audit is called, the auditDetails returns the value associated with current thread. The following example will help you to understand it more.

package basics;

public class ThreadLocalExamples {

public void methodA() {

//Generates a random value
int value = (int)(Math.random()*100);

//Prints the current thread and the generated random value
System.out.println("Setting " +value+ " to " +Thread.currentThread().getName());

//Set the random value as audit details
Audit.set(String.valueOf(value));

//Keeping the threads on sleep mode for some time
try {
Thread.sleep(value);
} catch (InterruptedException e) {
e.printStackTrace();
}
methodB();
}

public void methodB() {

//Just prints the audit details value set for the current thread
System.out.println(Thread.currentThread().getName()+":"+Audit.get());
}

public static void main(String[] args) {

final ThreadLocalExamples examples = new ThreadLocalExamples();

//Creates thread one and call methodA() on examples
Thread threadOne = new Thread() {
public void run() {
examples.methodA();
}
};

//Creates thread two and call methodA() on the same instance examples
threadOne.setName("ThreadOne");
Thread threadTwo = new Thread() {
public void run() {
examples.methodA();
}
};
threadTwo.setName("ThreadTwo");

//Starting the threads
threadOne.start();
threadTwo.start();
}
}
if you look at the code, there are two methods methodA() and methodB().The methodA() generates a random number and set it as audit details and calls the methodB().The static method set(string) in Audit class is called to set audit details to the thread local .The methodB() gets the audit details and prints it. The static method get() in Audit class is called to get audit details from thread local. The main method creates creates one instance of ThreadLocalExamples and two instances of threads. Both thread instances call the methodA() of same instance of ThreadLocalExamples in their run() method.
Note: The same instance of ThreadLocalExamples is accessed by two threads at the same time.
If you run the program, you will get something like the following output
Setting 13 to ThreadOne
Setting 67 to ThreadTwo
ThreadOne:13
ThreadTwo:67


if you analyze the output results, Thread one sets ‘13 ‘ to thread local, then Thread two sets ‘67 ‘ to thread local.Even though both threads access the same thread local instance to set the value. the values are set to the current thread’s local values. That’s why when it prints the value, the value associated to the current thread is retrieved and printed.

So one again i say it, ThreadLocal is a class provides way to hold thread local variables and provide access to get and set values. in other words, it allows you to have copy of variables per thread and these variables will be garbage collected what the thread dies.

Thursday, July 15, 2010

Be aware of Autoboxing


Target audience: Beginners and Intermediates
Autoboxing is a feature added in Java 5. Boxing and unboxing give convenient ways to use Wrapper classes. The following example shows how it was used to create a Wrapper class and unwrapp it in versions previous to Java 5 and How it is used with Java 5 autoboxing

//Without autoboxing
Integer one = new Integer(1);
int intOne = one.intValue();
System.out.println("Value of one = " + intOne);

//With autoboxing
Integer intTwo = 2;
System.out.println("Value of two= " + intTwo);

I think we all know about this. But i would like to suggest to be careful when autoboxing is used. Just have a look at the bellow example.

package features;

public class AutoboxingExamples {

public static void main(String[] args) {

Integer i1 = 200;
Integer i2 = 200;
if (i1 == i2) {
System.out.println("same");
} else {
System.out.println("different");
}

Integer i3 = 10;
Integer i4 = 10;
if (i3 == i4) {
System.out.println("same");
} else {
System.out.println("different");
}
}
}

The output of this program is:

different

same

Ohh... what’s happening here??.The i1 and i2 looks fine as normal. we could also predict that two references will be different because we know JVM creates two separate instances and i1 == i2 will be return false. But what happend to i3 and i4? should not it be also ‘different’? “i3 and i4” look even same as “i1 and i2” except the value 100 and 10 respectively.

Oki, let me explain what’s happening.
When the JVM interprets the code, it interprets the Integer i3 = 10; to Integer.valueOf(10);
//Code we wrote
Integer i3 = 10;

//code JVM interprited
Integer i3 = Integer.valueOf(10);

What is happening with Integer.valueOf() is, it uses in memory cache and if the value given(eg: 10) to create the Interger object is small( between -128 and 127) then it gets the object from the cache.The cache is created while loading the IntegerCache class with it’s static block. look at the code of Integer.valueOf() method.
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}

So if int value falls between -128 and 127, the JVM gives us the same objects, that’s why we got true for i3==i4 condition.Java uses in memory cache for small integers to improve the performance.

Not only the Integer wrapper class but the following wrappers also behave the same way
Boolean
Byte
Character from \u0000 to \u007f (7f is 127 in decimal)
Short and Integer from -128 to 127

Better be careful when we have conditions with autoboxing.

Wednesday, July 14, 2010

Using Apache Ant as template engine while building an Application


Target audience: Beginners
There will be situations where we may have more than one properties files having same values for keys. For Example, there can be different properties files but have the same value for server URL or JNDI Provider URL. These values will vary depends on the environment we deploy the Application. For Example, Server URL will be http://172.12.34.5:8080/myapp in UAT (User Acceptance Testing) environment and it will be http://201.12.34.6:80/myapp in production. We have to change all the places in all properties file whenever we deploy the application. It is Ok, if it’s only in one or two places. But what if there are several places to be changed and lot of values like this Server URL. It’ll be a headache.

What can be done?
What we can do is, we can use keys for all the configuration values and replace all the keys with the actual values when the application is built.

Let me explain, we can use a key for Server URL and this key will be used in all properties file. Where ever the Server URL is used, this key will be used instead. Ok, Assume that now we are going to use a key myapp.config.serverurl in all the places where Server URL is used. And we are going to replace this key with the actual value when we build the application. The idea is to replace all the actual values while building. We can keep the actual values in a configuration file with key value pair.

It sounds better, and how can we do this?
We can do this with Apache Ant. As you all know, Ant is a Java-based build tool widely used for building java projects. We can make use of replace task and do out work.Suppose, My application has properties file called myapp.properties, then I’ll make a myapp.properties.template file and myapp.config files. The myapp.properties.template file will have all configuration values replace with keys and the myapp.config will have entries for those keys and values. At the build time the Ant build system that I am going to create will generate the final file myapp.properties which will be used for deployment

I keep all files myapp.properties.template, myapp.config and build.xml in one folder and myapp.properties file also will be generated in the same folder

The myapp.properties.template
serverUrl=myapp.config.server.url

The myapp.config
myapp.config.server.url=http://localhost:8080/myapp


Ant build file























replacefilterfile="${project.conf}/myapp.config"
includes="*.properties" />


Once you run the ant task, the myapp.properties file will be generated. The generated file will look like the following
serverUrl=http://localhost:8080/myapp

How to check loaded classes and from which JAR file they were loaded


Target audience: Beginners

Sometimes we run into issue like loading a class from unexpected location or from JAR file in a different place. We might have placed the JAR in one location but there could be same JAR loaded from different location by class loader based on the class loading preferences but we could found difficulties to resolve the issue. In this kind of scenarios, we might need to find the actual JAR file from which the class files was loaded.

How can we find the loaded classes and its JAR files from which they were loaded?
Java has an JVM option -verbose:class. if we run the JVM with this option, then it will list out all classes thar are loaded by JVM and those classes’s JAR file with location. This will be really helpful resolving loading classes from unexpected JAR files.
E.g:
C:\Projects\MyWork>java -verbose:class org.test.TestMyClass

If you wish you can try out an opensource tool called Joops too.

Tuesday, July 13, 2010

CSS Style of Command Prompt or Console

In one of my blog post, I wanted to show some text as how it would look like in command prompt or console. Then i created a CSS style which will make the in-line text to be looked like texts in command prompt or console. Hope it will help you too.



Sample:
C:\Projects\MyWork\codebase\xml\build>_

Output will be:

C:\Projects\MyWork\codebase\xml\build>_

How to use encrypted password in JBoss datasource


Target audience: Beginners
Version: JBoss 4.x

We configure the datasources in *-ds.xml files and place those files under \server\xxx\deploy location. The JBoss will scan any *-ds.xml under this location and create datasources.

I’m going to explain only how to use encrypted password in datasource configuration and i hope you all know how to configure the datasource. In this section, i going to configure a XA datasource with encrypted password.

JBoss provides a way to do configure datasource using encrypted password. The way is to use a “security-domain” property in the -ds.xml. This property should be mapped to a policy in login-config.xml under \server\xxx\conf location.

Look at the following sample -ds.xml files . I have commented out the section that are used when a clear text password is used.




XAOracleDS

false
oracle.jdbc.xa.client.OracleXADataSource
jdbc:oracle:oci8:@tc


OracleDSEncryptedLogon
org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter


Oracle9i



name="jboss.jca:service=OracleXAExceptionFormatter">
jboss:service=TransactionManager




A “security-domain” property is defined(or mapped) with a value “OracleDSEncryptedLogon”. This “OracleDSEncryptedLogon” is called login policy and it should be defined in login-config.xml .
Ok, How do we define the login policy?. The bellow section shows how to defined a login policy in login-config.xml under \server\xxx\conf location.


.....





scott
5dfc52b51bd35553df8592078de921bc
jboss.jca:name=XAOracleDS,service=XATxCM






As you see, A “OracleDSEncryptedLogon” is defined with a user name and a password. The password is a encrypted password and it should be an encrypted password. The org.jboss.resource.security.SecureIdentityLoginModule is used as code. This org.jboss.resource.security.SecureIdentityLoginModule is a JBoss’s built in tool to encrypt and decrypt text.
Note: As i use XA datatsource, i have configured “managedConnectionFactoryName” module option with the jndi name “XAOracleDS” given in -ds.xml file and with the service “XATxCM”.

Ok, Now we know how to configure the encrypted password. But i think we have to encrypt the password . It can be done with the same jboss tool org.jboss.resource.security.SecureIdentityLoginModule. Follow the steps
Step 1.Open a command prompt
Step 2. Go to your JBoss home (C:/Tools/jboss-4.2.3.GA/)
Step 3. Set /bin to the path if it has not been set yet.
Step 4. Excecute bellow command to run the encryption tool to generate the encrypted password.

java -cp lib/jboss-common.jar:lib/jboss-jmx.jar:server/default/lib/jbosssx.jar:server/default/lib/jboss-jca.jar org.jboss.resource.security.SecureIdentityLoginModule password
you will see the
Encoded password: 5dfc52b51bd35553df8592078de921bc
Once you configured everything then just restart the server.
Hope this note will be helpful for you.

Saturday, July 10, 2010

How to use different deployment locations in JBoss


Target Audience: Beginners
JBoss version 4.x

We normally would have a build system which builds the application, creates the distribution files ( war, sar ,ear...) and then copies the distribution files to server/xxx/deploy directory. In JBoss, We used to deploy our applications under server/xxx/deploy.
E.g: D:/Tools/jboss-4.2.0.GA/server/default/deploy
Alternatively we can tell( configure) JBoss to deploy the application from our preferred location ( somewhere from outside of the JBoss).

How can we do that?
There is a MBean with name “jboss.deployment:type=DeploymentScanner” has been defined in conf/jboss-service.xml. This MBean is responsible for hot deployments. This MBean has a attribute “URLs” which accepts comma separated values. We can add our values too along with the existing values. Suppose our distribution files are built under c:/myproject/dist, then we can configure the DeploymentScanner as given bellow.


Don’t forget to restart the JBoss server after the changes were made. The DeploymentScanner will scan the configured URLs and deploy the possible applications.

If you want to configure the location without restating the application as hot deployment then you would have to do it through the JMX-Console. Please find the details here

Hope this will be helpful.

Friday, July 9, 2010

Hibernate persistence lifecycle


Target Audience: Beginners
Hibernate has three states respect to its persistence lifecycle which are transient, persistent and detached. Hibernate persistent manager has some callback methods which involves in those persistent states. In a lifecycle, the object can transition from transient to persistent to detached states.

Transient objects
When an object is instantiated (with new operator), it’s not persistent immediately. It’s first goes to the transient state which is in memory. In this state it’s not related to any database table row. When that object is de-referenced it loses its state and goes to detached state which will be eligible to garbage collected.
The objects that are in transient state are not considered as transactional objects. Any modification made on those object can not be part of transaction. If a transient object need to be persist or in other words if an object need to changes its state from transient to persistent, then the save () method should be called to persistent manager or that object should refer to one which was created from already persisted.

Persistent objects
Persistent instance is which has a valid database entry set with a primary key identifier. In other words, it should refer a valid database table row.
Persistent object can be instantiated with a call of save () method of the persistent manager then it’s associated to that persistent manager. Or alternatively it can be instantiated with a persistent object which is already associated with that persistent manager.
Persistent object participated in a transaction will be synchronized with the database when the transaction manager commits the transaction which executes the SQL query. Some times, the synchronization will happen before the execution of the queries just to make sure that the queries aware of the changes done during the previous transaction.
When the transaction ends, all the persistent object will not be updated to the database. Hibernate checks the objects and finds which are modified then only it’ll update the database. This process is called dirty checking. Dirty objects are which has had modified and not synchronized with database. This process gains performance with some databases and loose performance with some databases. So hibernate allows user to set this with dynamic-update="true" in class mapping so it would generate SQL dynamically to update only the columns that are modified.
When the persistent manager class the delete () method the data will be removed from database and the persistent object will move fro persistent state to transient sate.

Detached objects
Detached object are which no longer guaranteed to be synchronized with database state.
The persistence instances will still exist even after the transaction completes. These instances will be detached when the close () the Session. But still those object holds the data , Hibernate can detain this objects out side of the transaction manager and persistent manager, with a new transaction manager and with a new persistent manager.
Persistent objects can not be detached explicitly. The evict () method of Session can be used to detach the object from session cache. All persistent objects will be detached when close () the session or the objects are serialized.

Thursday, July 8, 2010

Catching java.lang.Throwable


Target Audience: Beginners
Can we catch java.lang.Throwable? This is a hot question in java developers world. I would say “yes, you can but you should not”. Is it confusing? Ok. Let me explain

Technically we can catch it as java allows it.

try{
//some code
}catch (Throwable e) {
// TODO: handle exception
}
The java.lang.Exception and java.lang.Error are only the direct subclasses of java.lang.Throwable. As we know all Exceptions in our code or program should be caught and handled except RuntimeException. RuntimeExceptions are caught and handled some times and most of the time it is let to be thrown to the caller. When RuntimeException is caught and handled? Suppose we are developing a web application and we got a exception while writing to a database and the underlying API like JDBC or Hibernate throws a RuntimeException, then we catch it and show the web user with an appropriate error message. Erros are mostly unrecoverable like java.lang.OutOfMemoryError and ava.lang.StackOverflowError. We can not do anything if we even catch it. So the java world extremely suggest not catch java.lang.Error in other words java.lang.Throwable because if we catch Throwable then we catch Error too.

We can look at in a different view too. Suppose you are creating a API which will be used by other developers ( like an open source component) and your component uses other third party API ( some other open source component like apache beanutils API ). you might have created your component using a specific version( V1.0) of third party component. if a developer try to use your component and pick the wrong version(V.2.0) of the third party component which your component depend on, then he may run into some errors like java.lang.NoSuchMethodError because of different version of third party. So in your component’s code you can plan to catch java.lang.NoSuchMethodError , log it and throw it as your customized Exception saying “ Hello! you are probably using a different version of X API, please use Xv1.0 or any previous versions”. Here we catch the Errors.

So my point is there could be extremely rare situations where you might catch java.lang.Throwable. But much much better to avoid doing so.

Avoid catching java.lang.Throwable and be happy.

Reference:
A video tutorial explaining very basics of java exception handling

Tuesday, July 6, 2010

PageContext.getSession() returns null

javax.servlet.jsp.PageContext.getSession() will return the reference to the implicit session object that we define in the page
e.g:
<%... page session="false" %>
<html>
<%= pageContext.getSession() %>
</html>
This will return you a null as we defined ‘false’ for implicit session object.

And I think that PageContext.getSession() would only return the session object if it has been already created otherwise you will get a null.

I mean the bellow one might also get a null unless a session has been already created.
<%... page session="true" %>
<html>
<%= pageContext.getSession() %>
</html>
The following will work perfectly
<%... page session="true" %>
<html>
<% request.getSession(); %>
<%= pageContext.getSession() %>
</html>

Binding JBoss to specific IP / configuring IP to JBoss application server


Target Audience: Beginner, Intermediate
When we configure the JBoss application in a production environment, the server need to be bind to an IP address ( in most cases). There are several ways to do it.
1. Setting as a run parameter. When we run the JBoss server in a cmd prompt, run as
run -b127.0.0.1

2. Setting it as a system property. We can set a system property which is used internally by JBoss server.
run -Djboss.bind.address=127.0.0.1

3. If we want the configuration to be permanent, then we can place the configuration inside run.bat file. Open run.bat file and search for org.jboss.Main and place the binding configuration .
E.g: org.jboss.Main -b192.168.5.29


Note: We can specify 0.0.0.0 if we want all IP addresses to be mapped to JBoss Server.

Monday, July 5, 2010

What is java.home?


Target Audience: Beginners
When a java program runs, the java runtime environment (JRE- who runs any java program) sets some system properties for its own use and java.home is one of those system properties. The java.home is referencing the JRE home directory E.g: C:\Tools\jdk1.5.0_04\jre.

People tend to confuse with JAVA _HOME and java.home. They are different. JAVA _HOME is set by the user ( me or you) to reference JDK’s home directory. E,g: C:\Tools\jdk1.5.0_04\

Following are the system properties that java sets.
Key Description of Associated Value
java.version Java Runtime Environment version
java.vendor Java Runtime Environment vendor
java.vendor.url Java vendor URL
java.home Java installation directory
java.vm.specification.version Java Virtual Machine specification version
java.vm.specification.vendor Java Virtual Machine specification vendor
java.vm.specification.name Java Virtual Machine specification name
java.vm.version Java Virtual Machine implementation version
java.vm.vendor Java Virtual Machine implementation vendor
java.vm.name Java Virtual Machine implementation name
java.specification.version Java Runtime Environment specification version
java.specification.vendor Java Runtime Environment specification vendor
java.specification.name Java Runtime Environment specification name
java.class.version Java class format version number
java.class.path Java class path
java.library.path List of paths to search when loading libraries
java.io.tmpdir Default temp file path
java.compiler Name of JIT compiler to use
java.ext.dirs Path of extension directory or directories
os.name Operating system name
os.arch Operating system architecture
os.version Operating system version
file.separator File separator ("/" on UNIX)
path.separator Path separator (":" on UNIX)
line.separator Line separator ("\n" on UNIX)
user.name User's account name
user.home User's home directory
user.dir User's current working directory


public class SystemExample {
public static void main(String[] args) {
System.out.println("java.home :" + System.getProperty("java.home"));
System.out.println("java.vm.version :" + System.getProperty("java.vm.version"));
System.out.println("os.name :" + System.getProperty("os.name"));
System.out.println("os.version :" + System.getProperty("os.version"));
System.out.println("user.name :" + System.getProperty("user.name"));
}
}

The output will be similar to this

java.home :C:\Tools\jdk1.5.0_04\jre
java.vm.version :1.5.0_04-b05
os.name :Windows XP
os.version :5.1
user.name :kannan

Sunday, July 4, 2010

Java Mail Examples


1.How to send a simple email in java
2.How to authenticate user and send email in java

1.How to send a simple email in java

package email;

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class EmailExample {

public static void main(String[] args) {

EmailExample.sendEmail("mail.test.com", "121",
"webmaster@test.com", "to@test.com",
"Wazz up!", "Testing...");
}

public static void sendEmail(String smtpHost, String smtpPort
, String from, String to, String subject, String body) {

Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", smtpPort);
Session session = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
} catch (MessagingException ex) {
System.err.println("Opps!! could not send email. " + ex);
}
}
}

2.How to authenticate user and send email in java

package basics;

import java.util.Date;
import java.util.Map;
import java.util.Properties;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

/**
* This is a default mail sender instance, which is implemented based on
* javax.mail API. This handles the actual mail sending part.
* The caller should create a map of email parameters and pass it to
* the send(Map) method.
*
* Map<String, String> params = new HashMap<String, String>();
* params.put(Mail.SMTP_HOST, "smtp.blogspot.test.com"));
* params.put(Mail.FROM, "testz_apps@blogger.test.com");
* params.put(Mail.TO, "testz_apps@blogger.test.com");
* params.put(Mail.SUBJECT, "");
* params.put(Mail.BODY, "");
* mailSender.send(params);
*
* It supports only "text/plain" as body content. When there are multiple
* emails concatenated in one String for Mail.TO,Mail.CC or
* Mail.BCC, use ',' as a separator or use Mail.ADDRESS_SEPERATOR instead.
* If the credentials need to be authenticated, a Mail.AUTH parameter
* should be set in the parameters map with the value of "true" along
* with Mail.USER_NAME and Mail.PASSWORD params.
*
* Map<String, String> params = new HashMap<String, String>();
* params.put(Mail.SMTP_HOST, "smtp.blogspot.test.com"));
* params.put(Mail.FROM, "testz_apps@blogger.test.com");
* params.put(Mail.TO, "testz_apps@blogger.test.com");
* params.put(Mail.SUBJECT, "");
* params.put(Mail.BODY, "");
* params.put(AUTH, "true");
* params.put(USER_NAME, "kannan");
* params.put(PASSWORD, "password");
* mailSender.send(params);
*
* @author Kannan
* @version 1.0
*/
public class MailSender implements IMailSender {

// TODO Implement replyTo
// TODO Implement files attachment
// TODO Implement template content

/** The log handler. */
private Logger logger = Logger.getLogger(this.getClass().getName());

/**
* {@inheritDoc}
*/
public boolean send(Map mailParams) throws EmailSendException {
boolean result = false;
try {
// validate the mandatory parameters, and throws the EmailSendException.
validateParams(mailParams);

// Sends the mail if the validation is fine.
sendMail(mailParams);
result = true;
if (logger.isDebugEnabled()) {
logger.debug("mails sent successfully");
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new EmailSendException(e.getMessage());
}
return result;
}

/**
* Validates all parameters. The to address, from address, body, subject
* and smtp host address parameters are mandatory. if one of mandatory
* parameters is null or one of to address, from address and smtp host
* address is empty, then it throws the EmailSendException with a
* appropriate message.
*
* @param mailParams the mail parameters.
* @throws if one of mandatory parameters is null
* @throws EmailSendException the email send exception
*/
private void validateParams(Map mailParams) throws EmailSendException {
if (mailParams == null) {
logger.error("The mail parameter map is null");
throw new EmailSendException("The mail parameter map is null");
}

// validates the smtp host address, the smtp host can not be empty.
String smtpHost = (String) mailParams.get(SMTP_HOST);
if (smtpHost == null || smtpHost.equals("")) {
logger.error("The mail smtp host is null or empty");
throw new EmailSendException("The mail smtp host is null or empty");
}

// validates the from address, the from address can not be empty.
String from = (String) mailParams.get(FROM);
if (from == null || from.equals("")) {
logger.error("The mail from address is null or empty");
throw new EmailSendException("The mail from address is null or empty");
}

// validates the subject, the subject can be empty.
String subject = (String) mailParams.get(SUBJECT);
if (subject == null) {
logger.error("The mail subject is null");
throw new EmailSendException("The mail subject is null");
}

// validates the body, the body can be empty.
String body = (String) mailParams.get(BODY);
if (body == null) {
logger.error("The mail body is null");
throw new EmailSendException("The mail body is null");
}

// validates the to address, the to address can not be empty.
String to = (String) mailParams.get(TO);
if (to == null || to.equals("")) {
logger.error("The mail to address is null or empty");
throw new EmailSendException("The mail to address is null or empty");
}
}

/**
* Sends the email for given toAddress. The message body and subject will be
* messageBody and messageSubject.
*
* @param mailParams the mail params
* @throws AddressException throws when a wrongly formatted address is encountered.
* @throws MessagingException if there are any other unexpected exception is encountered
* @throws EmailSendException the email send exception
*/
private void sendMail(Map mailParams) throws EmailSendException {

String from = (String) mailParams.get(FROM);
String subject = (String) mailParams.get(SUBJECT);
String body = (String) mailParams.get(BODY);
String to = (String) mailParams.get(TO);
String cc = (String) mailParams.get(CC);
String bcc = (String) mailParams.get(BCC);
String smtpHost = (String) mailParams.get(SMTP_HOST);
String smtpPort = (String) mailParams.get(SMTP_PORT);
String auth = (String) mailParams.get(AUTH);

// Get system properties
Properties props = System.getProperties();

// Specify the desired SMTP server
props.put("mail.smtp.host", smtpHost);
if (smtpPort != null) {// if null, the default port 25 will be used instead
props.put("mail.smtp.port", smtpPort);
}

// Create a new Session object
Session session = null;
// If authentication is required
if (auth != null && auth.toLowerCase().equals("true")) {
String username = (String) mailParams.get(USER_NAME);
String password = (String) mailParams.get(PASSWORD);
SMTPAuthenticator authenticator = new SMTPAuthenticator(username, password);
session = Session.getInstance(props, authenticator);
} else {
// If authentication is not required
session = Session.getInstance(props, null);
}

// Create a new MimeMessage object (using the Session created above)
Message message = new MimeMessage(session);

try {
// Setting the from address
message.setFrom(new InternetAddress(from));

// Setting the CC address if it's not null and empty
message.setRecipients(Message.RecipientType.TO, getInternetAddress(to));
if (cc != null && !cc.equals("")) {
message.setRecipients(Message.RecipientType.CC, getInternetAddress(cc));
}

// Setting the BCC address if it's not null and empty
if (bcc != null && !bcc.equals("")) {
message.setRecipients(Message.RecipientType.BCC, getInternetAddress(bcc));
}

// Setting the subject and body content. it supports only "text/plain" for now.
message.setSubject(subject);
message.setSentDate(new Date());
message.setContent(body, "text/plain");

if (logger.isDebugEnabled()) {
logger.debug("The mail is going to be sent using the following parameters");
logger.debug("To : " + to);
logger.debug("From : " + from);
logger.debug("Subject : " + subject);
logger.debug("Body : " + body);
logger.debug("Smtp host : " + smtpHost);
logger.debug("CC : " + cc);
logger.debug("BCC : " + bcc);
}
Transport.send(message);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new EmailSendException(e.getMessage(), e);
}
}

/**
* Returns the array of InternetAddress , for given address. it splits the give
* address with the ADDRESS_SEPERATOR and convert it into a
* InternetAddress.
*
* @param address the address, can be a single address or multiple address separated by
* ADDRESS_SEPERATOR.
* @return the array of InternetAddress , for given address
* @throws EmailSendException if there are any AddressException, then it logs the
* error and wraps it with EmailSendException and then throws it.
*/
private InternetAddress[] getInternetAddress(String address) throws EmailSendException {
String addressArray[] = address.split(ADDRESS_SEPERATOR);
InternetAddress[] inetAddress = new InternetAddress[addressArray.length];
for (int i = 0; i < addressArray.length; i++) {
try {
inetAddress[i] = new InternetAddress(addressArray[i]);
} catch (AddressException e) {
logger.error(e.getMessage(), e);
throw new EmailSendException(e.getMessage(), e);
}
}
return inetAddress;
}

/**
* The Class SMTPAuthenticator.
*/
private class SMTPAuthenticator extends javax.mail.Authenticator {

/** The username. */
String username = null;

/** The password. */
String password = null;

/**
* Instantiates a new sMTP authenticator.
*
* @param username the username
* @param password the password
*/
SMTPAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}

public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}

}

/**
* The constant class holds the key value pair.
*
* @author Kannan
* @version 1.0
*/
public class Mail {

/** The email address separator */
public static final String ADDRESS_SEPERATOR = ",";

/** The key for email from address */
public static final String FROM = "FROM";

/** The key for email subject address */
public static final String SUBJECT = "SUBJECT";

/** The key for email body address */
public static final String BODY = "BODY";

/** The key for email SMTP address */
public static final String SMTP_HOST = "SMTP_HOST";

/** The key for email SMTP port */
public static final String SMTP_PORT = "SMTP_PORT";

/** The key for email to address */
public static final String TO = "TO";

/** The key for email CC address */
public static final String CC = "CC";

/** The key for email BCC address */
public static final String BCC = "BCC";

/** The key for username */
public static final String USER_NAME = "USER_NAME";

/** The key for password */
public static final String PASSWORD = "PASSWORD";

/** The key for email authentication indicator */
public static final String AUTH = "AUTH";
}

/**
* The interface define methods for sending mails.
*
* @author Kannan
* @version 1.0
*/
public interface IMailSender {

/**
* Send the mail according to the parameters that are set by the mailParams map.
*
* @param the mail parameters. the mail parameters can be set as follows. *
*
* Map<String, String> params = new HashMap<String, String>();
* params.put(Mail.SMTP_HOST, "smtp.blogspot.test.com"));
* params.put(Mail.FROM, "testz_apps@blogger.test.com");
* params.put(Mail.TO, "testz_apps@blogger.test.com");
* params.put(Mail.SUBJECT, "");
* params.put(Mail.BODY, "");
* mailSender.send(params);
*
* @throws EmailSendException, if there are any exceptions conditions, then it is wrapped with
* EmailSendException and thrown.
*/
boolean send(Map mailParams) throws EmailSendException;
}

Spring to enable multi-environment deployment without rebuilding

I would like to share this article which I came across. It gives a better idea of how spring enables loading environment specific property files. It’s really helpful as most of the projects will be tested on multiple environments.

for more read this

Java Abstract Class Examples


1. How to create an abstract Class and its sub classes
2. How to create a static method in abstract Class

1. How to create an abstract Class and its sub classes

package basics;

public abstract class AbstractClassExample {

public static void main(String[] args) {
Lion lion = new Lion("Mr Lion", 4);
lion.printName();
System.out.println(lion.canWalkWithTwoLegs());

Bear bear = new Bear("Mr Bear", 4);
bear.printName();
System.out.println(bear.canWalkWithTwoLegs());
}
}

abstract class Animal {
private String name = null;
private int numberOfLegs = 0;

public Animal(String name, int numberOfLegs) {
super();
this.name = name;
this.numberOfLegs = numberOfLegs;
}

public abstract boolean canWalkWithTwoLegs();

public void printName() {
System.out.println("Name is: " + name);
}
}

class Lion extends Animal {

public Lion(String name, int numberOfLegs) {
super(name, numberOfLegs);
}

public boolean canWalkWithTwoLegs() {
return false;
}
}

class Bear extends Animal {

public Bear(String name, int numberOfLegs) {
super(name, numberOfLegs);
}

public boolean canWalkWithTwoLegs() {
return true;
}
}

There will be a zip file created at
Name is: Mr Lion
false
Name is: Mr Bear
true


2. How to create a static method in abstract Class

package basics;

public abstract class AbstractClassExample {

public static void main(String[] args) {
AbstractClassExample.doSomeThing();
}

public static void doSomeThing() {
System.out.println("What can i do?");
}
}


There will be a zip file created at
What can i do?

Saturday, July 3, 2010

Java Zip Examples


1. How to create ZIP file in java

package basics;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipExample {

void zipFiles(String[] sourcsFiles, String destPath) {
// Create a buffer for reading the files
byte[] tempBufffer = new byte[1024];

ZipOutputStream out = null;
FileInputStream in = null;
try {
// Create the zip file instance.
out = new ZipOutputStream(new FileOutputStream(new File(
destPath)));

// Compress the files
for (int i = 0; i < sourcsFiles.length; i++) {
in = new FileInputStream(sourcsFiles[i]);

// This is to get file name
String zipEntyname = sourcsFiles[i].substring(sourcsFiles[i]
.lastIndexOf("/") + 1, sourcsFiles[i].length());
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(zipEntyname));

// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(tempBufffer)) > 0) {
out.write(tempBufffer, 0, len);
}

// Complete the entry
out.closeEntry();
in.close();
}

// Complete the ZIP file
out.close();
} catch (Exception e) {
} finally {
try {
if (out != null) {
out.close();
out = null;
}
if (in != null) {
in.close();
in = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {
String[] sourcsFiles = { "C:/temp/one.properties",
"C:/temp/two.properties" };
new ZipExample().zipFiles(sourcsFiles, "C:/temp/files.zip");
}
}

There will be a zip file created at
C:/temp/files.zip

Java Reflection Examples


1. How to invoke or access a private method of an object or class in java

package basics;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

class ReflectionExample {

/**
* Invokes a private method of an object using java Reflection.
*/
public void invokePrivateMethod() {

//Class instance
Class personClass = Person.class;

// Get methods
Method[] methods = personClass.getDeclaredMethods();

// Create the object to invoke the methods on
Person computer = new Person("Ivan");

if(methods.length>0)
{
try {

//This is very important to invoke a private method
// or to access a private variable
methods[0].setAccessible(true);

methods[0].invoke(computer, null);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
return;
} catch (InvocationTargetException ex) {
ex.printStackTrace();
return;
} catch (IllegalAccessException ex) {
ex.printStackTrace();
return;
}
}
}

public static void main(String[] args) {
new ReflectionExample().invokePrivateMethod();
}
}

class Person {
private String name;

public Person(String name) {
this.name = name;
}

private void sayName() {
System.out.println("My name is : " + name);
}

}

The out put will be:
My name is : Ivan

Java StringTokenizer Example


1. How to use StringTokenizer

package basics;

import java.util.StringTokenizer;

public class StringTokenizerExample {

public static void tokenize(String text) {
StringTokenizer tokenizer = new StringTokenizer(text, "^");
while (tokenizer.hasMoreTokens())
System.out.println(tokenizer.nextToken());
}

public static void main(String[] args) {
StringTokenizerExample.tokenize("AAA^BBB^CCC^DDD");
}
}

The out put will be:
AAA
BBB
CCC
DDD

Java Cloning Examples


1. How to clone an Object/How to make a copy of an Object

package basics;

public class CloneExample {

// The Person value Object
class Person implements Cloneable {
private String name;
private Address address;

public Person(String name, String address) {
this.name = name;
this.address = new Address(address);
}

// Implementing cloning method
protected Object clone() throws CloneNotSupportedException {
Person clone = (Person) super.clone();
clone.address = (Address) address.clone();
return clone;

}
}

// The Address value Object
class Address implements Cloneable {
String street = null;

public Address(String street) {
this.street = street;
}

// Implementing cloning method
protected Object clone() throws CloneNotSupportedException {
Address clone = (Address) super.clone();
return clone;
}

public String toString() {
return street;
}
}

void testCloning() {
try {
Person person = new Person("calvin", "redhill");
Person cloned = (Person) person.clone();
System.out.println(cloned.name);
System.out.println(cloned.address);

} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {

CloneExample example = new CloneExample();
example.testCloning();
}
}

The out put will be:
calvin
redhill

Java Array Examples


1. How to sort integer Array
2. How to sort String Array
3. How to sort Object Array or Array of Objects

1. How to sort integer Array
The out put will be: 1,2,3,4,5,6,7,8,9,10

package basics;

import java.util.Arrays;

class ArrayExample {

public static void main(String[] args) {
ArrayExample example = new ArrayExample();
example.sortIntArray();
}

public void sortIntArray() {

int[] intArray = new int[] { 10, 8, 9, 7, 5, 6, 3, 4, 2, 1 };

Arrays.sort(intArray);

for (int i = 0; i < intArray.length; i++) {
System.out.print(intArray[i]);
System.out.print(",");
}
}
}


2. How to sort String Array
The out put will be: Five,Four,One,Three,Two,

package io;

import java.util.Arrays;

class ArrayExample {

public static void main(String[] args) {
ArrayExample example = new ArrayExample();
example.sortStringArray();
}

public void sortStringArray() {

String[] strArray = new String[] { "One", "Two", "Three", "Four",
"Five" };

Arrays.sort(strArray);

for (int i = 0; i < strArray.length; i++) {
System.out.print(strArray[i]);
System.out.print(",");
}
}
}

3. How to sort Object Array or Array of Objects
The out put will be: Chan,Ivan,Sachin,Suresh,

package basics;

import java.util.Arrays;

class ArrayExample {

public static void main(String[] args) {
ArrayExample example = new ArrayExample();
example.sortArray();
}

public void sortArray() {

Person[] array = new Person[] { new Person("Ivan"),
new Person("Suresh"), new Person("Chan"), new Person("Sachin") };

Arrays.sort(array);

for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
System.out.print(",");
}
}

// The Class shoulr implement java.lang.Comparable inteface.
// and should implement compareTo(Object o) method accordingly
class Person implements Comparable {
private String name;

public Person(String name) {
this.name = name;
}

public int compareTo(Object o) {
if (name != null) {
return this.name.compareTo(((Person) o).name);
} else {
return -1;
}
}

public String toString() {
return name;
}
}
}

Friday, July 2, 2010

Java System properties Examples


1. How to load a properties file into System properties
1. How to Retrieve all System properties

1. How to load a properties file into System properties
This program loads all properties from a properties file directly into System properties

package io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class SystemPropertiesExample {

public static void main(String[] args) {
FileInputStream fis = null;
try {

Properties props = new Properties();
fis = new FileInputStream(new File("c:/temp/config.properties"));
props.load(fis);
System.setProperties(props);

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fis.close();
fis = null;
} catch (IOException e) {
e.printStackTrace();
}
}

}
}


2. How to Retrieve all System properties

package io;

import java.util.Enumeration;
import java.util.Properties;

public class SystemPropertiesExample {

public static void main(String[] args) {

Properties props = System.getProperties();

// Enumerate all system properties
Enumeration enumu = props.keys();
while (enumu.hasMoreElements()) {
String propName = (String) enumu.nextElement();
String propValue = (String) props.get(propName);
System.out.println(propName +" :: "+propValue);
}
}
}

Java Timer Examples


1. How to run a Schedule Task or TimerTask
2. How to run a Schedule Task or TimerTask every day morning or every 24 hrs

1. How to run a Schedule Task or TimerTask

package basics;

import java.util.Timer;
import java.util.TimerTask;

public class TimerExamples {
public static void main(String[] args) {
Timer timer = new Timer();

//Delay for 0 mills seconds
//Repeat every 5000 mills second
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println("Running....");
}
}, 0, 5000);
}
}

2. How to run a Schedule Task or TimerTask every day morning or every 24 hrs

package basics;

import java.util.Calendar;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

public class TimerExamples {
public static void main(String[] args) {
Timer timer = new Timer();
Calendar startingTime = Calendar.getInstance(TimeZone.getDefault());

// Starting at 8:00 AM in every day the Morning
startingTime.set(Calendar.HOUR_OF_DAY, 8);
startingTime.set(Calendar.MINUTE, 00);
startingTime.set(Calendar.SECOND, 00);

timer.schedule(new TimerTask() {
public void run() {
System.out.println("Runs everday morning 8.00 AM");
}
// period 24 hrs (1000 *60 * 60 * 24 mills seconds)
}, startingTime.getTime(), 1000 * 60 * 60 * 24);
}
}

Java Date Format Examples


1.How to compare dates in java
2.How to format date in java

1.How to compare dates in java
package basics;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateExamples {

public static void main(String[] args) {
System.out.println(DateExamples.isDateGreaterThanToday("2/07/2010"));
}

public static boolean isDateGreaterThanToday(String date) {
boolean results = true;

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
if (date != null && !date.trim().equals("")) {
try {
Date dateToBeCompared = dateFormat.parse(date);
Date today = new Date();
if (today.compareTo(dateToBeCompared) > 0) {
results = false;
}
} catch (ParseException e) {
e.printStackTrace();
results = true;
}
}
return results;
}
}

2.How to format date in java
Symbol Meaning Presentation Example
G era designator Text AD
y year Number 2009
M month in year Text & Number July & 07
d day in month Number 10
h hour in am/pm (1-12) Number 12
H hour in day (0-23) Number 0
m minute in hour Number 30
s second in minute Number 55
S millisecond Number 978
E day in week Text Tuesday
D day in year Number 189
F day of week in month Number 2 (2nd Wed in July)
w week in year Number 27
W week in month Number 2
a am/pm marker Text PM
k hour in day (1-24) Number 24
K hour in am/pm (0-11) Number 0
z time zone Text Pacific Standard Time
' escape for text Delimiter (none)
' single quote Literal '

package basics;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormatExample {

public static void main(String[] args) {

SimpleDateFormat formatter = null;
Date date = new Date();

formatter = new SimpleDateFormat("MM/dd/yy");
String s = formatter.format(date); // Example 07/02/10

System.out.println(s);

formatter = new SimpleDateFormat("dd-MMM-yy");
s = formatter.format(date);// 02-Jul-10
System.out.println(s);

formatter = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
s = formatter.format(date); // 2010.07.02.21.32.35
System.out.println(s);

formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
s = formatter.format(date); // Fri, 02 Jul 2010 21:32:35 +0800
System.out.println(s);

formatter.applyPattern("EEE, MMM d, ''yy");
s = formatter.format(date); // Fri, Jul 2, '10
System.out.println(s);

formatter.applyPattern("hh 'o''clock' a, zzzz");
s = formatter.format(date); // 09 o'clock PM, Singapore Time
System.out.println(s);

formatter.applyPattern("yyyy.MMMMM.dd GGG hh:mm aaa");
s = formatter.format(date); // 2010.July.02 AD 09:39 PM
System.out.println(s);
}
}

How to set System properties in JBoss


Target Audience: Beginners
Most of the times, we have to deploy our application in many environments for testing before going to production or live. We might have configuration values which need to be set in System Properties and these configuration might change based on the environment. We set System propertis in run.conf , run.sh or run.bat files with -D prefix
E.g: If we want to Set System property with key ‘myKey’ and with value ‘myValue” then we do something like JAVA_OPTS="XXXXXX -DmyKey=myValue.

JBoss give a rich way to load system properties. System properties can also be provided using the System Properties Service. This service allows you to specify one or more system propertis as key value pair or through loading one or more properties file. The Service configuration file can be found in the server/xxx/deploy/properties-service.xml.

The following section describes hoe to set one or more system properties as Key Value pairs.

<mbean code="org.jboss.varia.property.SystemPropertiesService"
name="jboss:type=Service,name=SystemProperties">
<attribute name="Properties">
myKey1=myValue1
myKey12=myValue2
</attribute>
</mbean>

The Properties attribute section configures properties directly in the service
configuration. Properties must be specified as a name/value pair on a separate
line.

The following section describes hoe to set system properties through loading one or more files.

<mbean code="org.jboss.varia.property.SystemPropertiesService"
name="jboss:type=Service,name=SystemProperties">
<attribute name="URLList">
http://localhost/myapp-config.properties, ./conf/myweb-config.properties
</attribute>
</mbean>

The URLList attribute section refers to properties files that contain system properties.
You can provide a URL(http://localhost/myapp-config.properties) or a directory which is relative(./conf/myweb-config.properties) to the root of the server configuration.
Multiple entries should be separated with commas as shown above.

Hope this tutorial helps you.

Thursday, July 1, 2010

Java Directory Examples


1.How to create directory or folder
2.How to delete directory or folder
3.How to copy directory or folder (including subdirectories and files)

1.How to create directory or folder

package io;

import java.io.File;

public class DirectoryExample {
public static void main(String[] args) {

/* The parent directory "C:/temp/" should be exists before
* creating directory "a" */
File directory = new File("C:/temp/a");
boolean created = directory.mkdir();
System.out.println(created);

/* IF parent directory "C:/temp/" does exists, then it creates all */
created = directory.mkdirs();
System.out.println(created);
}
}


2.How to delete directory or folder

package io;

import java.io.File;

public class DirectoryExample {
public static void main(String[] args) {
try {
boolean delete = DirectoryExample.delete(new File("C:/temp/a"));
System.out.println(delete);
} catch (Exception e) {
e.printStackTrace();
}

}

/* Recursively delete all files and sub directories under g directory. */
public static boolean delete(File dir) throws Exception {

// check if the directory(or file) exists
if (!dir.exists()) {
throw new Exception(dir.toString() + " does not exist");
}

// Delete all files and sub directories if current one is a directory
if (dir.isDirectory()) {
String[] list = dir.list();
for (int i = 0; i < list.length; i++) {
delete(new File(dir, list[i]));
}
}

// All files and sub directories have been deleted
// Now delete the given directory
return dir.delete();
}

}

3.How to copy directory or folder (including subdirectories and files)

package io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class DirectoryExample {
public static void main(String[] args) {
try {
boolean coiped = DirectoryExample.copyDirectory(new File("C:/temp/a"),new File("C:/temp/b"));
System.out.println(coiped);
} catch (Exception e) {
e.printStackTrace();
}

}

// Copies all files under srcDir to dstDir.
// If dstDir does not exist, it will be created.
public static boolean copyDirectory(File srcDir, File destDir) throws Exception {

// check whether the source directory(or file) exists
if (!srcDir.exists()) {
throw new Exception(srcDir.toString() + " does not exist");
}

if (srcDir.isDirectory()) {

// Create destination directory if does not exists
if (!destDir.exists()) {
destDir.mkdir();
}

// copy all sub directories and files
String[] children = srcDir.list();
for (int i = 0; i < children.length; i++) {
copyDirectory(new File(srcDir, children[i]), new File(destDir, children[i]));
}
} else {
// This method is implemented in Copying a File
copyFile(srcDir, destDir);
}
return true;
}

public static void copyFile(File srcFile, File destFile) throws Exception {

FileChannel srcChannel = null;
FileChannel dstChannel = null;
try {
srcChannel = new FileInputStream(srcFile).getChannel();
dstChannel = new FileOutputStream(destFile).getChannel();

// Copy file contents from source to destination
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());

} catch (Exception e) {
throw new Exception(e.getMessage(), e);
} finally {
// Closing the channels
try {
if (srcChannel != null) {
srcChannel.close();
}
if (dstChannel != null) {
dstChannel.close();
}
} catch (IOException ioException) {
throw new Exception("Exception thrown while closing the channels inside finally!", ioException);
}
}
}
}

Wednesday, June 30, 2010

Java File Examples


1. How to check if a file exists
2. How to delete a file or folder
3. How to rename a file or folder
4. How to copy a file
5. How to list files with same extensions/how to list only same type files / How to use FilenameFilter
6. How to move a file in Java

1. How to check if a file exists

package io;

import java.io.File;

public class FileExample {

/**
* This is to check whether a file( not folder) exists.
*/
public static boolean isFileExist(String filePath) throws Exception {

boolean exists = false;
File file = null;
try {
file = new File(filePath);
exists = file.isFile();
} catch (Exception e) {
throw new Exception("Exception thrown while checking the file!", e);
} finally {
if (file != null) {
file = null;
}
}
return exists;
}
}


2. How to delete a file or folder

package io;

import java.io.File;

public class FileExample {

/**
* This is to delete a file or folder.
*/
public static void deleteFile(String filePath) throws Exception {
File file = null;
try {
file = new File(filePath);
if (file != null) {
file.delete();
}
} catch (Exception e) {
throw new Exception("Exception thrown while deleting the file!", e);
} finally {
if (file != null) {
file = null;
}
}
}

}

3. How to rename a file or folder

package io;

import java.io.File;

public class FileExample {

/**
* This is to rename a file or folder.
*/
public static void rename(String loaction, String currentName, String newName) throws Exception {
File currentFile = null;
File newFile = null;
try {
currentFile = new File(loaction + File.separator + currentName);
newFile = new File(loaction + File.separator + newName);
if (currentFile != null) {
currentFile.renameTo(newFile);
}
} catch (Exception e) {
throw new Exception("Exception thrown while deleting the file!", e);
} finally {
if (currentFile != null || newFile != null) {
currentFile = null;
newFile = null;
}
}
}
}


4. How to copy a file

class CopyFile {

public static void main(String[] args) {
try {
CopyFile copyFile = new CopyFile();
copyFile.copyFile("test.txt", "C:/temp/", "C:/temp/subtmp/");
System.out.println("done");
} catch (Exception e) {
e.printStackTrace();
}
}

public void copyFile(String fileName, String fromLocation, String toLocation) throws Exception {

FileChannel srcChannel = null;
FileChannel dstChannel = null;
try {
srcChannel = new FileInputStream(fromLocation + File.separator + fileName).getChannel();
dstChannel = new FileOutputStream(toLocation + File.separator + fileName).getChannel();

// Copy file contents from source to destination
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());

} catch (Exception e) {
throw new Exception(e.getMessage(), e);
} finally {
// Closing the channels
try {
if (srcChannel != null) {
srcChannel.close();
}
if (dstChannel != null) {
dstChannel.close();
}
} catch (IOException ioException) {
throw new Exception("Exception thrown while closing the channels inside finally!", ioException);
}
}
}
}

5. How to list files with same extensions/how to list only same type files / How to use FilenameFilter

package io;

import java.io.*;
import java.util.*;

public class FileExample {

public static void main(String[] args) {
try {
FileExample example = new FileExample();
example.listPDFFiles("C:/temp/subtmp/");
System.out.println("done");
} catch (Exception e) {
e.printStackTrace();
}
}

public void listPDFFiles(String folderPath) throws Exception {
File file = null;
try {
file = new File(folderPath);
FilenameFilter pdfFilter = new PDFFilter();
String[] list = file.list(pdfFilter);
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
}
} catch (Exception e) {
throw new Exception("Exception thrown while checking the file!", e);
} finally {
if (file != null) {
file = null;
}
}
}

class PDFFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.toLowerCase().endsWith(".pdf"));
}
}
}

6. How to move a file in Java

package io;

import java.io.*;
import java.util.*;

public class FileExample {

public static void main(String[] args) {
try {
FileExample.move("C:/temp/subtmp/newtest.txt", "C:/temp/subtmp/a/newtest.txt");
System.out.println("done");
} catch (Exception e) {
e.printStackTrace();
}
}

public static void move(String srcFilePath, String destFilePath) throws Exception {
File scrFile = null;
File destFile = null;
try {
scrFile = new File(srcFilePath);
destFile = new File(destFilePath);
if (scrFile != null) {
scrFile.renameTo(destFile);
}
} catch (Exception e) {
throw new Exception("Exception thrown while moving the file!", e);
} finally {
if (scrFile != null || destFile != null) {
scrFile = null;
destFile = null;
}
}
}
}

Getting User input in Java with Scanner


Target Audience:Beginners

Java 1.5 has a convenient way to receive user inputs. The Scanner class is a part of java util package. It scans the user inputs and with the help of its various next* methods, the user input can be received directly in desired type ( e.g: int , long or String) .For example, the following code allows a user to read a number from System input as integer type

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

Suppose if a file contains a list of numbers which can be converted to long type, then we can read those numbers as following.

Scanner sc = new Scanner(new File("numbers_file"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}

Now we’ll do a very simple example to understand it more. We are going to write a program which receives the user inputs and at the end it prints the sum of the given numbers. the program will print if we give “OK” as the last value and press enter key.

package com.learner.scanner;

import java.util.Scanner;

public class ScannerExample {

public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
double sum = 0.0;

/**
* This is to ask the user to enter a number
*/
System.out.println("Enter numbers to calulate sum.");

/**
* Loop through all input tokens e.g: 3 5 7 ok
*/
while (scanner.hasNext()) {

if (scanner.hasNextDouble()) {
sum += scanner.nextDouble();
} else {

// Exits if OK is gove as input
String str = scanner.next();
if (str.equals("OK"))
break;
else {

// Prints the error message if we give other than 'OK'
System.out.println("Error while running. Please try again");
return;
}
}
}

System.out.println("Sum is : " + sum);
}
}

Compile and run the class.
Refer here for how to compile and run- First Java Program

When the program runs, give following input and press enter 1 3 3 OK . Keep at least one space between tokens ( between numbers and ‘OK’)

The output will be : Sum is : 7.0

Wow. It’s pretty easy and clean. Hope it helps you.

Here is another basic video tutorial of how to use scanner