Monday, August 19, 2013

Behavior of Object reference when assigned to null and ""

Difference between assigning String reference to null or empty quotes

Instance variables are initialized to a default value each time a new instance is created
But String and other Object references are assigned to null by default.Its always a good practice to assign a value explicitly to variables which increases code readability.

Lets see what happens when we invoke String related methods when String reference is assigned to null or "".

Program 1 :-

public class StringReference {

/**
* @param args
*/
String str1;

public String getStr1() {
return str1;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
StringReference sr = new StringReference();
String strl = sr.getStr1();
System.out.println(strl.length());
}

}
Run the above program it throws nullpointer exception because str1 is a reference and is not pointed to any object. So invoking a reference which doesnt point to an Object will throw null pointer exception.
Output :-
Exception in thread "main" java.lang.NullPointerException
at StringReference.main(StringReference.java:16)

Now lets see assigning String variable to ""

public class StringReference {

/**
* @param args
*/
String str1="";

public String getStr1() {
return str1;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
StringReference sr = new StringReference();
String strl = sr.getStr1();
System.out.println(strl.length());
}

}


Output :- 0

Here Str1="" creates an empty String object

Now Str1 is referring to an object so invoking String related methods liketoUpperCase(),length() etc. will not throw null pointer exception.

Happy Learning

Please provide your valuable comments on this article and share it across your network.



Tuesday, August 6, 2013

Implementing Custom converters in Java Server Faces(JSF)

Custom converters :-
Java Server Faces provides set of standard converters but in some cases we need to implement our own converters.
We want to be date in a particular format or emailId should be of specific format etc.
We can implement this by using java script but if java script is disabled? So its always recommended to perform server side validations.

Steps to be followed for creating custom converters :-
  1. Create a Java class
  2. Implement javax.faces.convert.Converter
  3. Override the unimplemented methods getAsObject(FacesContext,UIComponent,String),getAsString(FacesContext,UIComponent,String)
Example :-

public class CustomConverter implements Converter {

@Override
public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2)
throws ConverterException {
// TODO Auto-generated method stub
return null;
}

@Override
public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2)
throws ConverterException {
// TODO Auto-generated method stub
return null;
}

}


As we get data from web page in form of String all the conversion
is done in getAsObject();

4.Registering custom converter class in faces-config.xml
<converter>
<description>Removes white spaces in the input</description>
<display-name></display-name>
<converter-id>cc</converter-id>
<converter-class>CustomConverter</converter-class>
</converter>

This can be done by component tab in faces-config.xml instead of writing the above lines.

The above converter can be implemented by using
1.Converter attribute :-
<h:inputText id="number" value="#{loginBean.num}" converter="cc">
</h:inputText>

  1. Using Converter tag nested inside the component tag
<h:inputText id="number" value="#{loginBean.num}">
<f:converter id="cc"/>
</h:inputText>


Happy Learning

Please provide your valuable comments on this article and share it across your network.


Converters In Java Server Faces--How to convert form data into respective data types?

Converters in JSF :-


In a web application the data entered in a form is always of String data type.
Consider a web page form having first name,last name and Age.Here names are of String type and Age is Number data type. But when the data is sent from form to server every filed is String type.

How to convert Age field data to integer type before assigning it to managed bean/backing bean? We can explicitly convert it by using Integer.parseInt() etc.Doing this way is tedious and not reusable.

Does JSF provide any mechanism to handle this?
Yes JSF provides a mechanism to convert these String types into respective data type.

  • For implicit data types JSF provides implicit conversion
  • For non primitive types we need to convert explicitly by using Standard Converters( for converting String to Date etc.)or by creating custom converters

First we will see different standard converters.


    SNO
    NAME
    MAIL
    1
    ByteConverter
    Converts input String value to java.lang.Byte
    2
    BooleanConverter
    Converts input String value to java.lang.Boolean
    3
    BigDecimalConverter
    Converts input String value Java.lang.BigDecimal
    4
    BigIntegerConveter
    Converts input String value to java.lang.BigInteger
    5
    CharacterConverter
    Converts input String value to java.lang.Character
    6
    DateTimeConverter
    Converts input String value to java.util.Date
    7
    NumberConverter
    Converts input String value to java.lang.Number
    8
    IntegerConverter
    Converts input String value to java.lang.Integer
    9
    FloatConverter
    Converts input String value to java.lang.Float

Similarly we have EnumConverter,ShortConverter etc.

There are three different ways to use this Standard converters.
  1. Using Converter attribute in input tags
  2. Using nested sub-tag <f:converter>
  3. Using standard converters like <f:convertDateTime>,<f:convertNumber> etc.
Lets see each of the above with examples.

1.Using Converter attribute in input tags :-
  • inputText,inputSecret,inputHidden,outputText are supported tags
  • Lets takes an example of entering date and using converter attribute
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Date</title>
</head>
<body>
<f:view>
<h:form>
Date <h:inputText id="myDate" value="#{loginBean.date}"
converter="javax.faces.DateTime">
</h:inputText>
<h:commandButton value="submit" ></h:commandButton>
<h:message for="myDate"></h:message>
</h:form>
</f:view>
</body>
</html>
  • Here we have used DateTime converter attribute in input text,the value entered should be like Aug 5, 2013--> mmm d, yyyy. If we enter a value with different value it will throw error it is displayed by using <h:message> tag



2.Using nested sub-tag <f:converter> :-

<h:inputText id="myDate" value="#{loginBean.date}">
<f:converter converterId="javax.faces.DateTime" />
</h:inputText>

Here we have used converter tag inside inputText tag

3.Using standard converters :-

we will use <f:convertdateTime> tag
<h:inputText id="myDate" value="#{loginBean.date}">
<f:convertDateTime type="date" dateStyle="short" />
</h:inputText>

There are different types of dateStyles like short,full etc.
Short type will expect date as mm/dd/yyyy or mm/dd/yy .
Long type will expect date as August 5, 2013 etc, this is generally used for outputText tag.

We can change/add the behavior of this converters by developing custom converters.
This will be discussed in my next post.



Happy Learning

Please provide your valuable comments on this article and share it across your network.



Sunday, August 4, 2013

Passing values to methods in Java-Primitives and Objects

In this post we will discuss about how method calling ,value passing happens in Java.

1.Passing Object reference variables to a method :-
  • when we pass an object to a method we are not actually passing object itself, we are passing object reference
  • Reference variable holds the address location of object and a way to load into memory
  • We are not passing actual reference variable,but a copy of reference variable-which holds the copy of bits present in actual value

Lets see below code snippent

Employee emp1=new Employee();
method1(emp1);
void method1(Employee emp)
{
}
Here both emp1 and emp point to same Employee Object in heap.

Example1 :-

public class ObjectReference {
private int var1;
private int var2;

public ObjectReference(int x, int y) {
var1 = x;
var2 = y;
}

public static void main(String[] args) {
ObjectReference op = new ObjectReference(5, 10);
System.out.println("before modify " + op.var1 + "&&" + op.var2);
op.modify(op);
System.out.println("after modify " + op.var1 + "&&" + op.var2);
}

void modify(ObjectReference pop) {
pop.var1 = pop.var1 + 10;
pop.var2 = pop.var2 + 10;
System.out.println("in modify " + pop.var1 + "&&" + pop.var2);
}
}



Output :-
before modify 5&&10
in modify 15&&20
after modify 15&&20

Here both op and pop reference variables are referring to same ObjectReference object .If one reference variable tries to change the value autotically it gets reflected to another varaible.

In the above example in change method we changed the value of var1 and var2 and when we print the value in main method it got reflected.
Now lets see what happens in case of primitive data types.

2.Passing primitive variables to a method :-
When we are passing primitive values to a method we are actually passing copy of bits that represent a value.Suppose we have int a=5,when we pass a to a method we are actually passing copy of bits of value 5. For this we use a terminology passbyvalue rather its passbycopyofvalue .

Example :-
public class PrimitivePass {
int a = 10;

public static void main(String[] args) {
PrimitivePass pp = new PrimitivePass();
System.out.println("Before change" + pp.a);
pp.change(pp.a);
System.out.println("After change" + pp.a);
}

void change(int pNum) {
pNum = pNum + 10;
System.out.println("in change" + pNum);
}
}

output :-
Before change10
in change20
After change10

From the output we can observe that value of a is not changed ,but in previous case we observed for object references the value has changed.

Note :-
  • While passing an Object we actually pass copy of the object reference
  • While passing a primitive type we pass the bits value stored in that variable
  • In both the cases we send copy of bits,in primitives actual value is stored but in case of Object reference it stores the address of the object

Happy Learning

Please provide your valuable comments on this article and share it across your network.



Internationalization(i18n) and Localization(L10N)

Internationalization(i18n):-The process of preparing an application to support more than one language and to represent data in different formats.There are 18 letters between i and n so will refer as i18n

Localization(L10N): -The process of adapting an internationalized application to support a specific region or locale
Lets take an example of Facebook which supports multiple languages like Engilish,Portugal,Hindi etc.
This can be achieved in JSF by using resource bundle.

Steps to Internationalization :-
  • Create a JSF web application in Eclipse
    • Open work space
    • Then New-->Create dynamic web application
    • Select run time environment like Tomcat etc.
    • Place JSF related libraries/Jars into build path(Ex:- ApacheMyFaces.lib etc.)
  • Create a resource bundle :- generally they will be .properties files,where we write text for different languages
  • Loading resource bundle :- There are two ways of implementing
    • faces-config.xml :- use <resource-bundle> is used to i18n for entire application
    • <f:loadBundle> :- is used to i18n for a particule web page

We will now implement i18n and L10N in a web application. We have a login page which supports English and French languages.Text related to this are placed in .properties file
  1. Create two .properties file one for English and One for French languages.Place them under src folder
    ApplicationResource.properties
    LoginId: Login Id:
    Password: Password:
    Login: Login
    Reset: Reset
ApplicationResource_fr.properties
LoginId: Identification d'ouverture :
Password: Mot de passe :
Login: Ouverture
Reset: Remettre à l'état initial
  1. Now we will use this resources in faces-config.xml .We can do this from GUI of faces-config.xml

<application>
<resource-bundle>
<base-name>ApplicationResource</base-name>
<var>msg</var>
</resource-bundle>
<locale-config>
<default-locale>en</default-locale>
<supported-locale>fr_FR</supported-locale>
</locale-config>
</application>
  1. Create a ManagedBean-LoginBean.java and register it in faces-config.xml . We can do this from GUI of faces-config.xml
    LoginBean.java
import java.util.Locale;
import javax.faces.context.FacesContext;

public class LoginBean {
private String uName;
private String password;

public String getuName() {
return uName;
}

public void setuName(String uName) {
this.uName = uName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}
public String changeFrench()
{
FacesContext.getCurrentInstance().getViewRoot().setLocale(Locale.FRENCH);
return "";
}
}

Explanation :-
In LoginBean.java we have a method changeFrench() which will take care of getting text from properties file and converting it into respective language
FacesContext.getCurrentInstance().getViewRoot().setLocale(Locale.FRENCH);
The above statement is used change language to French
  1. Login.jsp

<f:view>
<h:form>
<h:outputText value="#{msg.LoginId}">
</h:outputText>
<h:inputText value="#{loginBean.uName }"></h:inputText>
<br>
<h:outputText value="#{msg.Password}"></h:outputText>
<h:inputText value="#{loginBean.password }"></h:inputText>
<br>
<h:commandButton value="#{msg.Login}"></h:commandButton>
<h:commandButton value="#{msg.Reset}"></h:commandButton>
<h:commandLink action="#{loginBean.changeFrench }">
<h:outputText value="French"></h:outputText>
</h:commandLink>
</h:form>
</f:view>

Here we have used #{msg.LoginId} etc. statements. The variable msg is declared in faces-config.xml .
Now run the application .By default the page will be in english for converting into French click on link French.
Screenshot of Login.jsp in English :-

Click on French the method changeFrench in LoginBean will get called and converts the text into French


If we want to do it for a specific jsp page we can use
<f:loadBundle var="msg" basename="ApplicationResource"/> after <f:view> tag
Happy Learning

Please provide your valuable comments on this article and share it across your network.


Like and Share