Showing posts with label Utility Classes. Show all posts
Showing posts with label Utility Classes. Show all posts

Friday, June 21, 2013

Use of CountDownLatch API in java

This is a brand new API introduced in Java 5. This API is dealing with synchronization. It means that at any given point of time only one thread can access the block of code.

This API is under the java.util.concurrent package.

This is best suitable where you want to initialized all the sub programs before completing or other work.

Suppose, we have a program, which has LogManager and ErrorManager objects. At the same time we want to initialize all these objects then only the main program can do other work.

The CountDownLatch API has the following methods:

  1. await() - Causes the current thread to wait until the latch has counted down to zero.
  2. await(long timeout, TimeUnit unit) - Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted, or the specified waiting time elapses.
  3. countDown() - Decrements the count of the latch, releasing all waiting threads if the count reaches zero.
  4. getCount() - Returns the current count.







Thursday, August 16, 2012

Java object Describer instead of toString() method

Consider you have a JavaBean/DTO/VO, It has some properties. Sometime at runtime we are trying to print object's properties's value with property name, just for debugging purpose.

In this situation, most of the time we override the toString() method of Object class and for the shake of convenience, we just use the object name in the print method.

If you notice carefully, you have to write code for that feature. The solution is to create some generic solution for that, so that that can be used everywhere.

I have created an Interface named Describable and it has one menthod named describe().







Also, created an abstract class named ValueObject that implements Describable and Serializable interface.



 Test program would be given below:




















This way you can reduce your duplicate coding and this is used by almost all java class.

If you wish to use the utility, you can download the binary and use.

Sunday, May 6, 2012

How to get JVM PID(Process ID) from Java Program.

As you all know each and every process running in the Operation System has an unique ID. In Unix/Linux it is easy to find the PID from java using Runtime class, but in Windows, earlier versions of Java it difficult to get the PID of the JVM. In Java5.0, it is easy to find the OS Process ID assigned to the JVM.
There is an utility that is ment to return the PID of all running JVM on the machine or remote machine. This utility is not only ment for PID, you can also get the argument and complete package name.

The good thing with this tool is you can monitor any JVM on the network just you have to have the IP of that machine.

Let's discuss about the utility.

In the binary folder you can find an executable file named "jps.exe". The complete name is "JVM Process Status tool", this utility takes some parameters and work as per that option.

Syntax:

jps [options] [hostid]

Here options is the list of options and hostid is the IP of the remote machine for which you want to monitor.

"jps" options are listed below:
  • -l Output the full package name for the application's main class or the full path name to the application's JAR file.
  • -m Output the arguments passed to the main method. The output may be null for embedded JVMs.
  • -q Suppress the output of the class name, JAR file name, and arguments passed to the main method, producing only a list of local VM identifiers.
  • -v Output the arguments passes to the JVM.
  • -help Returns the syntax of this tool.

You don't need to use the "hostid" command argument, if you want to list JVM processes on the local machine. But to list JVM processes on a remote, you need to use "hostid" to specify how to connect to the remove machine.

Getting Help : jps.exe -help

Getting only PID : jps.exe -q

Getting only main Class name : jps.exe -m

Getting with complete package name : jps.exe -l

Getting with argument : jps.exe -v

Hope this program will helps you to understand the utility.

Thursday, November 19, 2009

Language Specific String Sorting

I have created an utility class for sorting strings on the basis of natural language. You can use this utility to sort array of strings, list of strings.



You can download StringSorter Utility

Saturday, November 14, 2009

Rules For Defining Immutable Objects

Below are some rule for creating Immutable Objects in Java, Immutable Objects are those objects: we can't change the state of the object after construction. Example of Immutable object is String Class.

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


final public class ImmutableRGB {

//Values must be between 0 and 255.
final private int red;
final private int green;
final private int blue;
final private String name;

private void check(int red, int green, int blue) {
if (red < 0 || red > 255
|| green < 0 || green > 255
|| blue < 0 || blue > 255) {
throw new IllegalArgumentException();
}
}

public ImmutableRGB(int red, int green, int blue, String name) {
check(red, green, blue);
this.red = red;
this.green = green;
this.blue = blue;
this.name = name;
}


public int getRGB() {
return ((red << 16) | (green << 8) | blue);
}

public String getName() {
return name;
}

public ImmutableRGB invert() {
return new ImmutableRGB(255 - red, 255 - green, 255 - blue,
"Inverse of " + name);
}
}

Tuesday, November 10, 2009

Get Property names of a Bean


import java.io.Serializable;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.beans.IntrospectionException;

public class GetBeanAttr implements Serializable {
private Long id;
private String name;
private String latinName;
private double price;

public GetBeanAttr() {
}

public static void main(String[] args) {
try {
BeanInfo beanInfo = Introspector.getBeanInfo(GetBeanAttr.class);
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();

for (PropertyDescriptor pd : pds) {
String propertyName = pd.getName();

System.out.println("propertyName = " + propertyName);
}
} catch (IntrospectionException e) {
e.printStackTrace();
}
}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

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

public String getLatinName() {
return latinName;
}

public void setLatinName(String latinName) {
this.latinName = latinName;
}

public double getPrice() {
return price;
}

public void setPrice(double price) {
this.price = price;
}
}

Notify when Bean property changed

We want to know or to get notified when the bean property is changed. For that we create a Bean having a property named name with getter/setter method.

First we need a PropertyChangeSupport field to the bean, with this object we will fire the property change event. When we need to listen for the change we have to create an implementation of a PropertyChangeListener. In this example we'll just use the MyBean class as the listener.

The PropertyChangeListener has a method called propertyChange and inside this method we'll implementing the code to get the event fired by the PropertyChangeSupport.

Friday, November 6, 2009

Uses of Console class in Java

Java 6 introduce a new class Console in the family of java.io.
This Class is used to access the character-based console device, if any, associated with the current Java virtual machine.

Whether a virtual machine has a console is dependent upon the underlying platform and also upon the manner in which the virtual machine is invoked. If the virtual machine is started from an interactive command line without redirecting the standard input and output streams then its console will exist and will typically be connected to the keyboard and display from which the virtual machine was launched. If the virtual machine is started automatically, for example by a background job scheduler, then it will typically not have a console.

If virtual machine has a console then it is represented by a unique instance of this class, which can be obtained by invoking
System.console().
If JVM does not recognize any console, then this function returns null.

The methods in this class are synchronized. You can read line of text by using the
readLine()
method. You can also read secure data such as Password by using
readPassword()
method. You can also format text by using
format()
. You can get PrintWriter and PrintReader by using
reader(), writer()
method.

Example: Get user name and password from the user.

public class IConsole
{
public static void main(String arg[])
{
Console console = System.console();
if(console!=null)
{
String userName = console.readLine("User Name:");
char [] password = console.readPassword("Password:");
console.printf("User Name is %1$s , Password is %1s",userName, String.valueOf(password));
}
}
}

Wednesday, September 30, 2009

Why Enum in Java

If you use Java1.5, there is a feature declaring constant value i.e Enum. An Enumerated type defines a finite set of symbolic names and their values. These symbolic names are called enum constants or named constants.

Well, you can declared such constants by static final variable like:


public class MyConstants
{
public static final int BUSY = 1;
public static final int IDLE = 2;
public static final int BLOCKED = 3;
}


such constants are not typesafe, as any int value can be used where we need to use a constant declared in the MyConstants class. Such a constant must be qualified by the class name. When such a constant is printed, only its value is printed, but we unable to print its name. One important thing is that, if you want to modify the value of any constant, then you have to compile both, the class or interface that declare the constant and the class where this constants are used. This is required bkz, constant names are substituted by its value at compile time.

Please look the code Snippet for the approach outlined above.

public enum ConstantEnum {
BUSY(3),IDLE(2);

int data;
private ConstantEnum(int refValue) {
data = refValue;
}

public int getValue()
{
return data;
}
}

public class TestValue {
public static void main(String arg[])
{
int i= ConstantEnum.BUSY.getValue();
System.out.println("using Enum value :"+ConstantEnum.BUSY);
System.out.println("using static final :"+MyConstants.BUSY);
}
}

Saturday, August 22, 2009

Efficient use of add(0,object) method of java.util.List

If you want an efficient access of add(0,object) method of List interface, where quick and random access of the list is not a primary concern. You must use java.util.LinkedList instead of ArrayList,LinearList and Queue.

You can check the efficiency of LinkedList inplementation by the given example:

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

public class EfficientList
{

/**
* @author Prabir Karmakar
*/
public static void main(String[] args)
{
List list = new ArrayList();
System.out.println("Using ArrayList..");
System.out.println("Before Manupulation:"
+System.currentTimeMillis());
for(int i=0;i<10000;i++)
{
list.add(0, "prabir"+i);
}
System.out.println("After Manupulation:"
+System.currentTimeMillis());

List list1 = new LinkedList();
System.out.println("Using LinkedList..");
System.out.println("Before Manupulation:"
+System.currentTimeMillis());
for(int i=0;i<10000;i++)
{
list1.add(0, "raj"+i);
}
System.out.println("After Manupulation:"
+System.currentTimeMillis());
}
}

Program Output

Using ArrayList..
Before Manupulation:1250946828955 (current time Millis)
After Manupulation:1250946829024 (current time Millis)
Using LinkedList..
Before Manupulation:1250946829024 (current time Millis)
After Manupulation:1250946829034 (current time Millis)

Saturday, August 8, 2009

Printing from Java Program

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;


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

DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
PrintService[] pservices = PrintServiceLookup.lookupPrintServices(flavor, aset);
int printnbr = 0;
DocPrintJob pj = pservices[printnbr].createPrintJob();
try
{
FileInputStream fis = new FileInputStream("C:\\YServer.txt");
Doc doc = new SimpleDoc(fis, flavor, null);
pj.print(doc, aset);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}

Monday, August 3, 2009

Format Date/Time Using System package

You can easily format date/Time using System package in java.

public class PrintDateTime
{
public static void main(String [] arg)
{
//printf is not line feed and carriage return, so you have to put a line break.
System.out.printf("Today is: %1$tm/%1$te/%1$tY", Calendar.getInstance());
System.out.print("\n");
System.out.printf("Time is: %tr", Calendar.getInstance());
System.out.print("\n");
System.out.printf("Time is: %tT", Calendar.getInstance());
}
}

Here
  • t means, you want to deal with date/time.
  • m means, you want month from the date.
  • e means, you want day from the date.
  • Y means, you want Year from the date.
  • r means, you want time as 12-hour clock with AM/PM
  • T means, you want time as 24-hour clock.
Output:
Today is: 08/3/2009
Time is: 09:55:45 PM
Time is: 21:55:45

Formating String using String Class

public class FormatString
{
public static void main(String [] arg)
{
Object ob[] = {"prabir",27};
st = String.format("My name is %s, I am %d years old", ob);
System.out.println(st);

st = String.format("The value of PI is:%f", Math.PI);
System.out.println(st);
//specify no. of decemals
st = String.format("The value of PI is:%.2f", Math.PI);
System.out.println(st);
}
}

Here
  • s expecting string value.
  • d expecting numeric value without decimal.
  • f expecting float value.
  • .2 specify no of decimal places.
Output:
The value of PI is: 3.141593
The value of PI is: 3.14

Saturday, August 1, 2009

Reading file with Scanner

You can easily use Scanner Class to read a physical file, you can refer given example:
public class ReadFile
{
private Scanner fileScanner = null;
public ReadFile()
{
this(null);
}
public ReadFile(File fileName)
{
if(fineName==null)
{
throw new NullPointerException("File can not be null.");
}
fileScanner = new Scanner(fileName);
//use line separator delimiter for fetch one by one line from the file, if you don't it fetch one by one word.
fileScanner.useDelimiter(Constant.LINE_SEP);
}
public void read()
{
while(fileScanner.hasNext())
{
System.out.println(fileScanner.next());
}
fileScanner.close();
}
public static void main(string [] arg)
{
try
{
File file = new File(arg[0])
ReadFile fileReader = new ReadFile(file);
fileReader.read();
}
catch(FileNotFoundException ex)
{
ex.printStack();
}
}
}

use this this command:
java ReadFile data.txt

Thursday, July 30, 2009

Create Read Only List

You can create read only List using Collections, complete code is given bellow:

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

/*
* @author: Prabir Karmakar
*/

public class UnModifiable
{
   private List list = null;
   private List fixed = null;

   public void initializeList(String args[])
       throws Exception
   {
      if(args.length<=0)          throw new Exception("Empty String: please enter string");       list = new ArrayList();
      for(String elem : args)
      {
         list.add(elem);
      }
   }

   public void
createUnmodifiableList()
   {
     fixed = new ArrayList();
     fixed = Collections.unmodifiableList(list);
   }

   public void doSomeChange(String str)
   {
     if(fixed==null)
       throw new NullPointerException("Read-Only list not initialized.");
     try
     {
       fixed.add(str);
     }catch(UnsupportedOperationException uox)
     {
        throw new UnsupportedOperationException("Can't modify readonly list.");
     }
   }

   public void fetch()
   {
     for(String str : list)
     {
       System.out.println(str);
     }
   }

   public static void main(String arg[])
   {
     UnModifiable unList = new UnModifiable();
     String param[] = {"prabir","rahul","kumar"};
     try
     {
       unList.initializeList(param);
       unList.createUnmodifiableList();
       unList.fetch();
       unList.doSomeChange("raj");
      }catch(Exception ex)
      {
        System.out.println(ex.getMessage());
      }
   }
}

Wednesday, July 29, 2009

Use Of Scanner Class

Java 5 provides a utility class named Scanner which is very power full for parsing/Tokening any strings, Input Streams, Files, Channels.

Do not compare it with StringTokenizer utility class, this is only working with strings.

One Important feature of Scanner class is that you can parse any primitive datatype from the given strings, Input Streams, Files and Channels. 

e.g: suppose i want to take only number from the command line(InputStream), then you can use this class. the implementation of this class is very simple, there are getter methods for almost all primitive datatypes.

The constructor can take String, InputStream, File etc.

public class TestScanner

{

  public static void main(String arg[])

  {

    Scanner scan = new Scanner(System.in);

    int retNum = scan.nextInt();

    System.out.println("Yaaaa , You Have Entered :"+ retNum);

  }

}

Default delimiter for Scanner is space between two words. if you want to use another delimiter then you have to set the delimiter for that Scanner, use this Syntax:

scanner.useDelimiter(",");

e.g: if i want to get all boolean values from the scanner, then

public class FetchBooleanScanner

{

  public static void main(String arg[])

  {

    Scanner scan = new Scanner("prabir,2,true,prabirmj,3,false,raj,4,false");

    scan.useDelimiter(",");

    while(scan.hasNext())

    {

        if(scan.hasNextBoolean())

        {

           System.out.println(scan.nextBoolean());

         }

         else

         {

             scan.next();

          }

    }

  }

}

Scanner can also operate with Regular Expression using scanner object method findInLine().

public class TestScannerRegEx

{

  public static void main(String arg[])

  {

    String input = "1 persion 2 persion black  persion white persion"; 

    Scanner scan = new Scanner(input);

    scan.findInLine("(\\d+) persion (\\d+) persion (\\w+) persion (\\w+)");

    MatchResult result = scan.match();

    for (int i=1; i<=result.groupCount(); i++)

        System.out.println(result.group(i));

    scan.close(); 

  }

}