Archive for July 2009

Create Read Only List

July 30, 2009

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());
      }
   }
}

Advertisements

Use Of Scanner Class

July 28, 2009

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(); 

  }

}

How to debug with Tomcat

July 28, 2009

You can easily debug any Jsp page and Java file using Tomcat in Eclipse with the help of Java Platform Debugger Architecture (JPDA) technology from Sun helps when you need to debug a running Java application in all situations. JPDA is a collection of APIs aimed to help with debugging Java code.

set following environment variables:

set JPDA_TRANSPORT=dt_socket
set JPDA_ADDRESS=5050

start tomcat using

catalina jpda start

Validate Zip code Using RegEx

July 24, 2009

public class ZipCodeValidator
{
public boolean validate(String zip)
{
String zipCodePattern = “\\d{5}((-)?\\d{4})?“;
return zip.matches(zipCodePattern);
}

public static void main(String arg[])
{
ZipCodeValidator zipCodeValidate = new ZipCodeValidator();
boolean retVal = zipCodeValidate.validate(“67652-5651”);
if(retVal)
System.out.println(“valid zip code found”);
else
System.out.println(“invalid zip code found”);
}
}

Validate E-Mail using RegEx

July 24, 2009

public class EMailValidator
{
public boolean validate(String email)
{
//Set the email pattern string
Pattern p = Pattern.compile(“.+@.+\\.[a-z]+”);
//Match the given string with the pattern
Matcher m = p.matcher(email);
//Check whether match is found
return m.matches();
}
public static void main(String arg[])
{
EMailValidator emailValidator = new EMailValidator();
boolean retVal = emailValidator.validate(“prabir.karmakar@acclaris.com“);
if(retVal)
System.out.println(“It is valid email”);
else
System.out.println(“It is invalid email”);
}
}

Computer Shutdown Utility in Java

July 21, 2009

Click http://groups.google.co.in/group/javawikiforbeginners for download utility

What is JavaServer Faces

July 21, 2009
JSF is new standard framework, developed through Java Community Process (JCP) that makes it easy to build user interfaces for java web applications by creating reusable components in a page. You can think of JSF framework as a toolbox that is full of ready to use components. So JSF applications are event driven. You typically embed components in a jsp page using custom tags defined by JSF technology and use the framework to handle navigation from one page to another. Components can be nested within another component, for example, input box, button in a form. JSF is based on well established Model-View-Controller (MVC) design pattern. Applications developed using JSF frameworks are well designed and easy to maintain then any other applications developed in JSP and Servlets. Unlike request-driven MVC web frameworks, JSF uses a component-based approach. The state of UI components is saved when the client requests a new page and restored when the request is returned JSF includes: A set of APIs for representing user interface (UI) components and managing their state, handling events and input validation, converting values, defining page navigation, and supporting internationalization and accessibility A default set of UI components Two JavaServer Pages (JSP) custom tag libraries for expressing a JavaServer Faces interface within a JSP page. A server-side event model State management Managed Beans (JavaBeans created with dependency injection)

Advantages of using JSF

July 21, 2009
  • JSF provides standard, reusable components for creating user interfaces for web applications.
  • SF provides many tag libraries for accessing and manipulating the components.
  • It automatically saves the form data and repopulates the form when it is displayed at client side.
  • By design and concept it allows creating reusable components. That will help to improve productivity and consistency.
  • Many quality and ready to use components are available from Apache, Richfaces, Infragistics, Oracle, etc.
  • The concept of action and action listener for button invocation is good.
  • Has very good support for EL expression that improves the user interface code readability.
  • The concept the validator is excellent.JavaScript code is embedded as part of the component.

Versions Of JSF

July 21, 2009

JavaServer Faces stats with version

  1. JSF 1.0
  2. JSF 1.1
  3. JSF 1.2
  4. Upcoming JSF 2.0

Features Of JSF

July 21, 2009

JSF is a rich featured framework of JAVA technology. Some of the features are given bellow:

  1. JSF is standard web user interface framework for Java.
  2. JSF is a component framework.*
  3. UI components are stored on the Server.*
  4. Easy use of third party components.
  5. Event driven programming model.*
  6. Events generated by user are handled by the server.
  7. Navigation handling.*
  8. Can automatically synchronize UI components.
  9. International language support.*