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

  }

}


Tuesday, July 28, 2009

How to debug with Tomcat

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


Friday, July 24, 2009

Validate Zip code Using RegEx

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

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

Tuesday, July 21, 2009

Computer Shutdown Utility in Java

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

What is JavaServer Faces

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

  • 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

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

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.*

Difference between JSF and JSP


JSF and MVC

JSF was developed integrating MVC design pattern so that applications can be designed well with greater maintainability. To understand this we need to understand what is MVC design pattern, how MVC helps to design and maintain an application.The MVC design pattern is divided into three separate parts: Model: handles data and logic. View: handles output (presentation) Controller: handles processing of an application. Controllers are used to process user actions. In JSF, Model part (Business logic) is handled by the Managed Beans (backing beans). View is handled by UI Components. Controller is Faces Servlet.

JSF Component

Components in JSF are elements like text box, button, table etc. that are used to create UI of JSF Applications. These are objects that manage interaction with a user. You can create:

  1. Simple components, like text box, button and
  2. Compound components, like table, data grid .

A component containing many components inside it is called a compound component.

JSF allows you to create and use components of two types:
Standard UI Components: JSF contains its basic set of UI components like text fields, check boxes, list boxes, panel, label, radio button etc. These are called standard components. For example:

UIForm represents a user input form that is a container of other components. UICommand represents UI components like buttons, hyperlinks and menu items.

UIInput represents UI components like text input fields, numeric input fields.

Custom UI Components: Generally UI designers need some different, stylish components like fancy calendar, tabbed panes. These types of components are not standard JSF components. JSF provides this additional facility to let you create and use your own set of reusable components .These components is called custom components. One of the greatest powers of JSF is to support third party components .Third party components are custom components created by another vendor. Several components are available in the market, some of them are commercial and some are open source. You can use these pre-built & enhanced components in UI of your web application .Suppose u need a stylish calendar , u have an option to take it from third party rather than creating it .This will help you to save your time & cost creating effective & robust UI and to concentrate on business logic part of web application.If you want to create custom components then its necessary to either implement UIComponent interface or extend UIComponentBase class that provides default behavior of components. These may be responsible for its own display or the renderer is used for its display. These components are stored in component tree on the server and they maintain state in between client requests. These components are manipulated on the sever in java code.

Monday, July 20, 2009

Taglibrary for JSF

JSF application typically uses JSP pages to represent views. JSF provides some useful special tags to enhance these views. JSF provides 43 tags in two standard JSF tag libraries:
  1. JSF Core Tags Library
  2. JSF Html Tags Library

Even a very simple page uses tags from both libraries.
<%@ taglib uri=”http://java.sun.com/jsf/core“ prefix=”f” %>

In the above code fragment we have imported two JSF tag libraries with the help of taglib directive. JSF Core Tag Library contains set of JSF core tags while JSF Html Tags Library contains set of html tags. Prefix is used to use tags defined in tag library. Here we are using conventional names f and h for Core & Html tags respectively. We have the choice to choose any name for the prefixes.

JSF Html Tags

JSF HTML tags are divided into following category:

Inputs (inputText, inputTextarea)
Outputs (outputText, outputLabel)
Commands (commandButton)
Selections (selectOneRadio, selectOneListbox, selectOneMenu for radio buttons, list boxes, menu etc)
Layouts (panelGrid)
Data table (dataTable)
Errors and messages (message, messages)

Some examples have been given below to understand how to use these tags and its attributes:

 

In JSF Html Tag Library there are 25 core tags:

  • column creates column in a dataTable
  • commandButton creates button
  • commandLink creates link that acts like a pushbutton
  • dataTable creates a table control
  • form creates a form
  • graphicImage displays an image
  • inputHidden creates hidden field
  • inputSecret creates input control for password
  • inputText creates text input control (single line)
  • inputTextarea creates text input control (multiline)
  • message displays the most recent message for a component
  • messages displays all messages
  • outputFormat creates outputText, but formats compound messages
  • outputLabel creates label
  • outputLink creates anchor
  • outputText creates single line text output
  • panelGrid creates html table with specified number of columns
  • panelGroup used to group other components where the specification requires one child element
  • selectBooleanCheckbox creates checkbox
  • selectManyCheckbox creates set of checkboxes
  • selectManyListbox creates multiselect listbox
  • selectManyMenu creates multiselect menu
  • selectOneListbox creates single select listbox
  • selectOneMenu creates single select menu
  • selectOneRadio creates set of radio button

JSF Core Tags

These tags allows you to take advantages of features of JSF framework, like validation, conversion , event handling. Core library is stepchild of Html library. i.e. core library supports the html library. Core tag library also contains tags for views and sub-views , loading resource bundle, adding arbitrary text to a page. Some examples of JSF core tags are given bellow:
  • f: view tag is used to create top level view
  • f: subview tag is used to create subview of a view.
  • f: validator tag is used to add a validator to a component.
  • f: converter tag is used to add an arbitrary converter to a component.
  • f: actionListener tag is used to add an action listener to a component.
  • f:valueChangeListener tag is used to add a valuechange listener to a component
Some examples have been given below to understand how to use these tags:


f: view tag is used to create top level view and is a container for all JSF component tags on a page. Where locale attribute provides several options for presenting localized views of your application. Here "en" represents English and if we give velue "fr" to locale attribute then french view will be displayed. So this attribute is useful for internationalization purpose.


The Validator tag registers a Validator on the component associated with the enclosing tag. In validatorId field, we give the value of one of the validator-id element of a validator in your Faces configuration file.
In JSF Core Tag Library there are 18 core tags.
  • f :view Creates the top-level view
  • f:subview Creates a subview of a view
  • f:attribute Adds an attribute to a component
  • f:param Constructs a parameter component
  • f:converter Adds an arbitrary converter to a component
  • f:converterDateTime Adds a datetime converter to a component
  • f:converterNumber Adds a number converter to a component
  • f:actionListener Adds an action listener to a component
  • f:valueChangeListener Adds a valuechange listener to a component
  • f:validator adds a validator to a component
  • f:validateDoubleRange Validates a double range for a component’s value
  • f:validateLength Validates the length of a component’s value
  • f:validateLongRange Validates a long range for a component’s value
  • f:facet Adds a facet to a component
  • f:loadBundle Loads a resource bundle, stores properties as a Map
  • f:selectitems Specifies items for a select one or select many component
  • f:selectitem Specifies an item for a select one or select many component
  • f:verbatim Adds markup to a JSF page


Lifecycle of JSF

Life cycle of a JSF web application starts when user makes a request. On submission of a page various further tasks are performed like validation of data provided in components in the view, data conversion according to types specified on server side etc. So series of steps that an application follows is called life cycle.

A JSF application typically follows six steps in its life:
  1. Restore view phase: This phase starts when a user requests a JSF page by clicking a link, button etc. In this phase view generation of the page, binding of components to its event handlers and validators are performed and view is saved in the FacesContext object. The FacesContext object contains all the state information JSF needs to manage the GUI component's state for the current request in the current session. The FacesContext stores the view in its viewRoot property. All the JSF components are contained by viewRoot for the current view ID. Component tree of a page is newly built or restored. A request comes through the FacesServlet controller. The controller checks the request and takes the view ID i.e. name of the JSP page. View ID is used to look up the components in the current view. JSF controller uses this ID if the view already exists . If the view doesn't already exist, the JSF controller creates it. The created view contains all components.
  2. Apply request values phase: The purpose of this phase is for each component to retrieve its current state. After restoring of component tree in previous phase each component in the tree retrieves its new value and store it locally. Component values are typically retrieved from the request parameters.If immediate attribute of a component is set to true, then the validation, conversion, and events associated with the component is processed in this phase. If a component's immediate event handling property is not set to true, the values are converted. Suppose field is bound to be an Integer property, the value is converted to an Integer. An error message associated with the component is generated if this conversion fails, and queued in the FacesContext. This message will be displayed during the render response phase, along with any validation errors resulting from next process validation phase. At the end of this phase, the components are set to their new values, and messages and events have been queued.
  3. Process validations phase: During this phase local values stored for the component in the tree are compared to the validation rules registered for the components. If local value is invalid, an error message is added to FacesContext, and the component is treated invalid then JSF proceeds to the render response phase and display the current view showing the validation error messages. If there were conversion errors from the apply request values phase, the messages for these errors are also displayed. If there are no validation errors, JSF proceeds ahead to the update model values phase.
  4. Update model values phase: After confirming that data is valid in the previous phase local values of components can be set to corresponding server side object properties i.e. backing beans. So bean properties will be updated .If the local data cannot be converted to the types specified by the bean properties, the life cycle proceeds directly to the render response phase and errors are displayed.
  5. Invoke application phase: Before this phase the component values have been converted, validated, and applied to the bean objects, so you can now use them to execute the application's business logic. Application-level code is executed such as submitting a form or linking to another page.For example user moves to the next page you will have to create a mapping in the faces-config.xml file. Once this navigation occurs, you move to the final phase of the lifecycle.
  6. Render response phase: In this phase JSP container renders the page back to the user,if jsp is used by application i.e. view is displayed with all of its components in their current state.If this is an initial request, the components will be added to the component tree. If this is not an initial request, the components are not added because they are already added to the tree.The state of the response is saved after rendering of the content of the view, so that subsequent requests can access it and it is available to the restore view phase.

Sunday, July 19, 2009

Create New Java Annotation

import java.lang.annotation.Documented;

import java.lang.annotation.ElementType;

import java.lang.annotation.Inherited;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;



@Documented

@Retention(RetentionPolicy.RUNTIME)

@Target {ElementType.TYPE, ElementType.METHOD,

ElementType.CONSTRUCTOR,

ElementType.ANNOTATION_TYPE,

ElementType.PACKAGE,

ElementType.FIELD,

ElementType.LOCAL_VARIABLE})

@Inherited

public @interface Unfinished

{

public enum Priority { LOW, MEDIUM, HIGH }

String value();

String[] changedBy() default "";

String[] lastChangedBy() default "";

Priority priority() default Priority.MEDIUM;

String createdBy() default "prabir karmakar";

String lastChanged() default "01/01/2009";

}

Saturday, July 18, 2009

Regular Expression Using String Class

You can use Java Regular Expression for performaing complex validation on String objects.
You can also use matchs() method of String class for performaing Regular Expression. This function returns boolean value, return "true" if string object passes the regular expression validation other wise return "false".
Example:
String namePattern = "[a-zA-Z_]+";
boolean retval = name.matches(namePattern);
if(retval)
System.out.println("Contains only alphabet");
else
System.out.println("validation fail");
pattern can take only alphabet of any case and underscore of any length.

JSF Validator

You can use Custom Validator for validating editable component in JavaServer Faces. Java Community provide an Interface called "Validator" it hava method validate() having
syntax:
public void validate(FacesContext context, UIComponent component, Object value)
throws ValidatorException

You need to implement this interface and provide the implementation for validate method.
Example:-

package com.validators;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
public class NameValidator implements Validator
{
public void validate(FacesContext context, UIComponent component, Object value)
throws ValidatorException
{
String name = (String) value;
String errorLabel = "Please enter a valid Name.";
if(!component.getAttributes().isEmpty())
{
errorLabel = (String) component.getAttributes().get("errordisplayval");
}
if(name.length()==0)
{
;
}
else
{
String namePattern = "[a-zA-Z_]+";
boolean retval = name.matches(namePattern);
if(!retval name.length()>8)
{
FacesMessage message = new FacesMessage();
message.setSeverity(FacesMessage.SEVERITY_ERROR);
message.setSummary(errorLabel);
message.setDetail(errorLabel);
throw new ValidatorException(message);
}
}
}
}