Wednesday, December 01, 2010

Add Java SOAP Handler to the Client Code

Step:
1. Implement SOAPHandler class
2. Implement authentication part to the SOAPHandler part
2. Add SOAP handler to the Service class.



import java.util.Collections;
import java.util.Set;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPHeader;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;


public class AuthenticationHandler implements SOAPHandler {

private static Logger log = Logger.getLogger(GCAuthenticationHandler.class.getName());

private String emailAddress;
private String password;


private String url = "http://www.localhost.net/webservice/";

private static final String CAuthenticationHeader= "CAuthenticationHeader";

public static enum AuthenticationHeader {EmailAddress, Password}



public GCAuthenticationHandler(String emailAddress, String password){
this.emailAddress = emailAddress;
this.password = password;

}


public GCAuthenticationHandler(String emailAddress, String password, String url){
this(emailAddress, password);
this.url = url;
}

@PostConstruct
public void init() {
}

@PreDestroy
public void destroy() {
}

public boolean handleMessage(SOAPMessageContext smc) {

boolean direction = ((Boolean) smc.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY)).booleanValue();

if (direction) {

try {

// get SOAP envelope from SOAP message
SOAPEnvelope envelope = smc.getMessage().getSOAPPart().getEnvelope();

// create instance of SOAP factory
SOAPFactory soapFactory = SOAPFactory.newInstance();

// create SOAP elements specifying prefix and URI
SOAPElement headerElm = soapFactory.createElement(CAuthenticationHeader, "", url);

SOAPElement idElm = soapFactory.createElement(AuthenticationHeader.Password.name(),"", url);
idElm.addTextNode(password);

SOAPElement passwdElm = soapFactory.createElement(AuthenticationHeader.EmailAddress.name(),"", url);
passwdElm.addTextNode(emailAddress);


// add child elements to the root element
headerElm.addChildElement(idElm);
headerElm.addChildElement(passwdElm);


// create SOAPHeader instance for SOAP envelope
SOAPHeader sh = envelope.addHeader();

// add SOAP element for header to SOAP header object
sh.addChildElement(headerElm);
} catch (Exception ex) {
ex.printStackTrace();
}


}

return true;

}

public Set getHeaders() {
return Collections.EMPTY_SET;
}

public boolean handleFault(SOAPMessageContext messageContext) {
return true;
}

public void close(MessageContext context) {
}
}


Wednesday, July 16, 2008

Find Largest Sub Tree


import java.util.ArrayList;

import java.util.HashMap;
import java.util.Map;

/**
*
* This class find out the largest subtree from the Tree
* nodeMap Store the node and it weight value
* rootNode Root node
*
* Class is not thread safe
*
* @author mamun
* @Date 15-07-2008
* @version 1.0.0
*
*/
public class SubTreeLarestFound {

private Map nodeMap = new HashMap();
public Node rootNode;

public void initData() {
Node t1 = new Node(1);
Node t2 = new Node(2);
Node t3 = new Node(3);
Node t4 = new Node(4);
Node t5 = new Node(5);
Node t6 = new Node(6);
Node t7 = new Node(7);

Node t8 = new Node(18);
Node t9 = new Node(9);

t1.addNode(t2);
t1.addNode(t3);
t1.addNode(t8);

t2.addNode(t5);
t2.addNode(t7);

t3.addNode(t4);
t3.addNode(t6);
t6.addNode(t8);
t6.addNode(t9);

rootNode = t2;
Node largestNode = findLargestSubtree(rootNode);
System.out.println("The node value is "+largestNode.value);

}




/**
* Get the tree and Return the Largest SubTree Node
* It is recursive function if node has child node then it call itself and start
* return after reach to the child node
* nodeMap store the node value and its weight
* largestNode Largest sub tree node
*
*
*
* @param currentNode -Root Node of the Tree
* @return Node - Larest SubTree Node
*/
public Node findLargestSubtree(Node currentNode) {

nodeMap.put(currentNode, currentNode.value); //put weight for each node

if (currentNode.getChilden().length > 0) { //Yes if Node has child node

int totalweight = 0; // Total weight for each SubTree
for (Node childNode : currentNode.getChilden()) {
Node node = findLargestSubtree(childNode); // Find the child node weight(recursive call)
totalweight += nodeMap.get(node); // Add Child node weight to the total weight
}
totalweight += nodeMap.get(currentNode);
nodeMap.put(currentNode, totalweight); //Update Total wight for SubTree

if (rootNode == currentNode) { // True for root Node find the largest weight
Node largestNode = null;
for (Node node : nodeMap.keySet()) {
if (node != rootNode) {
if (largestNode == null) {
largestNode = node;
}
if (nodeMap.get(node) > nodeMap.get(largestNode)) {
largestNode = node; //set largest subtree
}
}
}
return largestNode; //return largest subtree node
}
return currentNode;
} else {
return currentNode;
}
}

public static void main(String[] argv) {
SubTreeLarestFound test = new SubTreeLarestFound();
test.initData();
}

/**
* Node class of the Tree
* It's store its child node and wieght value
* Each Node must have a value but may not child node
* value store the node value
* Childen store the child node
* ZERO_NODE represent the zero node of the Node
* @author mamun
*
*/
public static class Node {

private ArrayList Childen; //child node
private int value; //node weight(value)
private Node[] ZERO_NODE = new Node[0];
public Node(int value) {
this.value = value;
this.Childen = new ArrayList();
}

/**
*
* @return the node value
*/
public int getValue() {
return value;
}

/**
*
* @param value Node Value
*/
public void setValue(int value) {
this.value = value;
}

/**
*
* @param node Add node to the child node list
*/
public void addNode(Node node) {
this.Childen.add(node);
}

/**
*
* @return the Node Array
*/
public Node[] getChilden() {
return Childen.toArray(ZERO_NODE);
}
}
}

Monday, June 02, 2008

Java Web Deployment Description
Web.xml is the file that is standard web deployment description for any j2ee web application server. The web.xml file define multiple component that the application can customize such as filtering, listeners, servlets, init-paramenters and local tag lib.

Filter: Filter are designed to warp calls to the web application, so here can intercept and perform variety global operation like security.
Listener: Listen either after or before an event. For JSF application faces-config.xml listen here
Servlet: This is the root of the web application.
Servlet Mapping: Give the reference to the servlet with a name.
Initial Parameter: These parameter are picked up by the servlet for configuration.
Tag Lib: This are used when tag lib stored in the locally and use in the JSP page.

Sample of Web.xml


Listener - org.apache.myfaces.webapp.StartupServletContextListener
context-param -javax.faces.STATE_SAVING_METHOD
Faces Servlet:-javax.faces.webapp.FacesServlet
Faces Servlet Mapping:- *.faces

Friday, February 01, 2008

Restful Web Service

Web service is designed to communicate with machine to machine. Web service is defined by W3C "as software system designed to support inter operable machine to machine interaction". There are different architecture of the web service like REST full resource oriented, RCP-style and REST-RCP hybrid.

Roy Fielding articulated REST as an underlying concept for today's Web architecture. The most important concept of the REST is it is architecture style not the protocol i,e There is no REST specification, no tools from SUN, IBM or Microsoft, it uses the exiting technology for creating web service. It is not standard it use the standard.

Who are using RESTFul web service

  • Services that expose the Atom Publishing Protocol (http://www.ietf.org/html.charters/atompub-charter.html) and its variants such as GData (http://code.google.com/apis/gdata/)
  • Amazon’s Simple Storage Service (S3) (http://aws.amazon.com/s3
  • Most of Yahoo!’s web services (http://developer.yahoo.com/)

All application are based on the representation state transfer. For amazon, after get the book id any one can get the book detail through the id.

What is the representation state transfer:
The web is the composed of resource. For example, University defined the student resource with their id(99301). Student can access the resource through the url

Year Dept Roll
99 3 01

http://www.university.edu/information/99301

The representation of the resource is returned through the url(99301.html). The client get new position of the state. By the new representation of the resource, client get another state. In this way, client change their state.

Creating RESTFul Web Service
For creating RESTFul web service need to identify all the resource that need to expose as the web service. Some example, student list, student detail. Use exiting http operation for accessing and creating the resource.

Http Operation
GET Accessing the resource
POST Create
PUT Update
DELETE Delete

Get the university student list:

http://www.university.edu/information/students
It will return all the student id list of the university.

The client receive the following document



xmlns:xlink="http://www.w3.org/1999/xlink">






Get details list:
http://www.university.edu/information/students/99301

It will return the detail list of the student.

In RCP based web service need to create client stubs in the client side and different method access the resource to the server but in the REST based, methods are the fixed(get, post, put, delete), no need to generate client stub to access the web service in the client side. Using browser
method get access all resource.

Friday, January 18, 2008

Singleton Pattern in Java Script using Lazy Instantiation

Singleton pattern provide a way group of code and logical unit can access through a single instance. In JavaScript it can be used for namespacing, which reduce number of global variable in your class. It can also use encapsulate browser different through a technique known as branching.

Singleton patten example through java script



var StringUtil = window.StringUtil || {}

StringUtil.DataParser = (function(){

var uniqueInstance;

function constructor(){

var whiteSpaceReges = /\s+/;

function stropWhiteSpace(str){
return str.replace(whiteSpaceReges,'');
}

function stringSplit(str, delimiter){
return str.split(delimiter);
}

this.stringToArray = function(str, delimiter, stripWS){
if(stripWS){
str = stropWhiteSpace(str);
}
var outputArray = stringSplit(str, delimiter);
return outputArray;
}
}

return {
getInstance: function(){
if(!uniqueInstance){
uniqueInstance = new constructor();
}
return uniqueInstance;
}
}
})();




Run the code:
var testStr = 'Hello , World, Test ';
var output = StringUtil.DataParser.getInstance().stringToArray(testStr,',',false);
output.length -> 3
Implement Interface in JavaScript

An interface provide a way what the behavior of the object should have mean what the method of the object. But it does not say how those method and behavior should be implemented. This allow group of object have same behavior.

Advantage of using interface in Java Script
Establishment interfaces are self documenting and promote re usability. An interface tell programmer what method must be implement which make user to use and easier to find out error and unit test.
Disadvantage of using interfaced
Java Script is extremely expressive language. Using interface its behave some thing like strict typing. There is no built in support or keyword like interface so it is not easy to implements interface in Java Script. Every thing need to implements manually. Using interface implementation in Java Script will create a performance hot, due in the part of having another mehtod invocation.

In complex map application there are many implementation and every one ensure all have implement all method that need the application.

function displayRoute(mapInstance) {
Interface.ensureImplements(mapInstace, DynamicMap);
mapInstance.centerOnPoint(12, 34);
mapInstance.zoom(5);
mapInstance.draw();
...
}

If any one want to use the display Route function then he/her must implement all the method like centerOnPoint, zoom and draw


Step by Step Interface implementation:

Simple Student class,
In Java:


interface IStudent{
void setName(String name)
String getName();
}

public class Student implements IStudent{
private String name
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}

}


In Java Script

1. Create Interface function that store the name of the implementation and name of the method.




var Interface = function(name, methods) {
if(arguments.length != 2) {
// alert("Expected two argument..");
throw new Error("Interface constructor called with " + arguments.length
+ "arguments, but expected exactly 2.");
}

this.name = name;
this.methods = []; //store the mehod name

for(var i = 0, len = methods.length; i <>


2. Create the static method of the Interface ensure the implementation.


Interface.ensureImplements = function(object) {

if(arguments.length < i =" 1," len =" arguments.length;" interface_ =" arguments[i];" j =" 0," methodslen =" interface_.methods.length;" method =" interface_.methods[j];">


3. Create Interface variable

var IStudent = new Interface('Student1',['setName','getName']);

var Student = function(){ };

Student.prototype.setName = function(name){
this.name = name;
}

Student.prototype.getName = function(){
return this.name;
}

function studentOperation(student){
Interface.ensureImplements(student, IStudent);
student.setName('Test Student1');
alert(student.getName());
}

5. Use the interface



function studentOperation(student){
Interface.ensureImplements(student, IStudent); // Must check the
student.setName('Test Student1');
alert(student.getName());
}

Thursday, January 17, 2008

Mixin in Java Script

There are many way to reuse code without strict inheritance, Mixin is the one of way. In practice it goes something like that any one create class that contain general purpose methods then use it to augment other classes. Those class with the general purpose method are called Mixin. Mixin implementation in JavaScript

1. First create a Person class

function Person(name){
this.name = name;
}
Person.prototype.getName = function(){
return this.name
}

2. Then create another class

function Author(name, books){
Person.call(this, name); // super class constructor call here
this.books = books
}
Author.prototype.getBooks = function(){
return this.books
}

3. Set the inheritance property

Author.prototype = new Person(); // the

4. Create the instance of the Author

var author = new Author('Ross Harmes', ['JavaScript Design Patterns']);
author.getName() ///It will print the author name of Ross Harmess

5. Now create Mixin class

function Mixin(){
};

Mixin.prototype.serialize = function() { //common method
return "Hello from Mixin"
}


//set the mixin proprty
function augment(receivingClass, givingClass){

if(arguments[2]){
for(var i = 0, len = arguments.length; i < len; i++){
receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
}
}else{
for(methodName in givingClass.prototype){
if(!receivingClass.prototype[methodName]){
receivingClass.prototype[methodName] = givingClass.prototype[methodName];
}
}
}
}

6. Call Mixin proprty

augment(Author, Mixin)
var author = new Author('testName',[''testBookName]);
var serializeStr = author.serialize(); //Result: 'Hello from mixin'