Saturday, February 4, 2012

HTML DTD for ICE faces JSPX


Resolving the browser compatibility issues while developing the web applications is a bit complex. Most of the times developer tries to write the browser specific code. But, it is not possible to implement the browser specific code for all the pages of the application in all the scenarios and it is not required if we specify the DOCTYPE. Specifying the doctype for the page will decrease the most of the browser compatibility issues.


A doctype declaration refers to the rules for the markup language, so that the browsers render the content correctly.


The doctype declaration is not an HTML tag; it is an instruction to the web browser about what version of the markup language the page is written in.
The doctype declaration refers to a Document Type Definition (DTD). The DTD specifies the rules for the markup language, so that the browsers render the content correctly.


The doctype declaration should be the very first thing in an HTML document, before the tag.


There are different DTDs for the HTML page as specified below:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/transitional.dtd">



Specifying the DTD on JSF page which developed using ICE faces might not accept as you specify on the normal HTML page. You have to place it after the declaration of f:view tag.



<jsp:root version="2.1" xmlns:jsp="http://java.sun.com/JSP/Page"          xmlns:f="http://java.sun.com/jsf/core"          xmlns:h="http://java.sun.com/jsf/html"          xmlns:ice="http://www.icesoft.com/icefaces/component">   
<jsp:directive.page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"/>   
<f:view>   
<ice:outputDeclaration doctypeRoot="HTML" doctypePublic="-//W3C//DTD HTML 4.01 Transitional//EN" doctypeSystem="http://www.w3.org/TR/html4/strict.dtd" />
<!-- Place the required code here --> 
</f:view>
</jsp:root>


Click here To Read more about fixing the browser compatibility issues.

Tuesday, January 24, 2012

equals() and hashCode() methods of Object Class

HashTable, HashMap and HashSet are the Collection classes in java.util package that make use of hashing algorithm to store objects. In all these Collection classes except HashSet, objects are stored as key-value pairs. For the storage and the retrieval of any user-defined objects it is a good practice to override the following methods which is mentioned below,
  • hashCode()
  • equals()
These methods are available in the Object class and hence available to all java classes.Using these two methods, an object can be stored or retrieved from a Hashtable, HashMap or HashSet.
hashCode() method
This method returns a hashcode value as an int for the object. Default implementation for hashcode() should be overridden in order to make searching of data faster. The implementation of hashCode() method for an user-defined object should be calculated based on the properties of the class which we wish to consider.
equals() method
This method returns a boolean which specifies whether two objects are equal or not. The default implementation of equals() method given by the Object Class uses the '==' operator to compare two object references, and returns true only if they refer to the same object. But, we can meaningfully re-define this equals() method to have en equality check based on our own criterias.
Consider the following code, which defines two user defined classes Employee and EmployeeId which are supposed to be stored in a Map.
Employee.java

public class Employee {
        private String name;

        public Employee(String name){
               this.name = name;
        }

        public String toString(){
        return name;
        }
}
EmployeeId.java

public class EmployeeId {

        private String id;

        public EmployeeId(String id){
               this.id = id;
        }

        public String toString(){
               return id;
        }      
}
The following class makes use of the above classes by storing it in a Map for later retrieval. We are adding Employee objects into the Map keyed with Employee Id.
HashCodeTest.java

public class HashCodeTest {

        public static void main(String[] args) {

               Map employees = new HashMap();

               employees.put(new EmployeeId("111"), new Employee("Johny"));
               employees.put(new EmployeeId("222"), new Employee("Jeny")); // Line A
               employees.put(new EmployeeId("333"), new Employee("Jessie"));

               Employee emp =  employees.get(new EmployeeId("222")); // Line B
               System.out.println(emp); // Line C
        }
}
In Line B, we try to retrieve the Employee object who has Employee Id with a value of 222. We expect the output to be 'Jeny', because the Employee with Employee Id (222) was already there in the Collection, but surprisingly, the output of the above code is null. The reason is that we did not override the equals() method for EmployeeId and Employee classes because the default implementation of equals() in the Object class considers the new EmployeeId("222") in the put statement and new EmployeeId("222") in the get statement as two different instances, and hence the call to get() in Line B returns null.
Let us look at how the same code works when we provide our desired implementation for hashcode() and equals() methods. We basically override hashcode() here just to make the object to be searched fast.
Employee.java

public class Employee {

        private String name;

        public Employee(String name){
               this.name = name;
        }

        public String toString(){
               return name;
        }

        @Override
        public boolean equals(Object obj){

               if(obj == null) {
                       return false;
               }
               if(obj.getClass() != getClass()){
                       return false;
               }

                Employee emp = (Employee)obj;
               if(this.name == emp.name){
                       return true;
               }
               return false;
        }

        @Override
        public int hashCode(){
               return name.hashCode();
        }
}
EmployeeId.java

public class EmployeeId {

        private String id;

        public EmployeeId(String id){
               this.id = id;
        }

        public String toString(){
               return id;
        }      

        public boolean equals(Object obj){

        if(obj == null)
               return false;

        if(obj.getClass() != getClass()){
               return false;
        }

        EmployeeId empId = (EmployeeId)obj;
        if(this.id == empId.id){
               return true;
        }
        return false;
        }

        @Override
        public int hashCode(){
               return id.hashCode();
        }
}
Now, we get the desired output 'Jeny', because as per our implementation for the equals() method, the new EmployeeId("222") in the put statement and new EmployeeId("222") in the get statement are considered one and the same.

Monday, January 16, 2012

Introduction to RESTful Web Services

REST is a “Representational state transfer” and it is firstly introduced by Roy Fielding (Fielding is one of the principal authors of the HTTP specification and a co-founder of the Apache HTTP Server project) in his 2000 doctoral dissertation.

REST-style services (i.e., RESTful services) adhere to a set of constraints and architectural principles that include the following:
  1.  RESTful services are stateless. As Fielding writes in Section 5.1.3 of his thesis, “each request from client to server must contain all the information necessary to understand the request, and cannot take advantage of any stored context on the server.”
  2. RESTful services have a uniform interface. This constraint is usually taken to mean that the only allowed operations are the HTTP operations: GET, POST, PUT, and DELETE.
  3. REST-based architectures are built from resources (pieces of information) that are uniquely identified by URIs. For example, in a RESTful purchasing system, each purchase order has a unique URI.
  4. REST components manipulate resources by exchanging representations of the resources. For example, a purchase order resource can be represented by an XML document. Within a RESTful purchasing system, a purchase order might be updated by posting an XML document containing the changed purchase order to its URI

Friday, December 30, 2011

Thanks to 2011

This is the time say thanks to 2011, it brought remarkable changes in my life and its gave me the confidence to start new things which takes me into redesign myself.


I have started my new career with a new team in a new company along with the 2011. As it is passing away I continued in learn new things, interacting with many number of people, continued in improving communication skills, I have learned many technical skills. So, I got the many appreciations and many recognitions for my dedicated work in the team. Finally I like to stress is 2011 brought considerable change in my work.


I am very sad for the retiring of 2011, and I am very happy in welcoming the new year 2012 which might bring more colorful and more happiness into my life. I hope 2012 brings more remarkable changes than 2011, and I wish you all the best for you all.


I am welcoming you all in inviting the new year.... :) so...


HAPPY NEW YEAR 2012 all for you my dear friends...:)

Saturday, November 19, 2011

Front Controller - Core J2EE design patterns

Front Controller pattern tells that, “There should be a Single entry and exit point for each and every request made by the user on a single application expecting for a single type of result and the same single controller may interact with different systems or programs to build the response for the request”.


For a better manageability of an application use a Front Controller as the initial point of contact for handling all related requests. The Front Controller centralizes control logic that might otherwise be duplicated, and manages the key request handling activities.


The Front Controller pattern suggests centralizing the handling of all requests but, it does not limit the number of handlers in the system, as does a Singleton. An application may use multiple controllers in a system, each mapping to a set of distinct services



Most of the current MVC based frameworks are using the Front Controller design pattern internally to handle the request from the multiple users.
  • Action Servlet is the Front controller in the Struts Framework (1.x)
  • Faces Servlet is the Front Controller in the JSF Framework.

Advantages:

Centralizes The Control: It works like a central place to handle system services and business logic across multiple requests and manages business logic processing and request handling. Centralized access to an application means that requests are easily tracked and logged.

Improves Manageability: Front Controller centralizes control, providing a choke point for illicit access attempts into the Web application. In addition, auditing a single entrance into the application requires fewer resources than distributing security checks across all pages.

Improves Reusability: Front Controller promotes cleaner application partitioning and encourages reuse, as code that is common among components moves into a controller or is managed by a controller.

Separates the System Processing Logic: Front Servlet seperates the System Processing logic from view and provides the better manageability from the same.

Sunday, November 13, 2011

XML Parsing Example using DOM in Java


package com.test;


import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class XMLParsing {
  public static void main(String arg[]) throws Exception{

          String xmlRecords = "<data><employee><name>A</name>"
        + "<title>Manager</title></employee></data>";


    DocumentBuilder db = DocumentBuilderFactory.newInstance().
newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlRecords));


    Document doc = db.parse(is);
    NodeList nodes = doc.getElementsByTagName("employee");


    for (int i = 0; i < nodes.getLength(); i++) {
      Element element = (Element) nodes.item(i);


      NodeList name = element.getElementsByTagName("name");
      Element line = (Element) name.item(0);
      System.out.println("Name: " + getCharacterDataFromElement(line));


      NodeList title = element.getElementsByTagName("title");
      line = (Element) title.item(0);
      System.out.println("Title: " + getCharacterDataFromElement(line));
    }
  }
  public static String getCharacterDataFromElement(Element e) {
    Node child = e.getFirstChild();
    if (child instanceof CharacterData) {
      CharacterData cd = (CharacterData) child;
      return cd.getData();
    }
    return "";
  }
}




Related Links:
                   XML Parsing using SAX Parser in Java
           Read Properties File in java
                   J2EE Design Patterns

SAX Parser Example in JAVA


package com.test;
import java.io.StringReader;
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


public class ParseXMLUsingSAX {
public static String xmlString = "<?xml version='1.0'?><EMPLOYEE><USER_ID>admin</USER_ID><PASSWORD>admin123</PASSWORD></EMPLOYEE>";
public static void main(String argv[]) {
String fileName = "D:\\test.xml";
parseXml(fileName);
}
public static void parseXml(String fileName){
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlString));
DefaultHandler handler = new DefaultHandler() {
boolean userID = false;
boolean password = false;
public void startElement(String uri, String localName, 
String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("USER_ID")) {
userID = true;
}
if (qName.equalsIgnoreCase("PASSWORD")) {
password = true;
}
}
public void endElement(String uri, String localName,
String qName) throws SAXException {
}
public void characters(char ch[], int start, int length) throws SAXException {
if (userID) {
System.out.println("userID : " + new String(ch, start, length));
userID = false;
}
if (password) {
System.out.println("password : " + new String(ch, start, length));
password = false;
}
}
};
//saxParser.parse(fileName, handler);
saxParser.parse(is, handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Intercepting Filter – Core J2EE design patterns

What Intercepting Filter does?

The Intercepting Filter pattern wraps existing application resources with a filter that intercepts the reception of a request and the transmission of a response.

What is the need of Intercepting Filter?

Consider a scenario, I your web application you want to check session from the every users request and if it is valid then only you want to let the user access the page. You can achieve this by checking sessions on all the servlet pages (or JSP pages) which users queries or you can do this by using Filter. In a filter you can write the logic to not enter the user without a valid session.
ie: An intercepting filter can pre-process or redirect application requests, and can post-process or replace the content of application responses. Intercepting filters can also be stacked one on top of the other to add a chain of separate, declaratively-deployable services to existing Web resources with no changes to source code.

Example for Intercepting Filter:


import java.io.IOException;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class LogFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;

        //Get the IP address of client machine.
        String ipAddress = request.getRemoteAddr();

        //Log the IP address and current timestamp.
        System.out.println("IP "+ipAddress + ", Time "
                            + new Date().toString());

        chain.doFilter(req, res);
    }
    public void init(FilterConfig config) throws ServletException {

        //Get init parameter
        String testParam = config.getInitParameter("test-param");

        //Print the init parameter
        System.out.println("Test Param: " + testParam);
    }
    public void destroy() {
        //add code to release any resource
    }
}


Advantages:

Centralizes Control with Loosely Coupled Handlers: Filters provide a central place for handling processing across multiple requests, as does a controller. Filters are better suited to massaging requests and responses for ultimate handling by a target resource, such as a controller. Additionally, a controller often ties together the management of numerous unrelated common services, such as authentication, logging, encryption, and so forth, while filtering allows for much more loosely coupled handlers, which can be combined in various combinations.

Improves Re-usability: Filters promote cleaner application partitioning and encourages reuse. These pluggable interceptors are transparently added or removed from existing code, and due to their standard interface, they work in any combination and are reusable for varying presentations.

Declarative and Flexible Configuration: Numerous services are combined in varying permutations without a single recompile of the core code base.

Disadvantages:

Information Sharing is Inefficient: Sharing information between filters can be inefficient, since by definition each filter is loosely coupled. If large amounts of information must be shared between filters, then this approach may prove to be costly.