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.

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

Saturday, October 22, 2011

Read Properties file in Java



package com.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
public class ReadPropetiesFile {
public static void main(String a[]){
String fileName = "test.properties";
ReadPropetiesFile readProp = new ReadPropetiesFile();
readProp.readProperties(fileName);
}
public void readProperties(String fileName){
try {
ResourceBundle labels = ResourceBundle.getBundle(fileName, Locale.ENGLISH);
Enumeration bundleKeys = labels.getKeys();
while (bundleKeys.hasMoreElements()) {
   String key = (String)bundleKeys.nextElement();
   String value = labels.getString(key);
   System.out.println("key = " + key + ", " +   "value = " + value);
}
}catch (Exception e) {
e.printStackTrace();
}
}
}

Sunday, July 17, 2011

How to fix browser compatibility issues?

A normal developer never cares about the executing the application in different browsers while developing the application and he might doesn’t know that he will get lot of issues once the development is completed. This causes a big headache to him after completion of the application as he gets more number of cross browser compatibility issues and he can’t fix those instantly. 
Fixing the cross browser compatibility issues after completion of the project is night mare for the developer. He has to start fixing the issues from the starting stage of the application development.

Below is the small discussion to fix the browser compatibility issues for different browsers like Chrome, Internet Explorer and Mozilla Firefox.

Mozilla Firefox: 
The excellent feature that Firefox has is the add-ons. There are lot of add-ons you can add to Firefox in which Fire-Bug is the best add-on to fix the issues in applications while running in  the Firefox browser. When you install the fire bug add-on, one bug icon displayed on the right-bottom corner of the browser.
Once you open your application in firefox and click on the bug icon, you will see a window which contains html source code as shown in the below screenshot. The developer has to analyze the code which display on the firebug window and has to fix the issues.


The error console (Ctrl+sift+J gives the error console) of the firefox browser contains the java script errors in the site. Developer has to fix those errors by analyzing and debugging the JavaScript code.
Developer can fix the css related issues by modifying the css classes in the fire bug window.
You can view the fire bug window by just pressing the button F12.

You can read more about the Fire bug on http://getfirebug.com/whatisfirebug
 

Internet Explorer:
Microsoft is providing the developer tool along with the Internet explorer to analyze the issues in the IE. Once the proper analysis is done by the developer and he can fix the issues by updating the changes in javascript code or css classes.
Below screen shot shows the Internet Explorer developer tool. You can open this by going to Tools --> Developer Tools or by simple pressing the key F12.

You can read more on Internet Explorer developer tools on http://petelepage.com/blog/2010/06/internet-explorer-developer-tools/


Google Chrome:
By clicking on F12 button, you can open the Developer tool in the Chrome browser. Below screen shot shows the code analyzer of the Chrome browser.

You can read more on Chrome Developer tools on http://code.google.com/chrome/devtools/docs/overview.html 


I thought most of the cross browser issues comes with the javascript errors or javascript un supported methods in the browsers. If the developer cares about the javascript predefined functions while development, he can remove more number of cross browser issues.

Sunday, June 26, 2011

Make the life more colorful....

Colors are more important part of life. There are lot of colors with the combination of three major colors. Every one the world likes colors in their own way and for me, White and skyblue are favorite. Sometimes I like black too, most of my dresses are black, my shoes are black and my mobile is also black.

Here I am going to tell about the White color...

White is a symbol for peace and if you look into white for some time, your mindset will become more tension free. I think most of we choose White color for walls on that psychological reason.




So, bring more white color into your life from the black.


Below is the small collection on colorful life from the web...

Saturday, May 21, 2011

The Servlet init Vs Constructor

Generally Servlets don’t have the Constructor, because a servlet is just like an applet in the respect that it has an init() method that acts as a constructor, an initialization code you need to run should be place in the init(), since it get called when the servlet is first loaded.

You cann’t use a Constructor instead of init() method to initialize a servlet.The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructor a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext. 

Even while you trying to override the init() method you should pass the argument a ServletContext object because the container passes the ServletConfig object to the servlet only when it calls the init method. So ServletConfig will not be accessible in the constructor.

Servlet Life Cycle

A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol.

The methods which are used to initialize a servlet, to service requests, and to remove a servlet from the server are called servlet life cycle methods. These are three methods namely init(), service(), destroy().

Init(): The servlet container calls the init method exactly once after instantiating the servlet. The init method must complete successfully before the servlet can receive any requests
It Contains all information code for servlet and is invoked when the servlet is first loaded.
You can override this method to write initialization code that needs to run only once, such as loading a driver, initializing values and soon, another case you can leave normally blank.

public void init(ServletConfig config)throws ServletException

Service() : is called by the Servlet container after the init method to allow the servlet to respond to a request. Service method receives the request from the client and identifies the type of request and delegates them to doGet() or doPost() for processing.

public void service(ServletRequest request,ServletResponce response) throws ServletException,  IOException

Destroy() : The Servlet Container calls the destroy( ) before removing a Servlet Instance from Sevice. Executes only once when the Servlet is removed from Server.

public void destroy() 


Click here to know about Servlets

Java Servlets

Servlet is a Java class used to extend the capabilities of servers that host applications accessed via a request-response programming model. Although servlets can respond to any type of request(like HTTP, FTP), they are commonly used to extend the applications hosted by Web servers.


Servlets runs at Server side typically Web Server or Application server, and respond to request by giving the response to user after processing the request. 


A servlet that implements SingleThreadModel means that for every request, a single servlet instance is created. This implementation helps in implementing the business applications like bank transactions. 


A multi-threaded servlet means that one servlet is capable of handling many requests which is the way most servlets should be implemented. This allows servlets to support systems such as on-line conferencing.


A servlet can handle multiple requests concurrently, and can synchronize requests. Servlets can forward requests to other servers and servlets.


As Servlet are written in java, they can make use of extensive power of the JAVA API,such as networking and URL access, multithreading, databaseconnectivity, RMI object serialization.

A Servlet implementation can be done in three ways:

  1. By implementing the Sevlet interface into your class. The class which implementing the Servlet interface, should implement all the servlet life cycle methods defined in the Servlet interface.
  2. By writing a subclass to GenricServlet present in the javax.servlet package. The subclass must override the abstract service method present in the Generic servlet class.
  3. By writing a subclass to HttpServlet present in javax.servlet.http package. The subclass of HttpServlet must override any of the methods in doGet(), doPost(), doDelete(), doPut(), init(), destroy(), getServletInfo().


In general most of the cases Servlet implementation can done by sub classing to GenericServlet or HttpServlet.
Below are the differences between HttpServlet and GenericServlet:
  1. HttpServlet is the subclass of GenericServlet.
  2. Generic Servlet defines a generic, protocol-independent servlet. HttpServlet provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site.
  3. A sub class which extends GenericServlet must implement the abstract service() method. A subclass of HttpServlet must override at least one method, usually one of these: doGet(), doPost(), doDelete(), doPut(), init(), destroy(), getServletInfo().

Click here to know Servlet Life cycles

Abstract class in Java

Abstract class is class which has more than one abstract method which doesn’t have method body but at least one of its methods need to be implemented  in derived Class.  
Abstract classes can be used to implement the inheritance relationship between the classes that belongs same hierarchy.
  1. Classes and methods can be declared as abstract.
  2. Abstract class can extend only one Class.
  3. If a Class is declared as abstract , no instance of that class can be created.
  4. If a method is declared as abstract, the sub class gives the implementation of that class.
  5. Even if a single method is declared as abstract in a Class ,  the class itself  can be declared as abstract.
  6. Abstract class have at least one abstract  method and others may be concrete.
  7. In abstract Class the keyword abstract must be used for method.
  8. Abstract classes have sub classes.
  9. Combination of modifiers Final and Abstract is illegal in java.
The general form of abstract class is :     
    abstract type name (parameter list);

The Number class in the java.lang package represents the abstract concept of numbers. It makes sense to model numbers in a program, but it doesn't make sense to create a generic number object.

Sample Abstract Classes: HttpServlet, GenericServlet 

You can more avout Interface here 
Click here for Difference between Abstract class and Iterface