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.

Saturday, November 12, 2011

J2EE Design Patterns

Recent times I have tried to look into the J2EE design patterns, as I am gaining the experience in Java development it is necessary the I should have complete Idea on the J2EE design patterns. Here I am planning to share my understanding, key points that I believe most important for normal java developer.

Most of J2EE/JEE based applications has the Presentation layer (which is visible to the user), Business Layer (which has the business components implementation) and Integration Layer (which integrates with other systems or databases). So, the people have classified the J2EE design patterns in to three types as below:

Presentation tier Patterns:

Business Tier Patterns:
  • Business Delegate
  • Service Locator
  • Session Fa├žade
  • Value List Handler
  • Business Object
  • Composite Entity

Integration tier patterns:
  • Data Access Object
  • Service Activator
  • Web Service Broker
  • Domain Service


I have listed the most of the design patterns above which I feel more important. Most of the design patters depends on one or more, so implementation of a complete J2EE based and good architecture enterprise application requires all the design patters listed above.

Design pattern definition: A design pattern describes a proven solution, from experienced hands, for a recurring design problem. These solutions are very generic. They are described in well-defined Pattern Templates, with the most popular template defined by the Gang of four. For a recurring problem there would be a single solution in a single context ie. There would be none other than one solution for single problem in a single context.

Saturday, November 5, 2011

Sorting of int values in an array



package com.classes;
public class ManualSorting {
int[] arr = { 12, 1, 3, 22, 222, -9 };
public void ascendingOrder() {
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
int temp = 0;
if (arr[i] < arr[j]) {
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
System.out.print(arr[i] + " ,");
}
System.out.println();
}
public void descendingOrder() {
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
int temp = 0;
if (arr[i] > arr[j]) {
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
System.out.print(arr[i] + " ,");
}
System.out.println();
}
public static void main(String arr[]) {
ManualSorting ms = new ManualSorting();
ms.ascendingOrder();
ms.descendingOrder();
}
}