Sunday, December 30, 2012

Factory Method Design Pattern or Virtual Constructor

Factory method design pattern is one of the extensively used design patter in software development using java. Concept of factory method design pattern is blend from factory which deals with the problem of creating products (in case of programming object).This is one of the basic creational design pattern.

Intent of factory method :

Define an interface for creating an object, but let subclasses decide which class
to instantiate. Factory Method lets a class defer instantiation to subclasses.

Assume an online banking system using two different sms gateway to deliver mobile banking notification to it's valued customers.System need to resolve which gateway will use by cell number assume hear gateway type. Based on category or need system need to create or return object/instance of a gateway. Hear is the practical example :
Gateway type enumeration :
package com.thinktank.rnd.se.pattern.factorymethod;


public enum GatewayType {
    ONE(1), TWO(2);

    private int value;

    private GatewayType(int value) {
        this.value = value;
    }

};
Gateway interface :
package com.thinktank.rnd.se.pattern.factorymethod;

public interface GateWay {
    public int connectToGateWay();
}

Implementation of gateway interface :
package com.thinktank.rnd.se.pattern.factorymethod;

public class SmsGatewayOne implements GateWay {
    public int connectToGateWay() {

        System.out.println("Connection Established With Gateway One");
        return 1;
    }
}

Another implementation of gateway interface :
package com.thinktank.rnd.se.pattern.factorymethod;


public class SmsGatewayTwo implements GateWay {
    public int connectToGateWay() {
        System.out.println("Connection Established to Gateway Two");
        return 1;
    }
}

Gateway factory class :
package com.thinktank.rnd.se.pattern.factorymethod;

public class GatewayFactory {

    public GateWay getGateway(GatewayType gatewayType) {

        switch (gatewayType) {
            case ONE:
                return new SmsGatewayOne();
            case TWO:
                return new SmsGatewayTwo();
        }
        return null;
    }
}

Main class for our factory method demo :
package com.thinktank.rnd.se.pattern.factorymethod;

public class DemoFactoryMethod {
    public static void main(String args[]) {

        GatewayFactory gatewayFactory = new GatewayFactory();
        GateWay gateWay = gatewayFactory.getGateway(GatewayType.TWO);
        gateWay.connectToGateWay();
    }
}


Use the Factory Method pattern when
·  a class can't anticipate the class of objects it must create.
·  a class wants its subclasses to specify the objects it creates.
·  classes delegate responsibility to one of several helper subclasses, and
you want to localize the knowledge of which helper subclass is the delegate.





Reference :
Design-patterns-elements-reusable-object-oriented
http://en.wikipedia.org/wiki/Design_Patterns
http://java.dzone.com/articles/design-patterns-factory
http://javapapers.com/design-patterns/factory-method-pattern/
http://en.wikipedia.org/wiki/Factory_method_pattern

Friday, December 28, 2012

Configure Tomcat for Remote Debug Your Web Application With Eclipse

Debugging is a vital part of developing any software system. Every developer relay on debug to find bugs and solve those quickly.In case of large code base it is too important.

To do remote debugging  with from eclipse we need to follow steps described bellow .

Before remote debug tomcat from eclipse you need to make sure :
  • Make sure that Tomcat is started in remote debugging mode
  • Make sure that you have the sources for the code that you are trying to debug in your IDE. For the libraries and for Tomcat itself you can "attach" the sources to the jar files: open a class file and then click "Attach Source..." button.
  • If you have a servlet or something, set a breakpoint where it is sure to hit on the next request.
  • Go to "Run->Debug Configurations...". Click on "Remote Java Applications", then click "New". Type in the title. Note that port 8000 from the Tomcat instructions. Save and run.
  • Eclipse will connect to the JVM that Tomcat is running under. Wow, that was easy!

Assume you are not starting tomcat from ide rathe using startup.sh/startup.bat file under /tomcat/bin.

Just add two lines in startup.bat at the end of file but before : 
call "%EXECUTABLE%" start %CMD_LINE_ARGS% 

set JPDA_ADDRESS=8000
set JPDA_TRANSPORT=dt_socket
And change :
call "%EXECUTABLE%" start %CMD_LINE_ARGS%
to 
call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS% startup.bat
Now save the file as startup_debug.bat You are ready to start your tomcat in debug mode .Start your tomcat with newly saved *.bat file startup_debug.bat. This will run the tomcat in debug mode.

Setup debug configuration in eclipse ide :
Go to debug configuration this will appear like bellow and replace project name with your one.


You are ready to start debugging . Now hit URL in browser set break point and have fun with debugging .














If you are interested about JPDA then take a look : http://docs.oracle.com/javase/1.5.0/docs/guide/jpda/



Wednesday, December 12, 2012

REST Service Client Tool : Beginner's Way

REST means Representational state transfer one of the mechanism of writing web service . After writing web service we need to write a client for it for testing purpose .But by using simple tool we can save our time of writing a client to test our server side service even it is 10 min. There is a chrome browser named Simple REST Client which we can use to serve our purpose.
We can download it from :Chrome Extension (Simple REST Client). We will find an icon in our chrome as indicated in picture after installing it in our chrome browser.



If we click the icon previously mentioned we will get a UI (user interface) like :


Instruction to use it :
URL : put your service url hear , example : https://www.example.com/restService/payment
Method : depends on your endpoint . in case of us POST
Header : Content-Type: text/html;charset=utf-8 or Content-Type: text/xml;charset=utf-8 this define the request message type expected by service end.In case of us (Content-Type: text/html;charset=utf-8).
Data : If you put service url in URL then this Data section will appear.In this section we will put actual client request message such as :


  CC
  John
  Doe
  1234 Street
  WA
  123
  US
  v
  4100111111111111
  0115
  123
  usd
 
     
  123
  Fall 2013
  123
  BBA
 
 
  example description
           12/12/2012
 
 
 
      
  TYPE
  tuition
  2
  2
  1

 
 
  TYPE
  Late Fee
  1
  2
  1
 


Previous request message (xml) taken from a real world scenario so i changed the real information to dummy information.

Now , we just need to hit send button , it will send the request to service end and show us response as desired by client. Response example : :

1
1
This transaction has been approved.
9DJEXW
Y
2180716417
4.00
CC
billing first name
billing last name
dhaka dhaka 1229 bangladesh 2 XXXX1111 Visa

This extension will work as a REST client . That's all. Apart from it we can use SOAP UI but this is much more easier for beginner and later on SOPA UI can be used . Wish to write on SOAP UI how to later.

Friday, August 24, 2012

Basic Control Flow in Python

def conditionalStatementTest():
    print("if else statement test:")
    x = int(input("Enter an integer :"))
    if(x < 10) :
        print("x is less then 10")

    elif(x > 10) :
        print("x is grater then 10")

    elif(x == 10) :
        print("x = 10")

def forLoopTest():
    print("Test for loop with range() function")
    for index in range(5):
        print(index)


if  __name__=='__main__':
    conditionalStatementTest()
    forLoopTest()


Python Learning Resource Link

Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.
Note for c/c++ Programmer :
It is a two hour job for a programmer who is already experienced with C/C++, to start with Python.
Important Note :About Version :
Before using any version of Python be sure you read the change between previous release and official release note.
Creator of Python :
Guido van Rossum
Popular Python Framework : DJANGO
Why Python
------------------
----under drafting--
Google's Python Class
From Wikipedia :
Good Blog On Python
Popular Opensource Project Using Python
Software Industry And Python Expart :
------------every skill has it's own gravity------------

Hello World Python Script

def addition():
    return(2+2)

def sub():
    return(2-2)

def multiplication():
    return(9999999999999999999999*9999999999999999999)

def piTest():
    return(22/7)


if  __name__=='__main__':
    print("Addition  :", addition())
    print("substraction :", sub())
    print("Multiplication :", multiplication())
    print("PI :", piTest())

Output :

Addition : 4
substraction : 0
Multiplication : 99999999999999999989990000000000000000001
PI : 3.142857142857143


Convert text to ASCII and ASCII to text - Python code

def asciiTest():
 
k = ord('B')

c = chr(66)

print(k)

print(c)

if __name__ == '__main__':
    asciiTest()


Thursday, July 26, 2012

Unknown initial character set index ’192′ received from server

Detail exception is :
java.sql.SQLException: Unknown initial character set index '192' received from server.
Initial client character set can be forced via the 'characterEncoding' property.



Solution :
find my.ini file of mysql 
And comment two lines bellow :

#collation_server=utf8_unicode_ci
#character_set_server=utf8


So far it works for me . 
But this is a known bug and fixed earlier hear .


http://bugs.mysql.com/bug.php?id=22456






Monday, July 23, 2012

Install Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 6

  • Step one :
    Download required files from hear. This two file are not shifted with standalone jre download. Hear you will get two file namely :
    • local_policy.jar
    • US_export_policy.jar
  • Step Tow :
    Find jre installation directory in your windows/linux machine .
    And locate the path
    C:\Program Files\Java\jre6\lib\security  
    //[in case of my windows 7 machine]

  • Step Three :
    Just past downloaded two files in located directory and overwrite previous two.

This will facilitate AES key generation up to 256 bits.

Example :

keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256);

For enthusiastic readers further reference on Java Security

Tuesday, July 03, 2012

WSDL , WADL , XRD

WSDL : Web Service Description Language
WADL : Web Application Description Language
XRD : Extensible Resource Descriptor


Sunday, July 01, 2012

Introduction To Session Bean


Web Service Security Concern

Writing on going , sorry for being waiting you .

http://www.w3.org/TR/ws-arch/#security

Wings of Fire


Wings of Fire: An Autobiography of APJ Abdul Kalam is an autobiography of A P J Abdul Kalam, former President of India. It was written by Dr. Kalam and Arun Tiwari. Wikipedia
A books of turning point of former president of India. And a man of honor. I read the almost four yer's ago . So hear is my soul experience about the book,

                                               


Friday, June 29, 2012

Introduction To RDF (Resource Description Framework)

Mr. Goni On RDF (Resource Description Framework)

  • RDF is a language for representing information about resources in the World Wide Web
  • RDF is a standard model for data interchange on web ,more elegantly and intelligently
  • The Resource Description Framework (RDF) is a family of World Wide Web Consortium (W3C) specifications
  • Originally Designed as a metadata data model
  • Prime intention of RDF is to represent meta data about the resource in the web
  • One of the major focus of RDF (Resource Description Framework) is the data represented using RDF will be used by different application rather then only representation purpose . This capability will leverage next generation developer to work with data more conveniently

        
                Tony Benn
                Wikipedia
                
                     
                          Tony Benn  
                     
                
        



Reference :


The processing instruction target matching "[xX][mM][lL]" is not allowed

This message is related to xml directly.This is actually related to xml parsing .Technically id  SAX Parse exception occur then we will see this message . This exception will occur if there is any black space of line in the very beginning of the xml message , means before the line bellow :

                   <?xml version = "1.0" encoding = "utf-8" ?>  

Simple problem , simple solution just remove the black line or space in start of xml message .

Things Fall Apart by Chinua Achebe

By Chinua Achebe - Anchor Books (1959) 

Rise and fall , ups and down even head and tail are some true factors of human race.Recently i read these 
specific book with great interest. I am an analytical reader .
The story of this books is round in a time when people of different villages (as described in the book) are 
fighting and keeping there hope alive round the year and even round there life time with spectacular 
custom and natural rituals in different occasion.

                                                    

Tuesday, June 26, 2012

EJB (Enterprise Java Beans) Introduction

Mr . Goni on EJB (Enterprise Java Beans)

  • Enterprise beans an JEE components that implements EJB
  • EJB run in EJB container
    • JEE server
    • EJB Container
    • Web container
    • Application client container
    • Applet container
  • EJB is a server side component
  • Written in the pure java programming language
  • Encapsulates the business logic of an application
  • Types of EJB(Enterprise Java Beans)
    • Session Bean
    • Message Driven
    • Note : Entity beans have been replaced by Java Persistence API entities.
  • When we need EJB
    • If we need to scale our application and handle growing number of user
    • To distribute application in different machines
    • If we need to be sure about data integrity
    • flexible access of shared objects
    • In case of thin client implementation we can use EJB
    • When portability issue arise we will choose EJB as our implementation technology without re thinking

Saturday, June 23, 2012

StAX API in JAVA to Work With XML Info-Set



Streaming API for XML (StAX) is an API to process XML documents. As official documents of StAX

The StAX project was spearheaded by BEA with support from Sun Microsystems, and the JSR 173 specification passed the Java Community Process final approval ballot in March, 2004 (http://jcp.org/en/jsr/detail?id=173). The primary goal of the StAX API is to give "parsing control to the programmer by exposing a simple iterator based API. This allows the programmer to ask for the next event (pull the event) and allows state to be stored in procedural fashion." StAX was created to address limitations in the two most prevalent parsing APIs, SAX and DOM.

--StAX is a pull API
--StAX has bi directional support means it can do both XML reading and writing .

Streaming Vs DOM


There are two models of programming to work with XML infosets : document streaming and document object model (DOM)
In DOM based processing , in memory objects are created to represent entire document as a trree while processing the xml document. Obviously there are memory and processing issues involved with these . If XML document is smaller then we can ignore these issue but if document getting larger then we need to re think about DOM based solution. Though DOM based API gives developer programmatic flexibility but gives some memory and processing overhead.
On the other hand streaming refer to a programming model where xml document are processd serially and in application run time and often from dynamic sources whose contents are not precisely known beforehand. Moreover, stream-based parsers can start generating output immediately, and infoset elements can be discarded and garbage collected immediately after they are used. While providing a smaller memory footprint, reduced processor requirements, and higher performance in certain situations, the primary trade-off with stream processing is that you can only see the infoset state at one location at a time in the document. You are essentially limited to the "cardboard tube" view of a document, the implication being that you need to know what processing you want to do before reading the XML document.
Streaming models for XML processing are particularly useful when your application has strict memory limitations, as with a cellphone running J2ME, or when your application needs to simultaneously process several requests, as with an application server. In fact, it can be argued that the majority of XML business logic can benefit from stream processing, and does not require the in-memory maintenance of entire DOM trees.

Pull Vs Push Style API


In case of pull type programming model application need explicit call to read data from xml info-set means pulling from xml infoset .

But, in case of push parsing model parser API push the data to application when encounter any element in xml infoset.

Pull Parsing Has Some Advantages Over Push Model :

---client has control on application thread
--lees code writing
--can handle multiple documents at ones in a single thread
--StAX parser has filtering capabilities to ignore unwanted elements in xml infoset
--support xml views of non xml data

Reference

http://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.6/tutorial/doc/SJSXP2.html



Sample StAX Code To Write XML Document

public void generateXML ()  {

  String generatedXMLAsString = "";

  try {
   XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
   ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
   XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(byteArrayOutputStream);


   xmlStreamWriter.writeStartDocument();
   xmlStreamWriter.writeCharacters("\n\n");

   xmlStreamWriter.writeStartElement("rootElement");
   xmlStreamWriter.writeNamespace("", "http://wwww.example.com/hello");
   xmlStreamWriter.writeCharacters("\n");

   xmlStreamWriter.writeStartElement("childElement");
   xmlStreamWriter.writeCharacters("hello");
   xmlStreamWriter.writeEndElement();
   xmlStreamWriter.writeCharacters("\n");

   xmlStreamWriter.writeEndElement();

   xmlStreamWriter.writeEndDocument();
   xmlStreamWriter.close();

   generatedXMLAsString = new String(byteArrayOutputStream.toString());

   System.out.println(generatedXMLAsString);

   byteArrayOutputStream.close();
  } catch (Exception e) {
   System.out.println(e.getMessage());
  }
 }

Generated XML


hello


Thursday, June 07, 2012

REST with Java (JAX-RS) using Jersey in five minutes


Simple Root Resource Class :
package com.hello.demo;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;


@Path("/hello")
public class Hello  {

 @POST
 @Path("/test")
 @Consumes(MediaType.TEXT_XML)
 @Produces(MediaType.TEXT_XML)
 public String consumeTest (String requestMessage) {
   return requestMessage;
    
 } 
}


Testing this service using Simple REST Client found as chrome extension :
That's it. Try and enjoy.

Wednesday, June 06, 2012

Generate JAVA File from XSD using XJC Tool (JAXB)

Hello world xsd file :






     

 
  
      

 
 

 
  
   
   
   
   
  

 
  
   
   
   
  



Then Initiate the command from command line : Generated class files are :
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 
// See http://java.sun.com/xml/jaxb 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2012.06.06 at 11:37:48 AM ALMT 
//


package com.helloworld;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;


/**
 * 

Java class for anonymous complex type. * *

The following schema fragment specifies the expected content contained within this class. * *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="hackername" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="hackercode" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="expcode" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 * 
* * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "hackername", "hackercode", "expcode" }) @XmlRootElement(name = "Hacker") public class Hacker { @XmlElement(required = true) protected String hackername; @XmlElement(required = true) protected String hackercode; @XmlElement(required = true) protected String expcode; /** * Gets the value of the hackername property. * * @return * possible object is * {@link String } * */ public String getHackername() { return hackername; } /** * Sets the value of the hackername property. * * @param value * allowed object is * {@link String } * */ public void setHackername(String value) { this.hackername = value; } /** * Gets the value of the hackercode property. * * @return * possible object is * {@link String } * */ public String getHackercode() { return hackercode; } /** * Sets the value of the hackercode property. * * @param value * allowed object is * {@link String } * */ public void setHackercode(String value) { this.hackercode = value; } /** * Gets the value of the expcode property. * * @return * possible object is * {@link String } * */ public String getExpcode() { return expcode; } /** * Sets the value of the expcode property. * * @param value * allowed object is * {@link String } * */ public void setExpcode(String value) { this.expcode = value; } }
And :
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 
// See http://java.sun.com/xml/jaxb 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2012.06.06 at 11:37:48 AM ALMT 
//


package com.helloworld;

import javax.xml.bind.annotation.XmlRegistry;


/**
 * This object contains factory methods for each 
 * Java content interface and Java element interface 
 * generated in the com.helloworld package. 
 * 

An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.helloworld * */ public ObjectFactory() { } /** * Create an instance of {@link Hacker } * */ public Hacker createHacker() { return new Hacker(); } }

And final one :
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 
// See http://java.sun.com/xml/jaxb 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2012.06.06 at 11:37:48 AM ALMT 
//

@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.helloworld.com", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.helloworld;




Sunday, June 03, 2012

Introduction to XML Path Language (XPATH)

XPath is a W3C recommendation.
XPath is a language to navigate through different parts of xml document,designed to be used bu both XSLT and XPointer.
Simple way to use XPath with java .

The XML file need to read : hello.xml



Asraful
24
Male



Rid
22
Male



Tina
19
Female


And , Hear is the java code to read the file named : hello.xml
package com.thinktank.rnd.se.pattern.xml;


import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

public class XMLReadWrite {
    public static void main(String args[]) throws Exception {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

        documentBuilderFactory.setNamespaceAware(true);

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        Document document = documentBuilder.parse("hello.xml");

        XPath xPath = XPathFactory.newInstance().newXPath();

        XPathExpression expr = xPath.compile("//person/*/text()");

        Object result = expr.evaluate(document, XPathConstants.NODESET);

        NodeList nodes = (NodeList) result;

        for (int i = 0; i < nodes.getLength(); i++) {
            System.out.println(nodes.item(i).getNodeValue());
        }

    }

}

Finally Output of the code :

Asraful
24
Male
Rid
22
Male
Tina
19
Female

Thursday, May 31, 2012

Create Simple SOAP Request Message Using SAAJ API


The SOAP with Attachments API for Java (SAAJ) enables developers to produce and consume messages conforming to the SOAP 1.1 and SOAP 1.2 specification and also and SOAP with Attachments note.

Hear is a simple example code to produce SOAP request message to get user detail using SAAJ API.

public void createSOAPRequestMessage () {

    MessageFactory messageFactory = MessageFactory

               .newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);

  SOAPMessage soapMessage = messageFactory.createMessage();

        SOAPPart soapPart = soapMessage.getSOAPPart();

        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

        SOAPBody soapBody = soapEnvelope.getBody();

        soapEnvelope.addNamespaceDeclaration("xsi","http://www.w3.org/2001/XMLSchema-instance");

        soapEnvelope.addNamespaceDeclaration("xsd","http://www.w3.org/2001/XMLSchema");

        soapMessage.getSOAPHeader().detachNode();

        QName qNameRootTag = new QName("http://www.example.com/","GetUserDetail");

        SOAPBodyElement soapRootBodyElement = soapBody.addBodyElement(qNameRootTag);

        QName username = new QName("username");

        SOAPElement inputTagOne = soapRootBodyElement.addChildElement(username);

        inputTagOne.addTextNode("Mr Goni");

        QName userid = new QName("userid");

        SOAPElement inputTagTwo = soapRootBodyElement.addChildElement(userid);

        inputTagTwo.addTextNode("W2012X");

        soapMessage.saveChanges(); 

  soapMessage.writeTo(System.out);

        System.out.println();

}

This code will produce output like :





 

 Mr Goni
 W2012X

 






So , grub the code test and use or modify as your need .

Monday, May 28, 2012

Read File From /WEB-INF/ at runtime

Suppose one want to read a  example.properties  file located in /WEB-INF/props/example.properties in run time.

A simple way :

Properties properties = new java.util.Properties();
        InputStream inputStream =   
            getServletContext().getResourceAsStream("/WEBINF/props/example.properties");
properties.load(inputStream);

Now , we are ready to get value from example.properties file .

String value = properties.getProperty("propertyName");

Sample Properties File :

example.properties 

propertyName  = 123
-------------------------------------------------------------------

getResourceAsStream(String str) explained at java doc  :


public InputStream getResourceAsStream(String name)
Returns an input stream for reading the specified resource.The search order is described in the documentation for getResource(String).
Parameters:
name - The resource name
Returns:
An input stream for reading the resource, or null if the resource could not be found
Since:
1.1

Thursday, May 24, 2012

Introduction to SOAP Protocol


Official Definition of SOAP

W3 described SOAP as “SOAP Version 1.2 is a lightweight protocol intended for exchanging structured information in a decentralized, distributed environment ”
We can define it as a simple messaging framework .It build on XML technologies.
Two version of SOAP protocol is available now , 1.1 and 1.2 . Her I will focus on version 1.2.

Major Use Case : Exchanging information between systems.

Power of SOAP 1.2 :
This framework designed such a way that it is “independent of any particular programming model and other implementation specific semantics ”.

SOAP makes communication with web services smooth and more solid.
Example : SOAP message containing a SOAP header block and a SOAP body
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
 <env:Header>
  <n:alertcontrol xmlns:n="http://example.org/alertcontrol">
   <n:priority>1</n:priority>
   <n:expires>2050-06-22T14:00:00-05:00</n:expires>
  </n:alertcontrol>
 </env:Header>
 <env:Body>
  <m:alert xmlns:m="http://example.org/alert">
   <m:msg>Hello World SOAP Message</m:msg>
  </m:alert>
 </env:Body>
</env:Envelope>

SOAP Terminology :
Conceptual :
SOAP :
Simple object protocol.

SOAP node
 A SOAP node is responsible for enforcing the rules that govern the exchange of SOAP messages
SOAP role :
A SOAP receiver's expected function in processing a message. A SOAP receiver can act in multiple roles.
SOAP binding
Set of rules to exchange SOAP message in top of another protocol or a part of another protocol. Usually SOAP message exchanged with in an HTTP entity-body or over Tcp stream.
SOAP feature
"reliability", "security", "correlation", "routing", and "Message Exchange Patterns" (MEPs).
SOAP module
A SOAP Module is a specification that contains the combined syntax and semantics of SOAP header blocks.
SOAP message exchange pattern (MEP)
A template for the exchange of SOAP messages between SOAP nodes.
SOAP application
Can be a web service provider or a web service consumer system.

Data Encapsulation :

SOAP message
The basic unit of communication between SOAP nodes.
SOAP envelope
The outermost element information item of a SOAP message.
SOAP header
A collection of zero or more SOAP header blocks each of which might be targeted at any SOAP receiver within the SOAP message path.
SOAP header block
An element information item used to delimit data that logically constitutes a single computational unit within the SOAP header. The type of a SOAP header block is identified by the XML expanded name of the header block element information item.
SOAP body
A collection of zero or more element information items targeted at an ultimate SOAP receiver
SOAP fault
A SOAP element information item which contains fault information generated by a SOAP node.

Message Sender and Receiver Concepts

SOAP sender
A SOAP node that transmits a SOAP message.
SOAP receiver
A SOAP node that accepts a SOAP message.
SOAP message path
The set of SOAP nodes through which a single SOAP message passes. This includes the initial SOAP sender, zero or more SOAP intermediaries, and an ultimate SOAP receiver.
Initial SOAP sender
The SOAP sender that originates a SOAP message at the starting point of a SOAP message path. It can be a client application.
SOAP intermediary
A SOAP intermediary is both a SOAP receiver and a SOAP sender and is targetable from within a SOAP message. It processes the SOAP header blocks targeted at it and acts to forward a SOAP message towards an ultimate SOAP receiver.
Ultimate SOAP receiver
The SOAP receiver that is a final destination of a SOAP message. It can be a web service end point.

Monday, May 21, 2012

Enable Line Number in Eclipse


Generate Unique ID Using Java

Sometimes we need to generate unique ID for different purpose.Hear is a simple code block to do so. And ready to use .


public static String generateUniqueId () {
    UUID uuid = UUID.randomUUID();
    Date date = new Date();
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(uuid.toString());
    stringBuilder.append("-");
    stringBuilder.append(String.valueOf(date.getTime()));
   final String UNIQUEID = stringBuilder.toString();
   return UNIQUEID;
}


public static void main (String args[]) {
           System.out.println(PaymentUtil.generateUniqueId());
}



        Sample output : it will differ in every run :

       89c9f0ad-7c25-4955-9496-faf802976caf-1337661403009


Hot Eclipse Short Cut

Hear is some hot shortcut for eclipse user (java) :

Fix Code Shortcut :

  • Ctrl + 1

Indent Code : 
  • Ctrl + I
Format Code :
  • Ctrl +Shift + F
Quick Open Any File (or open resource) :
  • Ctrl + Shoft + R
Run :
  • Ctrl + F11
Debug : 
  • F11
See Outline of A Class :
  • Ctrl + O
Organize Import :
  • Ctrl + Shift + O 
Search In Project :
  • Ctrl + H
Find Next :
  • Ctrl + K
Find Previous :
  • Ctrl + Shift + K




shortcut to select column wise in notepad ++

I was almost giving up to find solution . Finally got it :)

To select a column in notepad++ use a simple shortcut :

"ALT +  Left Mouse Key (drag and drop way )"






Saturday, May 19, 2012

Singleton Design Pattern


Toady Mr. duffer go to his Guru named Goni to learn singleton design pattern.Let stay with Mr. duffer.

Singleton is one of the basic design patten. Name of these pattern comes from mathematical concept of singleton. In mathematics singleton is a set with exactly only one element . Example : Let S = {0} is a set with only one element . So set S is a singleton in mathematics . Hear is the end of background.

Now, i will describe singleton design pattern from software engineering view. Singleton design pattern is a conceptualization or a design pattern to restrict instantiation of a class only one object. And a global access point of that single instance across the system.

Further more :
GOF says, “Ensure a class has only one instance, and provide a global point of access to it. [GoF, p127].

     Example of singleton design pattern :
public class Singleton {
    private static Singleton singleInstance;

    private Singleton() {
    }
    public static Singleton getSingleInstance() {
        if (singleInstance.equals(null)) {
            synchronized (Singleton.class) {
                if (singleInstance.equals(null)) {
                    singleInstance = new Singleton();
                }
            }
        }
        return singleInstance;

    }

    public String helloSingleTon() {
        return "Hello Singles";
    }
}


When to use :
To coordinate actions across any software system with exactly one instance of a class. One can choose singleton design pattern to achieve these.
Some other use :
The Abstract Factory, Builder, and Prototype patterns can use Singletons in their implementation.
  • Facade Objects are often Singletons because only one Facade object is required.
  • State objects are often Singletons.
Some points need to keep in mind in case of singleton design pattern :
  • It makes unit testing harder .
  • Access to the singleton in a multi-threaded context must be serialised 
  • Advocates of dependency injection would regard this as an anti-pattern, mainly due to its use of private and static methods
  • Sometimes singleton is actually is not a singleton.These issue can be explore with the article When a singleton is not a singleton?
Singleton Design Pattern n JAVA API

java.lang.Runtime#getRuntime()  java.awt.Desktop#getDesktop()

That's all. Thanks for stay with me through the journey of singleton .
Happy Coding.


Saturday, January 21, 2012

Collection to Array of Objects

Sometimes we need to convert collection of objects to array of objects.To do so java provide a easy to use method toArray which provides  bridge between collections and older APIs that expect arrays on input.

For example : suppose bookCollection  is a Collection and we can convert it to a new Object type array as :

Object bookObjectArray [] = bookCollection.toArray();

If bookCollection contains only specific type object such as String then we may want to convert the collection to String array . And we can do that as :

String bookStringArray [] = bookCollection.toArray(new String[0]) ; 

{suppose bookCollection contain only one String }





 

Java Collection Framework Overview

Collection framework introduced in java from java 2 platform . A collection is a group of objects that represent a group of objects. Those who are familiar with C++ STL , it will be easy to understand for them as a beginner . But it's not tough concept to grab for new learner.

As a java application developer one can got some advantages with collection framework :
  • Programming effort reduction by providing useful data structures and algorithm.
  • Increase application performance.
  • Provides interoperability between unrelated APIs
  • Reduces the effort required to learn APIs
  • Reduces the effort required to design and implement APIs
  • Fosters software reuse
The collections framework consists of:
  • Collection Interfaces
  • General-purpose Implementations
  • Legacy Implementations
  • Special-purpose Implementations
  • Concurrent Implementations
  • Wrapper Implementations
  • Convenience Implementations
  • Abstract Implementations
  • Algorithms
  • Infrastructure
  • Array Utilities
There are fourteen collection interfaces.
The most basic interface is Collection. These interfaces extend Collection: Set, List, SortedSet, NavigableSet, Queue, Deque, BlockingQueue and BlockingDeque. The other collection interfaces, Map, SortedMap, NavigableMap, ConcurrentMap and ConcurrentNavigableMap do not extend Collection, as they represent mappings rather than true collections. However, these interfaces contain collection-view operations, which allow them to be manipulated as collections. (ref: http://docs.oracle.com/javase/6/docs/technotes/guides/collections/overview.html)

Collection Implementations



Implementations
Hash Table Resizable Array Balanced Tree Linked List Hash Table + Linked List
Interfaces Set HashSet
TreeSet
LinkedHashSet
List
ArrayList
LinkedList
Deque
ArrayDeque
LinkedList
Map HashMap
TreeMap
LinkedHashMap



Friday, January 20, 2012

Garbage Collection and JAVA

Introduction :
Garbage collection is an amazing feature of java. Application developer use java for different kind of application ranging form small to complex enterprise software application. So demand of garbage collection is different based on nature of java application. Java HotSpot™ virtual machine implementation (Java HotSpot™ VM) provides multiple garbage collectors, each designed to satisfy different requirements.

Question is when the choice of garbage collector is a big issue . Most of the case it is not too important. But in case of large application its tightly related to performance issue.

Performance issue of java powered application is tightly related to the proper combination of three parameter namely :

  • garbage collector,
  • heap size,
  • and runtime compiler

Available Garbage Collector :
Java HotSpot VM includes three different collectors, each with different performance characteristics.

  1. The serial collector
  2. The parallel collector
  3. The concurrent collector
Selecting a Garbage Collector :
1. If the application has a small data set (up to approximately 100MB), then serial collector is ok: and we can select it as by : -XX:+UseSerialGC. If the application will be run on a single processor and there are no pause time requirements, then
    • let the VM select the collector, or
    • select the serial collector with -XX:+UseSerialGC.
  1. If (a) peak application performance is the first priority and (b) there are no pause time requirements or pauses of one second or longer are acceptable, then
    • let the VM select the collector, or
    • select the parallel collector with -XX:+UseParallelGC and (optionally) enable parallel compaction with -XX:+UseParallelOldGC.
  2. If response time is more important than overall throughput and garbage collection pauses must be kept shorter than approximately one second, then
    • select the concurrent collector with -XX:+UseConcMarkSweepGC. If only one or two processors are available, consider using incremental mode, described below.

Tuesday, January 03, 2012

Install Apache Web Server From Source


For complete installation documentation, see [ht]docs/manual/install.html or

http://httpd.apache.org/docs/2.2/install.html
 
 Step One : Download  *.tar.gz file from the following link:

 http://mirrors.ispros.com.bd/apache//httpd/httpd-2.2.21.tar.gz

Step Two : Issue following command
$ ./configure --prefix=PREFIX

Step Three : Issue the following command
$ make

Step Four : Issue the following command (need to be root user)
$ make install

Step Five : Issue the following command
$ PREFIX/bin/apachectl start

Step Six : Now open browser and test that apache2 is running by writing the url  : http://localhost

Thta's all.



Find List of Installed Package In Debian

Package management and listing installed package in debian is a regular task to us.And simple linux command can help us to find list of packages which are installed.


To find is php is installed we can use :

dpkg --get-selections | grep php


libapache2-mod-php5                             install
php-geshi                                                 install
php5                                                         install
php5-cli                                                     install
php5-common                                           install
php5-ldap                                                 install
php5-mysql                                               install



To find is python is installed we can use :

dpkg --get-selections | grep python



gimp-python                                     install
ipython                                         install
python                                          install
python-4suite-doc                               install
python-4suite-xml                               install
python-apt                                      install
python-beagle                                   install
python-brlapi                                   install
python-cairo                                    install
python-central                                  install
python-cups                                     install
python-cupsutils                                install
python-dbus                                     install
python-dev                                      install
python-dulwich                                  install
python-eggtrayicon                              install
python-elementtree                              install
python-fpconst                                  install
python-gdata                                    install
python-gdbm                                     install
python-glade2                                   install
python-gmenu                                    install

----------

-----

And to list all installed package under debian we can simply use :

dpkg --get-selections