Sunday, November 13, 2011

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.

Monday, November 7, 2011

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, September 25, 2011

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