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

Loops


1.How to write while loop statements
2.How to write do while loop statements
3.How to write for loop statements

How to write while loop statements

class LoopSamples {

public static void main(String[] args) {
int x = 1;
while (x < 2) {
System.out.println(x);
++x;
}
}
}

The output will be: 1

How to write do while loop statements

class LoopSamples {

public static void main(String[] args) {
int x = 1;
do {
System.out.println(x);
++x;
} while (x < 2);
}
}

The output will be: 1
Note: The loop will exected atleast one ( first) time

How to write for loop statements

class LoopSamples {

public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println("i is " + i);
}

int y = 6;
for (int x = 0; (x < 2); x++, y++) {
System.out.println("x is " + x);
System.out.println("y is " + y);
}
}
}

How to write switch statements



class SwitchExample {

public static void main(String[] args) {
int a = 2;
switch (a) {
case 1:
System.out.println("a is equal to 1");
break;
case 2:
System.out.println("a is equal to 2");
break;
case 3:
System.out.println("a is equal to 3");
break;
default:
System.out.println("value of a is not 1,2,or 3");
}
}
}

The output will be: a is equal to 2
Note: only char, byte, short, int can be used in switch variable

Creating your own exception or creating custom exception


Create your own exception or creating custom exception

class EmailSendException extends Exception {

public EmailSendException() {
super();
}

public EmailSendException(String message, Throwable cause) {
super(message, cause);

}

public EmailSendException(String message) {
super(message);
}

public EmailSendException(Throwable cause) {
super(cause);
}
}

Tuesday, June 29, 2010

How to use isDebugEnabled() efficiently


Target audience: Beginners
We all use loggers for debugging the application in-case if there were any issues. We all write debug statements in our code.I would like to share my experience of how effectively we can use
debug statements. We should write the debug statements which do not impact on our application performance. Lets see how we can do it. I use log4j for logging.

this is how we write debug code

log.debug(" some informantion");
...
log.debug("some informantion : " + variale);

We can see, there are some string concatenations happening here. We all know that string concatenation is very expensive means that it badly affect the application performance.if you see the above code, it will be executed even if the log level is set to INFO,WARN or ERROR. if we restrict these code to be executed only if DEBUG level is enabled, then we can improve the performance of the application. How we can do it? See bellow

if(logger.isDebugEnabled()){
log.debug(" some informantion");
}
.....
if(logger.isDebugEnabled()){
log.debug("some informantion : " + variale);
}

These conditions we added will check whether the log level is set to DEBUG. The log statements will be executed only if the log level is set to DEBUG. This will help to improve the performance.
But the normal practice is the developers do not check for Debug level when there is no string catenation as they think that it does not impact on performance. But it slightly impacts.

Let me explain with sample code

package test;

import org.apache.log4j.Logger;

public class MyLogger {
private Logger logger = Logger.getLogger(this.getClass().getName());

public void check() {

long withCOunt = 0;
long withOutCount = 0;

for (int i = 0; i < 1000; i++) {

// with debug
long start = System.currentTimeMillis();
for (int n = 0; n < 1000; n++) {
if (logger.isDebugEnabled())
logger.debug(n);
}
long end = System.currentTimeMillis();
withCOunt = withCOunt + (end - start);

// with out debug
long start2 = System.currentTimeMillis();
for (int j = 0; j < 1000; j++) {
logger.debug(j);
}
long end2 = System.currentTimeMillis();
withOutCount = withOutCount + (end2 - start2);
}

System.out.println("Total Time Elapsed(With isDebugEnabled) : " + withCOunt);
System.out.println("Total Time Elapsed(Without isDebugEnabled) : " + withOutCount);
}

public static void main(String[] args) {
MyLogger myLogger = new MyLogger();
myLogger.check();
}
}

You should configure log4j or any other loggers. I do not cover configuration here. I use log4j here.
I have one method which has two loops and both of them do the same work but only the difference is one loop has isDebugEnabled() checking. I try to get the accumulated time by running 1000 times to get fairly good results.

// with out debug
....
logger.debug(j);

// with debug
....if (logger.isDebugEnabled())
logger.debug(n);


If you run the application with log level WARN.
The out put will be similar to the following:
Total Time Elapsed(With isDebugEnabled) : 15
Total Time Elapsed(Without isDebugEnabled) : 47

And you run the application with log level DEBUG.
Total Time Elapsed(With isDebugEnabled) : 119704
Total Time Elapsed(Without isDebugEnabled) : 118393

The results will vary based on the machine memory configurations. But if you see, the performance is much better when we use isDebugEnabled() check with log level greater than DEBUG and the performance is fairly equal with loge level DEBUG .

Create your own Ant task


Target Audience: Beginners
Apache Ant is one of the most popular and powerful build tool is the industry. Ant script is a xml file which contains the details of the project and its target that need to be used for the building purpose. Some very common targets are compile, clean, build and dist.

One of the reasons that I like Ant is that it allows user to define their own task. Example: if I need to need to backup files as zip format with a file name which contains the time stamp then I can do that. I can do that in a normal way like having a target which called as “backup” which just zips the files that I need to copy and name it with the time stamp and put it in a folder that I specify. In the other way, I can write a custom ant task which will do that for me.

I’m going to create a custom task which just says the first voice of programmers “Hello World”. I can do this as a normal way like the following.


But I try to do it in a different way so that I can learn how to write a custom task.

Before getting started, download and install Ant version 1.6.1 or later on your system, if it is not already there. When you extract the files from the Ant archive (in .zip, .gzip, or .bzip2 format, depending on what you download), you'll notice a bin directory in the distribution. Place the bin directory in your path, and then type ant -version at a command or shell prompt. If you get back a response like
Apache Ant version 1.6.1 compiled on February 12 2004,

Let’s get started!

The following is the custom task

package com.ltol.ant;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

public class HelloTask extends Task
{
// The method executing the task
public void execute()
throws BuildException {
System.out.println("Hello World");
}
}

If you see the class, there are two classes are imported BuildException and Task classes. BuildException is an important class which will throw the exception when something goes wrong while executing the task. Task is the main class that we need to extend from if we need to create a custom task. The execute() of the Task class is the one will be executed when the target get triggered.

Now we’ll compile
javac -classpath ant.jar com/ltol/ant/HelloTask.java
Once you are successful at compiling HelloTask.java, package HelloTask.class into a .jar file:
jar cvf hello.jar com/ltol/ant/HelloTask.class
The class or classes you use for the task apparently must be in a .jar file to work -- I've tried just using bare classes in a variety of ways with no success. For convenience, place a copy of hello.jar in the class path or to the ant lib directory where all of the Ant .jar files live. With hello.jar there, Ant will be able to find the class in it at build time.
Now we’ll create a build file to execute task that we created. The following is our build.xml file

If you run this build file, you will be getting the output something like this. Make sure that you have the hello.jar file in the class path.


Buildfile: build.xml
sayhello:[hello]
Hello World
BUILD SUCCESSFUL
Total time: 1 second
How simple.

Basics Of Class and Objects


Target audience: Beginners
When I learned java, i could not understand the contract between Class and objects. When i learned more and more,i could get the hang of it.I would like to share my understanding for the people who are beginning to learn about Java class and objects and specially for the people have confusion :)

Definition of the Class is “A template which describes the state(variables) and behavior(methods) of the object of its type.”

Imagine you are going to do business. you are going to manufacture Credit Cards for a client ( e.g: Bank). What will you do first before you start manufacturing? you will design a template or a prototype of a actual Credit Card. you will plan where the owners name should be printed. you will plan where the Credit Card number should be printed. The color ,size of the card and so on. Then you will get a list of user details from your client(E.g: Bank) to create the actual cards. Then you will manufacture thousands or millions of credit cards with actual data printed. You can imagine the ‘Class’ as ‘credit card template’ and the ‘Object’ as the actual credit card printed with user detail (may be with your name on it). The ‘state’ or ‘variables’ are the used detals( name, credit card number and all) That’s it. Classes are the templates of the objects.

//Class, is a template

public class Person {
private String name;
private int hight;

public void Person(String name, int hight) {
this.name = name;
this.hight = hight;
}

public void sayYourName() {
System.out.println(name);
}
}

//Objects, are the actual copies of class

Person me = new Person(“My Name”,185); 
Person you = new Person(“Your Name”,190);

When Java find the “new” key word, then it creates a object or instance(actual copy )of the class and keep it in it memory

Hope it clears your confusion and helps you to understand

Monday, June 28, 2010

First Java Program


Target audience: Beginners
Here, we are not going to talk about basics of java. The objective is to configure Java Development Kit (JDK) ,run a simple java program and understand the basics clearly.

Tools we need
1. JDK ( we are going to use version 1.5)
2. A Text Editior ( Notepad, TextPad,..)

What to be remembered before going into our game
Java is an object-orientated language
There are several types of Java programs and common are the stand-alone application, and the applet. Don't worry,you will get to know others later

First, we are going to write a basic program which just prints "Lets do this!". In Java, you write everything inside a Class. That' it. you can see the structure of a class bellow. A class should always be written inside open and end curly brackets


class Start {
}

Now i'm going to change this class to print "Lets do this!".As I stated earlier we need two tools JDK and a Text Editor. Open your text editor and write the following code.Save the code as Start.java in a prefered location ( i am going to refer the location as c:\myprogram, So the fulpath will be c:\myprogram\Start.java)


class Start {
public static void main(String[] args) {
System.out.println("Lets do this!");
}
}

what to be noticed:
The method "public static void main(String[] args)".This is the main method in java where your program starts running. Java will look for this method when you run a program. Java will do anything you write inside this method ( of course you have to follow some conventions and standards ). you do not need to worry about the method signature now as you are a very beginner. We'll cove all later. if you see the main method also be written inside open and end curly brackets. Yes,Methods also should be written inside open and end curly brackets.

To print a text ot String, you have to use System.out.println(SomeText) or System.out.print(SomeText) method. Here we used System.out.println("Lets do this!");. This will print a text "Lets do this!" in console (command prompt where you run the program). you will understand the details of the syntax later but for now, think that you say to java ( system) to print something in the output (console).

Now we will compile and run the program.
Hope you have downloaded the JDK and installed in a preferred place.( i am going to refer the JDK loaction as c:\tools\jdk1.5)
Go into JDK's 'bin' directory and check whether there are javac.exe( c:\tools\jdk1.5\bin\javac.exe) and java.exe( c:\tools\jdk1.5\bin\java.exe) file exixting. I'll explain what are they in a minute

How java runs the code we wrote.
Java turns the source code (eg: Start.java) to class file (Start.class). This is called compilation. Compilation is translating the source code (Start.java) into byte code ( Start.class). The Java tool which does the compilation is called Java compiler (javac.exe).What we get after the compilation is a byte code ( .class ). Java reads this byte code, understand and then run the application. This process is called interpretation. The java tool which does this process is Java Interpretor (java.exe)

Now we'll compile the code.
1.Open a command prompt ( Start->Run->type 'cmd' and perss 'OK')
2. Set JDK's bin directory in 'PATH' system environment variable
How to set: In command prompt type 'set PATH=c:\tools\jdk1.5\bin
Why we set:This will set the JDK's bin directory in systems environment variable. So whenever we type "javac" or "java", the system will go to "c:\tools\jdk1.5\bin" and run "javac.exe" or "java.exe" respectively
3. Once you set the PATH environment, the go to source directory in command prompt.
How to go: In command prompt type 'cd c:\myprogram". Then you can type "dir" to check whether you see your Start.java file
4. Compile the code
How to compile:In command prompt type "javac Start.java". If compilation is success, then you will see "Start.class" file in the same directory of source code file (c:\myprogram\Start.class)

Now we'll run the program.
How to run: Assume that you are still in the command prompt and the source code directory (c:\myprogram\). type" java Start". the you will see the out put "Lets do this!" in the command prompt console
Hope this helps to to understand the basics of compiling and running Java code or progarm.


Here is another video java tutorial for your reference



Installing JDK on Windows


Target Audience: Beginners
If you want to write and run a program the you will need a development kit. which compiles your cource code and run the application. In Java, the tool is called Java Development KIT (JDK). This KIT contains the tools for compiling ,running, packaging and etc.

What should know before get into details: Difference between JRE and JDK
If you want to write and run a program the you will need a development kit. which compiles your cource code and run the application. In Java, the tool is called Java Development KIT (JDK). This JDK contains the tools for compiling ,running, packaging and etc.
JRE is the Java Runtime Environment. This contain the tool for running the Java application ( not for developing) . A user, other than a developer, who is going to run a Java program can use JRE. No need to get JDK as the user is not going to develop a program.

Where to download JDK?


SUN has a long list of versions of JDK that they have released so far. you can select the java version and the operating system on which you plan to use ( eg: JDK 1.5, Windows 32bit) .Download it to your local machine. if you can not find the one you want in the listing then look for the previous releases and download it. Once you download , execute the exe file with default option, it will install everything you.

Once it is installed, open the command prompt ( Start ->Run->Type 'cmd' and press 'OK') and type java. you will get a list of options for command 'java' and that indicates that you installed JDK successfully. If you do not see the options listed, then that means the Java path is not in the system environment and you need to set it.

How to set system environment variable
  • Let's assume it is installed in the folder "C:/tools/jdk1.5"
  • Right click on the My Computer icon on your desktop and select properties
  • Click the Advanced Tab
  • Click the Environment Variables button
  • Under System Variable, slect "Path" and click "edit"
  • Append ;C:/tools/jdk1.5/bin at the end of the value of "Path"
  • Click OK
  • Click Apply Change
Now open the command prompt again ( Start ->Run->Type 'cmd' and press 'OK') and type java. you will get a list of options for command 'java'.

Here is a video for installing JDK

Setting up JAVA_HOME System Variable in Windows


Target Audience: Beginners

The bellow instructions will lead you to set up JAVA_HOME environment variable in Windows . Know where JDK is installed. E.g: "C:/tools//jdk1.5"
  • Go to My computer
    For Windows XP : On Desktop or Start->My computer
    For Windows Vista : Start(Windows Icon)->Computer
  • Right click on My Computer icon and select properties
  • Click on Advanced Tab For Windows XP and 'Advance System Settings' task in Windows Vista
  • Click on Environment Variables button
  • Under System Variable, select New button
  • Enter the variable name "JAVA_HOME"
  • Enter the variable value as the install path for the Development Kit (E.g: C:/tools//jdk1.5)
  • Click OK
  • Click Apply Changes
You are done.