skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

  • Home
 
  • RSS
  • Twitter
Sunday, September 9, 2012

Power of Java Reflection API

Posted by Admin at 4:43 AM – 0 comments
 
 Reflection API is part of core java. This is the most powerful API that java has ever 
produced. Reflection is the powerful technique and can produce application which would
otherwise impossible. Other than very minor drawbacks of reflection it is always useful to
develop any kind of new configurable API. We can find hundreds of new Java
technologies, tools which are built on reflection.
Reflection API:
This API contains mainly the way to access and modify the class, field, methods and
constructors.

We are very much familiar with above core attributes of JAVA but we should know how to
access and modify them during runtime using reflection.

Class:
Following code tells you how to access/create a class during runtime.
Class c = Class.forName(someVar); 
Here someVar is the fully qualified name of the class we wanted to load in runtime.
Similarly to create array of some primitive type we can also generate at runtime as
following
Class stringArray = Class.forName(“[java.lang.String”);
Primitive type class can be created in runtime as following.
Class primitive = Double.TYPE 
This will create a double type primitive object.

Field:
Accessing or modifying a field.
Class c = Class.forName(someVar); 
Field someFieldName = c.getField(someField); 
We can even get the class name of the above field as following.
Class classOfField = someFieldName.getDeclaringClass();

Method:
Following code is to access a method.
Method method = c.getMethod(someMethod, Object[] params); 

Following code shows to invoke a method.
Object returnObject = method.invoke(Object objectWhoseMethodTobeInvoked, Object[] 
params); 

Constructor:
 Class c =  Class.forName(someVar); 
Constructor constructor = c.getConstructor() ; 
constructor.newInstance();


Obejct hacking using reflection:
This does not really mean any kind of hacking concept. We can break the java security
concepts using reflection. This is called the object hacking concept.
As we all know java is built in some private accessor type. By declaring any field or
constructor or method by this accessor we can not really access or construct the same. But
using reflection we can break these concepts.
We can do that very well by following steps:
1. Get the private constructor or field or method.
2. Set value setAccesible(true).
3. Try accessing now in public way
Ex:
Method m = cls.getMethod(somePriveteMethod);
m.setAccesible(true);
m.invoke(object, null); 
Use:
• Because of the ability to modify access the core attributes of java in runtime
reflection is widely used to develop configurable powerful tools. Like DOZER,
Springs, Hibernate and in most of the tools we use everyday to develop
applications in java.
For example say about DOZER API.
We can have one or many mapping configuration files. DOZER API reads those
mapping files using a XML parser and then creates list of maps of class and the
fields to be mapped. And again it loads the class in runtime and creates the get
and set methods of the fields and invokes the method to get value from source to
set in destination.
  • Runtime implementation based on the identification of class, method, fields like complex operation is very easy to implement  
  • We can reduce thousand lines of code if reflection is used.  These are the overhead use of Reflection. 
  • Reflection is a bit slower code as types are required to be solved dynamically by JVM 
  • Reflection sometimes can produce side effect implies can raise a portability issue.
[ Read More ]
Read more...

Writing JAVA Code to invoke Web Seriveces

Posted by Admin at 2:44 AM – 0 comments
 
 Introduction 

Web services are Web based applications that use open, XML-based standards and
transport protocols to exchange data with clients. Web services are developed using
Java Technology APIs and tools provided by an integrated Web Services Stack.
The term Web services describes a standardized way of integrating Web-based
applications using the XML, SOAP, WSDL and UDDI open standards over an Internet
protocol backbone. XML is used to tag the data, SOAP is used to transfer the data,
WSDL is used for describing the services available and UDDI is used for listing what
services are available. The SOAP engine generally used is AXIS - Apache EXtensible
Interaction System.
Web Services are used primarily as a means for businesses to communicate with each
other and with clients; Web services allow organizations to communicate data without
intimate knowledge of each other's IT systems behind the firewall.

What is SOAP?

SOAP is an XML-based communication protocol and encoding format for inter-
application communication. Originally conceived by Microsoft and Userland software, it
has evolved through several generations; the current spec is version, SOAP 1.2, though
version 1.1 is more widespread. The W3C's XML Protocol working group is in charge of
the specification.
SOAP is widely viewed as the backbone to a new generation of cross-platform cross-
language distributed computing applications, termed Web Services.

 What is AXIS? 

Axis is essentially a SOAP engine -- a framework for constructing SOAP processors
such as clients, servers, gateways, etc. The current version of Axis is written in Java,
but a C++ implementation of the client side of Axis is being developed.
But Axis isn't just a SOAP engine -- it also includes:
  • a simple stand-alone server,  
  • a server which plugs into servlet engines such as Tomcat,  
  • extensive support for the Web Service Description Language (WSDL),  
  • emitter tooling that generates Java classes from WSDL.  
  • some sample programs, and  
  • a tool for monitoring TCP/IP packets.  
Axis is the third generation of Apache SOAP (which began at IBM as "SOAP4J"). In late
2000, the committers of Apache SOAP v2 began discussing how to make the engine
much more flexible, configurable, and able to handle both SOAP and the upcoming
XML Protocol specification from the W3C.
Axis delivers the following key features :-
  • Speed. Axis uses SAX (event-based) parsing to achieve significantly greater speed than earlier versions of Apache SOAP.  
  • Flexibility. The Axis architecture gives the developer complete freedom to insert extensions into the engine for custom header processing, system management, or anything else you can imagine.  
  • Stability. Axis defines a set of published interfaces which change relatively slowly compared to the rest of Axis.  
  • Component-oriented deployment. You can easily define reusable networks of Handlers to implement common patterns of processing for your applications, or to distribute to partners.  
  • Transport framework. We have a clean and simple abstraction for designing transports (i.e., senders and listeners for SOAP over various protocols such as SMTP, FTP, message-oriented middleware, etc), and the core of the engine is completely transport-independent.  
  • WSDL support. Axis supports the Web Service Description Language, version 1.1, which allows you to easily build stubs to access remote services, and also to automatically export machine-readable descriptions of your deployed services from Axis. 
NOTE: The version of AXIS we will be referring to in this document is Apache Axis
2.1.3.

What is a WSDL File? 

The Web Services Description Language is an XML-based language that provides a
model for describing Web services.
WSDL is often used in combination with SOAP and XML Schema to provide web
services over the Internet. A client program connecting to a web service can read the
WSDL to determine what functions are available on the server.
Any special data types used are embedded in the WSDL file in the form of XML
Schema. The client can then use SOAP to actually call one of the functions listed in the
WSDL.
4.1 Using WSDL with Axis
When you make a service available using Axis, there is a unique URL associated with
that service, users may then access the service's URL with a standard web browser and
by appending "?WSDL" to the end of the URL, Axis will automatically generate a service
description for the deployed service, and return it as XML in your browser.
The resulting description may be saved or used as input to proxy-generation, described
next. You can give the WSDL-generation URL to your online partners, and they'll be
able to use it to access your service with toolkits like .NET, SOAP::Lite, or any other
software which supports using WSDL.

Steps for Writing Java Code to Invoke Web Services 
Step 1 - Get Apache Axis2
Download Apache Axis. It can be downloaded from the link http://ws.apache.org/axis2/.
Just unzip it in a dir. Let’s say your Apache Axis is unzipped here: C:\axis2. Let’s call
this dir <AXIS_HOME>.

Step 2 - Get hold of the wsdl
Get hold of the wsdl file that describes the web-service. Every web-service has an
associated wsdl file (as explained above). Normally, the web-service URL with a
‘?wsdl’ suffix appended to it, will show you the wsdl file. So, if a web-service you want to
invoke is available at: http://host:port/superservice/servicemall. You can see the wsdl via
a URL: http://host:port/superservice/servicemall?wsdl

Step 3 - Create the Stub
Stub is nothing but the web-service invocation code that you are going to generate now.
Go to your command line window, change to dir: <AXIS_HOME>\bin, and run this
command:
¾ WSDL2Java -uri servicemall.wsdl
NOTE: servicemall.wsdl should be present in AXIS_HOME\bin directory. Instead of
pointing to that file, you could even use a URL format pointing to the wsdl, now the
command to be run on your command line window is:
¾ WSDL2Java -uri http://host:port/superservice/servicemall?wsdl
You will see that stub code has been generated here: <AXIS_HOME>\bin\src. Here
you will see that a file ends with *Stub.java name, this is the stub file you need. The
contents of this java file look quite complex, but you don’t need to worry about all its
contents. You will only need to know the Constructor, Parameter, and Response related
sub-classes in this file.

Step 4 - Use the Stub
Let’s write a MyWebServiceInvoker.java file now, that will invoke the Stub (which in turn
invokes the actual web-service). Assuming the name of the stub file generated was:
ServiceMallStub, and that the service we want to invoke takes one param (item id),
and returns item details when its method getItemDetails is invoked.
You will notice that parameter and the response are also inner classes in the
generated stub java file, and they have appropriate methods for your use.

public class MyWebServiceInvoker 
{ 
 public static void main(String[] args) 
 { 
  try 
  { 
   com.servicemall.ServiceMallStub  serviceMallStub = new      
     com.servicemall.ServiceMallStub(); 
   com.servicemall.ServiceMallStub.MyItem theParam = new 
     com.servicemall.ServiceMallStub.MyItem(); 
   theParam.setItemid("11"); 
   theParam.MyItemResponse theResp = serviceMallStub.getItemDetails(theParam); 
   boolean result = theResp.getItemResult(); 
   System.out.println("Result is:" + result); 
  } 
  catch (Throwable t) 
  { 
   System.out.println(t); 
  } 
 }

Step 5 - Run
Just compile and run the MyWebServiceInvoker. To compile, you must put the
<AXIS_HOME>\lib\ jar files in the classpath. To run in addition you must have the
compiled stub classes in your classpath too. (You could also use the build.xml that is
generated along with source code for compilation).
Tested with : Apache Axis 2.1.3 and JDK 1.5.

Common Causes of Exception 

A common cause of exception is HTTP Protocol mismatch (although the exception
message doesn’t give suitable hint about it!). You may have to ask your stub to use
HTTP 1.0 protocol, instead of the default HTTP 1.1 protocol it uses. You can do this in
the constructor class of the stub. For setting the required Protocol follow these steps :-

Step 1
Search for this line (in the constructor class of the stub): //Set the SOAP version
_serviceClient.getOptions().setSoapVersionURI(org.apache.axiom.soap.SOAP12Const
ants.SOAP_ENVELOPE_NAMESPACE_URI);

Step 2
Now, just below this line, add this line:
_serviceClient.getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants
.HTTP_PROTOCOL_VERSION,
org.apache.axis2.transport.http.HTTPConstants.HEADER_PROTOCOL_10);

Step 3
Compile, and try again.

[ Read More ]
Read more...

XML Parsing with JAVA with Example

Posted by Admin at 1:46 AM – 0 comments
 
Writing XML documents is very straightforward, but reading them is not nearly as
simple. Fortunately, we can use an XML parser to read the document for us. The
XML parser exposes the contents of an XML document through an API. A client
application reads an XML document through this API. As well as reading the
document and providing the contents to the client application, the parser also checks
the document for well-formedness and (optionally) validity. If it finds an error, it
informs the client application.
XML parser is a software module to read documents and a means to provide access to
their content. XML parser generates a structured tree to return the results to the
browser. An XML parser is similar to a processor that determines the structure and
properties of the data. An XML parser can read a XML document to create an output
to generate a display form. Now, XML parser for Java runs on any platform where
there is Java virtual machine. It is sometimes called XML4J. It has an interface which
allows you to take a string of XML formatted text, pick the XML tags and use them to
extract the tagged information.
Among the various XML parsers, the two mostly used ones are SAX parser & DOM
parser. Here is a brief description of these two different parsers.

SAX
SAX, the Simple API for XML, is the gold standard of XML APIs. It is the most
complete and correct by far. Given a fully validating parser that supports all its
optional features, there is very little you can’t do with it. It has one or two holes, but
they're really off in the weeds of the XML specifications, and you have to look pretty
hard to find them. SAX is an event driven API. The SAX classes and interfaces model
the parser, the stream from which the document is read, and the client application
receiving data from the parser. However, no class models the XML document itself.
Instead the parser feeds content to the client application through a callback interface,
much like the ones used in Swing and the AWT. This makes SAX very fast and very
memory efficient (since it doesn’t have to store the entire document in memory).
However, SAX programs can be harder to design and code because you normally
need to develop your own data structures to hold the content from the document.
SAX works best when your processing is fairly local; that is, when all the information
you need to use is close together in the document. For example, you might process
one element at a time. Applications that require access to the entire document at once
in order to take useful action would be better served by one of the tree-based APIs
like DOM or JDOM. Finally, because SAX is so efficient, it’s the only real choice for
truly huge XML documents. Of course, “truly huge” has to be defined relative to
available memory. However, if the documents you're processing are in the gigabyte
range, you really have no choice but to use SAX.
DOM
DOM, the Document Object Model, is a fairly complex API that models an XML
document as a tree. Unlike SAX, DOM is a read-write API. It can both parse existing
XML documents and create new ones. Each XML document is represented as
Document object. Documents are searched, queried, and updated by invoking methods
on this Document object and the objects it contains. This makes DOM much more
convenient when random access to widely separated parts of the original document is
required. However, it is quite memory intensive compared to SAX, and not nearly as
well suited to streaming applications.
Ahead in the document I have included example of XML parsing with Java using both
of these parsers.
XML Parsing with JAVA
I would like to start with an example of how to parse a XML file create Java Objects
and manipulate them.
The idea here is to parse the employees.xml file with content as below
<?xml version="1.0" encoding="UTF-8"?>
<Office>
<Employee type="permanent">
<Name>Debamalya</Name>
<Id>235960</Id>
<Age>25</Age>
</Employee>
<Employee type="contract">
<Name>Rishin</Name>
<Id>3675</Id>
<Age>24</Age>
</Employee>
<Employee type="permanent">
<Name>Debalina</Name>
<Id>3676</Id>
<Age>28</Age>
</Employee>
</Office>
From the parsed content create a list of Employee objects and print it to the console.
The output would be something like
Employee Details - Name:Debamalya, Type:permanent, Id:235960, Age:25.
Employee Details - Name:Rishin, Type:contract, Id:3675, Age:24.
Employee Details - Name:Debalina, Type:permanent, Id:3676, Age:28.
I will start with a DOM parser to parse the xml file, create Employee value objects
and add them to a list. To ensure we parsed the file correctly let's iterate through the
list and print the employees data to the console. Later we will see how to implement
the same using SAX parser.
In a real world situation you might get an xml file from a third party vendor which
you need to parse and update your database.
Using DOM Parser:
This program DomParserExample.java uses DOM API.
The steps are
• Get a document builder using document builder factory and parse the xml file
to create a DOM object.
• Get a list of employee elements from the DOM.
• For each employee element get the id, name, age and type. Create an
employee value object and add it to the list.
• At the end iterate through the list and print the employees to verify we parsed
it right.

a) Getting a document builder
private void parseXmlFile(){ 
 DocumentBuilderFactory dbf = 
   DocumentBuilderFactory.newInstance(); 

 try { 
  //Using factory get an instance of document builder 
  DocumentBuilder db = dbf.newDocumentBuilder(); 
  //parse using builder to get DOM representation of the XML 
  file 
  dom = db.parse("employees.xml"); 

 }catch(ParserConfigurationException pce) { 
  pce.printStackTrace(); 
 }catch(SAXException se) { 
  se.printStackTrace(); 
 }catch(IOException ioe) { 
  ioe.printStackTrace(); 
 } 
}

b) Get a list of employee elements
Get the rootElement from the DOM object. From the root element get all employee
elements. Iterate through each employee element to load the data.
private void parseDocument(){ 
 //get the root element 
 Element docEle = dom.getDocumentElement(); 

 //get a nodelist of elements 
 NodeList nl = 
   docEle.getElementsByTagName("Employee"); 
 if(nl != null && nl.getLength() > 0) { 
  for(int i = 0 ; i < nl.getLength();i++) { 

   //get the employee element 
   Element el = (Element)nl.item(i); 

   //get the Employee object 
   Employee e = getEmployee(el); 

   //add it to list 
   myEmpls.add(e); 
  } 
 } 
}
c) Reading in data from each employee.
/** 
 * I take an employee element and read the values in, create 
 * an Employee object and return it 
 */ 
private Employee getEmployee(Element empEl) { 

 //for each  element get text or int values of //name ,id, age and name 
 String name = getTextValue(empEl,"Name"); 
 int id = getIntValue(empEl,"Id"); 
 int age = getIntValue(empEl,"Age"); 

 String type = empEl.getAttribute("type"); 

 //Create a new Employee with the value read from the xml nodes 
 Employee e = new Employee(name,id,age,type); 

 return e; 
} 

/** 
 * I take a xml element and the tag name, look for the tag 
and  
 * get the text content 
 * i.e for Deb xml snippet 
if 
 * the Element points to employee node and tagName is  
 *'name' I will return Deb 
 */ 
private String getTextValue(Element ele, String tagName) { 
 String textVal = null; 
 NodeList nl = ele.getElementsByTagName(tagName); 
 if(nl != null && nl.getLength() > 0) { 
  Element el = (Element)nl.item(0); 
  textVal = el.getFirstChild().getNodeValue(); 
 } 

 return textVal; 
} 

/** 
 * Calls getTextValue and returns a int value 
 */ 
private int getIntValue(Element ele, String tagName) { 
 //in production application you would catch the exception 
 return Integer.parseInt(getTextValue(ele,tagName)); 
} 

d) Iterating and printing.
private void printData(){ 
 System.out.println("No of Employees '" + myEmpls.size() + 
   "'."); 
 Iterator it = myEmpls.iterator(); 
 while(it.hasNext()) { 
  System.out.println(it.next().toString()); 
 } 
}

Using SAX Parser:
This program SAXParserExample.java parses a XML document and prints it on the
console.
Sax parsing is event based modeling. When a Sax parser parses a XML document and
every time it encounters a tag it calls the corresponding tag handler methods.
When it encounters a Start Tag it calls this method
public void startElement(String uri,..
When it encounters a End Tag it calls this method
public void endElement(String uri,...
Like the DOM example this program also parses the xml file, creates a list of
employees and prints it to the console. The steps involved are
• Create a Sax parser and parse the xml
• In the event handler create the employee object
• Print out the data
Basically the class extends DefaultHandler to listen for call back events. And we
register this handler with the Sax parser to notify us of call back events. We are only
interested in start event, end event and character event.
In start event if the element is employee we create a new instant of employee object
and if the element is Name/Id/Age we initialize the character buffer to get the text
value.
In end event if the node is employee then we know we are at the end of the employee
node and we add the Employee object to the list. If it is any other node like
Name/Id/Age we call the corresponding methods like setName/SetId/setAge on the
Employee object. Java Bean classes can be used for this. In character event we store
the data in a temp string variable.

a) Create a Sax Parser and parse the xml
private void parseDocument() { 

 //get a factory 
 SAXParserFactory spf = 
   SAXParserFactory.newInstance(); 
 try { 

  //get a new instance of parser 
  SAXParser sp = spf.newSAXParser(); 

  //parse the file and also register this class for call backs 
  sp.parse("employees.xml", this); 

 }catch(SAXException se) { 
  se.printStackTrace(); 
 }catch(ParserConfigurationException pce) { 
  pce.printStackTrace(); 
 }catch (IOException ie) { 
  ie.printStackTrace(); 
 } 
} 

b) In the event handlers create the Employee object and call the corresponding setter
methods.
public void startElement(String uri, String localName, String 
  qName, Attributes attributes) throws SAXException { 
 //reset 
 tempVal = ""; 
 if(qName.equalsIgnoreCase("Employee")) { 
  //create a new instance of employee 
  tempEmp = new Employee(); 
  tempEmp.setType(attributes.getValue("type")); 
 } 
} 

public void characters(char[] ch, int start, int length) 
  throws SAXException { 
 tempVal = new String(ch,start,length); 
} 

public void endElement(String uri, String localName, 
  String qName) throws SAXException { 

 if(qName.equalsIgnoreCase("Employee")) { 
  //add it to the list 
  myEmpls.add(tempEmp); 

 }else if (qName.equalsIgnoreCase("Name")) { 
  tempEmp.setName(tempVal); 
 }else if (qName.equalsIgnoreCase("Id")) { 
  tempEmp.setId(Integer.parseInt(tempVal)); 
 }else if (qName.equalsIgnoreCase("Age")) { 
  tempEmp.setAge(Integer.parseInt(tempVal)); 
 } 

}

c) Iterating and printing.
private void printData(){ 
 
 System.out.println("No of Employees '" + myEmpls.size() + 
"'."); 
 
  Iterator it = myEmpls.iterator(); 
  while(it.hasNext()) { 
   System.out.println(it.next().toString()); 
  } 
 }

Writing XML with Java
The previous programs illustrated how to parse an existing XML file using both SAX
and DOM Parsers. But generating a XML file from scratch is a different story, for
instance you might like to generate an xml file for the data extracted from a database.
To keep the example simple this program XMLCreatorExample.java generates XML
from a list preloaded with hard coded data. The output will be book.xml file with the
following content.
<?xml version="1.0" encoding="UTF-8"?>
<Books>
<Book Subject="Java 1.5">
<Author>Kathy Sierra .. etc</Author>
<Title>Head First Java</Title>
</Book>
<Book Subject="Java Architect">
<Author>Kathy Sierra .. etc</Author>
<Title>Head First Design Patterns</Title>
</Book>
</Books>
The steps involved are
• Load Data
• Get an instance of Document object using document builder factory
• Create the root element Books
• For each item in the list create a Book element and attach it to Books element
• Serialize DOM to FileOutputStream to generate the xml file "book.xml".

a) Load Data.
/** 
 * Add a list of books to the list 
 * In a production system you might populate the list from a db
 */ 
private void loadData(){ 
 myData.add(new Book("Head First Java", 
   "Kathy Sierra .. etc","Java 1.5")); 
 myData.add(new Book("Head First Design Patterns", 
   "Kathy Sierra .. etc","Java Architect")); 
} 
b) Getting an instance of DOM.
/** 
 * Using JAXP in implementation independent manner create a 
document object 
 * using which we create a xml tree in memory 
 */ 
private void createDocument() { 

 //get an instance of factory 
 DocumentBuilderFactory dbf = 
   DocumentBuilderFactory.newInstance(); 
 try { 
  //get an instance of builder 
  DocumentBuilder db = dbf.newDocumentBuilder(); 

  //create an instance of DOM 
  dom = db.newDocument(); 

 }catch(ParserConfigurationException pce) { 
  //dump it 
  System.out.println("Error while trying to 
    instantiate DocumentBuilder " + pce); 
    System.exit(1); 
 } 

} 
}
c) Create the root element Books.
/** 
 * The real workhorse which creates the XML structure 
 */ 
private void createDOMTree(){ 

 //create the root element  

 Element rootEle = dom.createElement("Books"); 
 dom.appendChild(rootEle); 

 //No enhanced for 
 Iterator it  = myData.iterator(); 
 while(it.hasNext()) { 
  Book b = (Book)it.next(); 
  //For each Book object  create element and attach it to root 
  Element bookEle = createBookElement(b); 
  rootEle.appendChild(bookEle); 
 } 

}
d) Creating a book element.
/** 
 * Helper method which creates a XML element 
 * @param b The book for which we need to create an xml 
representation 
 * @return XML element snippet representing a book 
 */ 
private Element createBookElement(Book b){ 
 Element bookEle = dom.createElement("Book"); 
 bookEle.setAttribute("Subject", b.getSubject()); 
 //create author element and author text node and attach it to bookElement 
 Element authEle = dom.createElement("Author"); 
 Text authText = dom.createTextNode(b.getAuthor()); 
 authEle.appendChild(authText); 
 bookEle.appendChild(authEle); 
 //create title element and title text node and attach it to bookElement 
 Element titleEle = dom.createElement("Title"); 
    Text titleText = dom.createTextNode(b.getTitle()); 
 titleEle.appendChild(titleText); 
 bookEle.appendChild(titleEle); 
 return bookEle; 
}
e) Serialize DOM to FileOutputStream to generate the xml file "book.xml".
/** 
 * This method uses Xerces specific classes 
 * prints the XML document to file. 
 */ 
private void printToFile(){ 
 try 
 { 
  //print 
  OutputFormat format = new OutputFormat(dom); 
  format.setIndenting(true); 
  //to generate output to console use this serializer 
  //XMLSerializer serializer = new 
  XMLSerializer(System.out, format); 

  //to generate a file output use fileoutputstream instead of 
  system.out 
  XMLSerializer serializer = new XMLSerializer( 
    new FileOutputStream(new File("book.xml")), 
    format); 
  serializer.serialize(dom); 
 } catch(IOException ie) { 
  ie.printStackTrace(); 
 } 
}
Note:
The Xerces internal classes OutputFormat and XMLSerializer are in different
packages.
In JDK 1.5 with built in Xerces parser they are under
com.sun.org.apache.xml.internal.serialize.OutputFormat
com.sun.org.apache.xml.internal.serialize.XMLSerializer
In Xerces 2.7.1 which we are using to run these examples they are under
org.apache.xml.serialize.XMLSerializer
org.apache.xml.serialize.OutputFormat
We are using Xerces 2.7.1 with JDK 1.4 and JDK 1.3 as the default parser with JDK
1.4 is Crimson and there is no built in parser with JDK 1.3.
Also please remember it is not advisable to use parser implementation specific classes
like OutputFormat and XMLSerializer as they are only available in Xerces and if
you switch to another parser in the future you may have to rewrite.
Another example, of writing a XML containing the first 10 Fibonacci numbers is as
follows.
<?xml version="1.0"?>
<Fibonacci_Numbers>
<fibonacci>1</fibonacci>
<fibonacci>1</fibonacci>
<fibonacci>2</fibonacci>
<fibonacci>3</fibonacci>
<fibonacci>5</fibonacci>
<fibonacci>8</fibonacci>
<fibonacci>13</fibonacci>
<fibonacci>21</fibonacci>
<fibonacci>34</fibonacci>
<fibonacci>55</fibonacci>
</Fibonacci_Numbers>
To produce this, just add string literals for the <fibonacci> and </fibonacci> tags
inside the print statements, as well as a few extra print statements to produce the XML
declaration and the root element start- and end-tags. XML documents are just text,
and you can output them any way you’d output any other text document. The
FibonacciXML.java is created for this.

import java.math.BigInteger;

public class FibonacciXML {
 public static void main(String[] args) {
  BigInteger low = BigInteger.ONE;
  BigInteger high = BigInteger.ONE;
  System.out.println("");
  System.out.println("");
  for (int i = 0; i < 10; i++) {
   System.out.print(" ");
   System.out.print(low);
   System.out.println("");
   BigInteger temp = high;
   high = high.add(low);
   low = temp;
  }
  System.out.println("");
 }
}
   
Running Programs in JAVA
The instructions to compile and run these programs vary, based on the JDK that you
are using. This is due to the way the XML parser is bundled with various Java
distributions. These instructions are for Windows OS. For Unix or Linux OS you just
need to change the folder paths accordingly. Xerces parser is bundled with the JDK
1.5 distribution. So you need not download the parser separately.

Running DOMParserExample
1. Place DomParserExample.java, Employee.java, employees.xml to
c:\xercesTest
2. Go to command prompt and type
cd c:\xercesTest
3. To compile, type
javac -classpath . DomParserExample.java
4. To run, type
java -classpath . DomParserExample

Running SAXParserExample
1. Place SAXParserExample.java, Employee.java, employees.xml to
c:\xercesTest
2. Go to command prompt and type
cd c:\xercesTest
3. To compile, type
javac -classpath . SAXParserExample.java
4. To run,type
java -classpath . SAXParserExample

Running XMLCreatorExample
1. Place XMLCreatorExample.java, Book.java to c:\xercesTest
2. Go to command prompt and type
cd c:\xercesTest
3. To compile, type
javac -classpath . XMLCreatorExample.java
4. To run, type
java -classpath . XMLCreatorExample


Running FibonacciXML
1. Place FibonacciXML.java to c:\xercesTest
2. Go to command prompt and type
cd c:\xercesTest
Internal Use 15
XML Parsing with JAVA
3. To compile, type
javac -classpath . FibonacciXML.java
4. To run, type
java -classpath .


Comparison
Both SAX & DOM have there advantages & disadvantages but need to be used
according to the requirement.
SAX:
  1.  Parses node by node
  2.  Doesn’t store the XML in memory
  3.  We can’t insert or delete a node
  4.  Top to bottom traversing
DOM
  1. Stores the entire XML document into memory before processing.
  2. Occupies more memory
  3. We can insert or delete nodes
  4. Traverse in any direction.
If we need to find a node and doesn’t need to insert or delete we can go with SAX
itself otherwise we can use DOM parser, provided we have enough memory in place.
  
Conclusion
I hope this document will be useable to enlighten a beginner to be able to successfully
code for extracting data from an xml. XMLs are one of the most widely used
structures for storing data, and Java provides the most commonly used parsers. In real
life situations, we receive XMLs from a third party source which are needed to be
parsed & data need to be stored in databases. These motives can be easily met using
DOM or SAX XML parsers in Java.
We can have a JMS configured system where XMLs are received in a
automated way(these can be done using MDB), the same XMLs can be parsed using
Java parsers. The parser code can be scheduled to run automatically using a .ksh
script. The parsed value can be easily stored in oracle databases using simple JDBC
codes. In most of the IT projects XML sizes are usually huge & those are complex. In
such cases it is not possible to use DOM parser, but SAX parser is used frequently.
Although DOM parsers are easier to be coded, SAX parsers are more rapidly used in
case of real-life systems. 
[ Read More ]
Read more...
Friday, September 7, 2012

AntiSamy – A Java Solution for XSS Attacks

Posted by Admin at 12:17 PM – 0 comments
 
The increasing popularity of web applications has increased the threats and security
vulnerabilities. One such vulnerability is due to XSS or Cross-Site scripting. XSS is an attack
technique that forces web application to echo the malicious executable code supplied by
the attacker, which then loads in the results in the user’s web browser. The data supplied is
usually the HTML/JavaScript code that executes at the client side.
XSS vulnerabilities can be classified into three types – Firstly, DOM based which exists in
the clients web page, Secondly; on-Persistent or Reflected is when malicious input
supplied is displayed back onto the screen after returning back from the server. This is
most common vulnerability found in most of the web applications and finally the most
dangerous XSS vulnerability - Persistent or Second Order or Stored XSS wherein the
malicious data supplied is stored in the persistent storage or database.
Thus, there is a need to focus on handling these XSS vulnerabilities using frameworks or
open source solutions.
Threats of Cross-Site Scripting
Some of the most common threats by cross-site scripting are-
  • Inserting a script into a web page collects the user cookies which are then sent back to the attacker. This situation would be dangerous particularly in single sign-on applications 
  • Insertion of a malicious link into a well known meaningful website can cause the user clicking it to be navigated to a harmful site. 
  • XSS can cause sensitive data to be sent back to the attacker.
Solutions for handling cross-site scripting
Some of the possible solutions to handle XSS are –
  • Encoding and Decoding – Encode HTML input and alternatively decode the pre-defined tags. This ensures all the output is encoded and allows only specified tags to be included. However it is difficult to properly decode the attributes and enumerate all the required tags. 
  • Use Mark-Up languages such as BBCode – Create mark-up tags that can be decoded using Markup parsers. This ensures the required and valid tags insertion but enforces the developers to learn the language. 
  • Using XSD for validation – Create an XSD file that defines the allowable tags and HTML elements. Convert the HTML content into XML and verify the XML against the XSD. This ensures valid and allowable tag insertion and the implementation is flexible enough but an XSD needs to be created for all HTML elements and no response or error message can be given to the user. 
  • Use Open Source XSS solutions such as AntiSamy – These solutions provide APIs that can be called by the web applications. These APIs are simple to use and also provide user-friendly error messages to the user.
Introduction to AntiSamy
AntiSamy is a project by OWSAP (Open Web Application Security Project). It is an
enterprise web input validation and output encoding tool that provides us with a set of
API that can be invoked to filter and validate the input against XSS and to ensure the user
input supplied is in compliance with an application’s rules.

AntiSamy has been released to support Java and .NET applications. It is simple to use and
flexible enough and can be modified depending on the project needs. The tool uses
NekoHTML and Policy file for validating HTML and CSS inputs.

NekoHTML is a simple HTML scanner that parses HTML into XML using a parser. The policy
file consists of directives, common attributes, regular expressions, general tag attributes,
css and tag rules. It can be modified to suit the project requirements.

The input HTML supplied by the user is first parsed using NekoHTML and then validated
against the policy files. User-friendly error messages are returned back to the user.
There are four types of policy files that can however be modified to meet project
requirements. These are –
  • antisamy-slashdot.xml - This policy file strictly allows only <b>, <u>, <i>, <a>, <blockquote> HTML tags. No CSS tags are allowed. 
  • antisamy-ebay.xml – The policy file strictly emphasizes on the input containing more rich content.  
  • antisamy-myspace.xml – This policy file restricts the user from submitting Javascript.  
  • antisamy-anythinggoes.xml – This policy file allows every single HTML and CSS 
elements except Javascript and other phishing CSS tags.
Integrating AntiSamy with the web application is very simple and can be done by
following the steps below –
  • Download antisamy.jar, nekoHtml.jar and xercesImpl.jar and place them in the class-path 
  • Download the required policy file and place it in the class-path 
  • Call the API methods for scanning / filtering the user input 
AntiSamy can be integrated with a Maven application. The pom.xml entry for the same is –
<repository>
<id>wso2-maven2-repository</id>
<url>http://dist.wso2.org/maven2</url>
</repository>
<dependency>
<groupId>antisamy</groupId>
<artifactId>antisamy-bin</artifactId>
<version>1.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.7</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.8.0</version>
<scope>compile</scope>
</dependency>

How does AntiSamy work?
The fig below describes the workflow of AntiSamy for HTML and CSS inputs

HTML / XHTML Workflow


CSS Workflow 


For instance, consider the HTML input
<body>
<p> This is a test <h1 onclick= “alert(‘malicious code’);” > for </h1>
AntiSamy </p>
</body>
The above mentioned code consists of malicious code “onclick=”alert(‘malicious code’)” “
embed in <h1> tags.
This input when filtered using AntiSamy is first cleaned using NekoHtml
The parsed input is then validated using antisamy-slashdot.xml policy file to validate and
filter the malicious code.

This input when filtered using AntiSamy returns a clean output as shown below along with
a user-friendly message.


Features
Some of the key features of AntiSamy are as listed below–
  • Simple API to use 
  • Policy files can be customized thus provides flexibility to the desired behavior  
  • Support for Maven applications 
  • User-friendly error messages are displayed. 
  • Works with broken HTML and CSS 
  • Support for other languages like ColdFusion and .NET. 
  • Internationalized error messages for English, Italian, Portuguese, Russian and Chinese.
Sample Code
Let us now create an application that uses AntiSamy for filtering the input data for XSS. Let
us create a wrapper class AntiSamyWrapper that contains scan() method to filter the input
data. The scan() of this class internally passes the input data and the policy file to the
scan() of AntiSamy.java class. This method returns an instance of CleanResults class.
The instance of CleanResults contains the clean input and error messages while filtering
the input data.
AntiSamyWrapper is a wrapper class that interacts with the AntiSamy API for validating
and filtering the input. The class returns a singleton instance when getInstance() of the
class is invoked. The scan() of the class can be called by passing the input data. The data is
passed through the API that returns the instance of CleanResults. This class contains the
error messages and clean input.


Pre-Requisites
JDK 1.4 or above
antisamy.jar – (can be downloaded from http://code.google.com/p/owaspantisamy/downloads/list ) 
AntiSamy Policy Files - (can be downloaded from
http://code.google.com/p/owaspantisamy/downloads/list )
NekoHTML.jar - (can be downloaded from http://sourceforge.net/projects/nekohtml/ )
XercesImpl-2.5.jar - (can be downloaded from http://www.ibiblio.org/maven/xerces/jars/)

Step-by-Step approach for implementing AntiSamy
  • Download antisamy.jar, nekoHtml.jar and xercesImpl.jar and place them in the class-path.  
  • Download the example policy file (antisamy-slashdot-1.3.xml) and place it in the class-path. Customize the policy file if required. 
  • Create java classes and modify the classes as mentioned below 
  • Run the class files and check the output. 
AntiSamyWrapper.java
//Add package statement 
//Import statement 
public final class AntiSamyWrapper 
{ 
 private static AntiSamyWrapper antiSamyWrapper; 
 public AntiSamy antiSamy; 
 public Policy policy; 
 public CleanResults cleanResults; 
 String policyFilePath = ; 
 String policyFileName = ; 
 private AntiSamyWrapper 
 { 
  try 
  { 
   policy = Policy.getInstance(this.getClass(). 
     getResourceAsStream(policyFilePath + 
       policyFileName)); 
  } 
  catch(PolicyException pe) 
  { 
   //Add code here to handle exceptions 
  } 
  antiSamy= new AntiSamy(); 
 } 
 /* Returns the Singleton instance of the class 
  */ 
 public static AntiSamyWrapper getInstance() 
 { 
  if(antiSamyWrapper == null) 
  { 
   antiSamyWrapper = new AntiSamyWrapper(); 
  } 
  return antiSamyWrapper; 
 } 
 public String scan(String inputString) 
 { 
  try 
  { 
   cleanResults = antiSamy.scan(inputString,policy); 
   // Add code here to handle errors by accessing method 
   // getNumberOfErrors() 
  } 
  catch(ScanException sc) 
  { 
   //Add code here to handle exceptions 
  } catch(PolicyException pe) 
  { 
   // Add code here to handle exceptions 
  } 
  return cleanResults.getCleanHTML(); 
 } 
} 

AntiSamyTest.java
///Add package statement 

//Import statement 

public class AntiSamyTest
{
 public static void main(String[] args) 
 { 
  String inputData = “ This is  a test  for AntiSamy”; 
  String cleanInput = AntiSamyWrapper.getInstance().scan(inputData); 
  System.out.println(“ Clean Output from AntiSamy -- > ”  + cleanInput); 

 }
}
Run AntiSamyTest.java class. The value for the “cleanInput” is filtered output from
AntiSamyWrapper class and the output of the program is -
Clean Output from AntiSamy -- > this is a <b> for</b>
The error message by invoking scan() of AntiSamy class is –
The body tag has been filtered for security reasons. The contents of the tag
will remain in place., The b tag contained an attribute that we could not
process. The onclick attribute has been filtered out, but the tag is still
in place. The value of the attribute was "alert&#40;&#39;hi&#39;&#41;".
This message can be viewed by adding the following code in scan() of AntiSamyWrapper
class.
cleanResults = antiSamy.scan(inputString,policy); // Existing Code
ArrayList errorList = cleanResults.getErrorMessages();
[ Read More ]
Read more...

An Overview of Tapestry Components

Posted by Admin at 11:45 AM – 0 comments
 
Introduction: 
Tapestry is a component-based web application framework, written in Java. Tapestry is
more than a simple templating system; Tapestry builds on the Java Servlet API to build a
platform for creating dynamic, interactive web sites. More than just another templating
language, Tapestry is a real framework for building complex applications from simple,
reusable components. The current stable Tapestry release is version 5.1.0.5. Version 4 and
below are relatively similar, whereas version 5 contains substantial changes. This
document describes the parameters and bindings of Tapestry in detail. It is not a tutorial
that is available as a separate document. Instead, this is a guide to some of the internals of
Tapestry, and is intended for experienced developers who wish to leverage Tapestry fully.

An overview of Tapestry:
Tapestry is an object-oriented Java web application framework to implement applications
in accordance with the model-view-controller design pattern.

MVC Design Pattern:
The main aim of MVC design pattern is to separate the business logic and data (the Model)
from the display logic (the View).
Ideally, the Model should have no idea of what displays its data (and how that data is
displayed) as there can potentially be numerous different views. The View in its turn
should have no idea of where the data it displays come from, as data can potentially come
from just anywhere. It is for the piece of code named Controller to ensure that a correct
piece of data was sent for processing to the Model and that the result of that processing
was forwarded to a proper view.

Tapestry – Component Centric:
The hardest part of understanding Tapestry is the fact that it is component-centric not
operation-centric. Most web technologies (Struts , servlets, PHP, etc.) are operation-centric.
We create servlets (or Actions, or what have you) that are invoked when a user clicks a link
or submits a form. We are responsible for selecting an appropriate URL, and the name and
type of any query parameters, so that we can pass along the information that we need in
the URL.

Everything is different inside Tapestry. Tapestry applications consist of pages; pages are
constructed from smaller components. Components may themselves be constructed from
other components. Every page has a unique name, and every component within a page
has its own unique id ... this is a component object model. Effectively, every component
has an address that can easily be incorporated into a URL.
In practical terms, we don't write a servlet for the add-item-to-shopping-cart operation. In
fact, we don't even write an add-item-to-shopping-cart component. What we do is take an
 existing component, such as Direct Link , and configure it. When the component renders, it
will create a callback URL. When you click that link, the callback URL (which includes the
name of the page and the id of the component within the page) will invoke a method on
the component ... and that method invokes your application-specific listener method.

Listener Methods:
Listener methods in Tapestry are very similar in intent to delegates in C#. In both cases, a
method of a particular object instance is represented as an object. We supply just the
listener method ... not an entire servlet. Tapestry takes care that our listener method is
invoked at the right time, under the right conditions. You don't have to think about how to
build that URL, what data goes in the URL, or how to hook it up to your application-specific
code--that's all handled by the framework.

Parameters and Bindings:
Tapestry components are designed to work with each other, within the context of a page
and application. The process of rendering a page is largely about pulling information from
a source into a component and doing something with it. For example, on a welcome page,
a component might get the userName property from the visit object and insert it into the
HTML response. Each component has a specific set of parameters. Parameters have a
name, a type and may be required or optional.
Parameters define the type of value needed, but not the actual value. This value is
provided by a special object called a binding. The binding is a bridge between the
component and the parameter value, exposing that value to the component as it is
needed. The reason for all this is to allow pages, and the components within them, to be
shared by many concurrent sessions ... a major facet in Tapestry's strategy for maintaining
application scalability. When a component needs the value of one of its parameters, it
must obtain the correct binding, an instance of interface IBinding, and invoke methods on
the binding to get the value from the binding. Additional methods are used with output
parameters to update the binding property.
There are two types of bindings: static and dynamic.
Static Bindings:
Static bindings are read-only; the value for the binding is specified in the component
specification as shown below.
<component id="now" type="Insert"> <binding name="value" value="currentDate"/> </component>
This is understood by Tapestry in the following way: to obtain the value, evaluate the
currentDate expression. Which means: go to the page class, find a method named
getCurrentDate(), invoke it, and whatever it returns will be the value you are looking for. So
the next step is to create the page class with the getCurrentDate() method in it.
Dynamic Bindings:
Dynamic bindings are more prevalent and useful. A dynamic binding uses a JavaBeans
property name to retrieve the value when needed by the component. The source of this
data is a property of some component. In fact, dynamic bindings use property paths,
allowing a binding to 'crawl' deeply through an object graph to access the value it needs.
This frees the components from relying totally on the properties of their container, instead
they are free to access properties of more distant objects.


Connected Parameters:
In most cases, a developer is not interested in bindings; an easier model for developers is
one in which Tapestry uses the parameters and bindings to set properties of the
component automatically. Starting in release 2.1, Tapestry includes this behavior, with
some constraints and limitations.
Part of the <parameter> specification for a parameter is the direction, which can be one of
the following values:
in
Input parameter; the value is drawn from the binding (if bound) and applied to the
corresponding component property just before rendering the component.
form
A parameter which matches the semantics of a form component. The parameter is treated
like an in parameter when the page is rendering. When the form containing the
component is submitted, the connected property is read (after the component renders),
and the value applied to the parameter.
custom
Tapestry does not try to connect the parameter with any property; the component is
responsible for accessing the binding and retrieving or setting values. This type must be
used for any kind of output parameter, or for an input parameter where the property may
be accessed other than during the rendering of the component.
Defining a parameter as direction in causes Tapestry to connect the parameter to the
corresponding property of the component. The parameter specification must identify the
Java type of the property. Properties must be read/write (they must have both getter and
setter methods).
Tapestry will set properties from parameters just before rendering the component. After
the component renders, the parameters are cleared; they are returned to inital values.
Tapestry reads these initial values just before it sets the properties the first time. This
makes it very easy to set defaults for optional parameters: just provide a default value for
the corresponding instance variable.
Connected Parameter - Specification

<specification ...>
<parameter name="color" direction="in" java-type="java.awt.Color"/>
...
Connected Parameter - Java Code
public class ColorComponent extends AbstractComponent {
 private Color color = Color.RED;

 public Color getColor()

 {
  return color;
 }

 public void setColor(Color color) {
  this.color = color;
 }

 protected void renderComponent(IMarkupWriter writer, IRequestCycle cycle) throws RequestCycleException 
 { 
 writer.begin("font"); 
 writer.attribute("color", ^RequestContext;.encodeColor(color); 
 renderWrapped(writer, cycle); 
 writer.end(); 
 }
}

In this example, the component writes its content inside a <font> element, with the HTML
color attribute set from the color parameter. RequestContext includes a static
convienience method for converting from a Color object to an encoded color that will be
meaningful to a web browser.
The parameter is optional and defaults to red if not specified (that is, if the parameter is not
bound). At runtime, Tapestry will invoke setColor() first (if the color parameter is bound). It
will then invoke renderComponent(). Finally (even if renderComponent() throws an
exception) it will invoke setColor() again, to restore it back to the default value, Color.RED.
This code includes a defect: because the parameter is optional, there is nothing to prevent
it from being bound to null.

Formal vs Informal Parameters:
Tapestry components have two types of parameters: formal and informal.

Formal Parameter:
Formal parameters are parameters defined in the component specification. Each formal
parameter has a specific (case sensitive) name and may be required or optional.
In many cases, there is a one-to-one mapping between a Tapestry component and a
specific HTML tag. For example, Body and <body>, Form and <form>, etc. In other cases, a
Tapestry component produces a known single HTML tag. For example, ActionLink,
DirectLink, PageLink and ServiceLink all produce an <a> tag. To support truly rich
interfaces, it is often necessary to specify additional attributes of the HTML tags; usually
this means setting the class of a tag so as to get visual properties from a style sheet. In
other cases, display attributes may be specified inline. In theory, these components could
define additional formal parameters for each possible HTML attribute, but there are a huge
number of possible attributes, many of which are specific to a particular browser.
  
Informal Parameter:
Instead, Tapestry has the concept of an informal parameter. This is an "additional"
parameter, not specified in the component's specification. In most cases, where informal
parameters are allowed, they are added as additional HTML attributes (there are a few
special exceptions, such as the Script component).
Informal parameters do have some limitations. Informal parameters that conflict with the
names of any formal parameters, or with any of the HTML attributes generated directly by
the component, are silently ommitted. The comparison is case-insensitve. Thus, for a
DirectLink component, you can not change the href attribute, even if you supply a Href (or
other variation) informal parameter.
Not all Tapestry components even allow informal parameters; this is explicitly stated in the
component specification.

Conclusion:
Since every entity of Tapestry project can be analyzed separately, it is easy to edit the code
as well as debug the errors when we create a complex web project. Tapestry components
are "black boxes" that are involved with both rendering HTML responses and responding
to HTTP requests. In this document we have learnt the fundamentals of different
parameters and components that are used in Tapestry.
[ Read More ]
Read more...

Agile Methodology of Programming in Java

Posted by Admin at 11:32 AM – 0 comments
 
What is Agile Java? 
Agile Java weaves Master Java 5.0, object-oriented design, and Test-Driven
Development (TDD) into a single coherent approach to building professional, robust
software systems. Java and Test-Driven Development integrate throughout the entire
development lifecycle; helping you leverage today’s fastest, most efficient
development techniques from the very outset.

What’s agile methodology?
One of the fundamental tenets of any agile software methodology is the importance of
communication between the various people involved in software development.
Furthermore agile methods put a large premium on improving communication
through face-to-face communication. As the agile manifesto states "The most efficient
and effective method of conveying information to and within a development team is
face-to-face conversation." Extreme Programming emphasizes this with its practice of
a single open development space where the team can work closely together.

Why Agile Methodology?
An agile software development team can add features in any order and can release a
working version of the product at any iteration. The ability to release a version of the
product at each iteration also makes the developers far better software engineers.
Issues such as integration and installation that previously were deferred to the end of a
project must now be addressed consistently throughout the entire development
lifecycle. Software built in this manner is of consistently higher quality

Why TDD?
Test-driven development (TDD) is a programming technique heavily emphasized in
Extreme Programming. Essentially the technique involves writing your tests first then
implementing the code to make them pass. The goal of TDD is to achieve rapid
feedback and implements the "illustrate the main line" approach to constructing a
program. This TDD-centered approach doesn't just lead to better code: it provides
powerful feedback that will help you learn Java far more rapidly. The use of TDD as a
learning mechanism is a landmark departure from conventional teaching techniques.

How do I Start Coding Agile java?
Agile java can be achieved by building a team that’s competent of developing
software using tools that support Extreme Programming i.e. Agile Tools .

What are agile tools?
Exactor Framework:
An Acceptance Test Framework for use in a Java based environment. A framework
for creating automated acceptance tests, this tool acts as a layer of verification on top
of unit testing, and a benchmark from which project completion can be measured.
Mainly used within an Agile environment, Exactor supports web and desktop (SWT)
applications and is easily extended to support other application. The framework is
built on top of parts of JUnit and utilises JWebUnit.


IntelliJ
A State of the Art Java Development Environment with some of the most advanced
support tools available. Built with Agile developers in mind, this IDE can actively
increase development time by minimizing the time needed for repetitive or often-
unneeded tasks, as well as utilising an extremely advanced toolset for refactoring,
Testing and Integration.

MySQL
MySQL is a full fledged Relational Database Management System.

NSIS
NSIS is a state of the art tool for creating installation scripts for Windows
applications. Using the extensive scripting language, you can not only put the
software in the right directory but also create shortcuts on the desktop, modify registry
entries and create the uninstall utility.

OpenSTA (Open System Testing Architecture)
OpenSTA is a tool for capturing usage-scenarios of web-applications and using this
scenarios for stress testing these web-applications. The test-results are displayed in
both reports and graphs. It runs on the Windows-platform. More info can be found on
http://www.opensta.org.

SAME
Same is a small java-application that gives you the ability to spot identical
lines/sections across selected files or all files in your codebase. This way it helps to
identify duplicated code.

SourceMonitor
With SourceMonitor you can easily monitor the health of your codebase by
periodically creating a snapshot of metrics of your codebase. It supports all major
languages as Java, Delphi, C#, C/C++, VisualBasic, HTML. The metrics can be
graphed over time. SourceMonitor is a Windows application.

Other Tools and IDE’s

DBUnit - Unit testing against a database
DbUnit is a JUnit extension (also usable with Ant) targeted for database driven
projects that, among other things, puts your database into a known state between test
runs. This is an excellent way to avoid the myriad of problems that can occur when
one test case corrupts the database and causes subsequent tests to fail or exacerbate
the damage. DbUnit has the ability to export and import your database data to and
from XML datasets. Since version 2.0, DbUnit can works with very large dataset
when use in streaming mode. DbUnit can also help you to verify that your database
data match expected set of values.
Further Information available at: http://dbunit.sourceforge.net/

Maven - For building, deploying, and collecting application metrics Maven is a
software project management and comprehension tool. Based on the concept of a
project object model (POM), Maven can manage a project's build, reporting and
documentation from a central piece of information.
Further Information available at: http://maven.apache.org/

JUnit - Unit testing in java
Testing is not closely integrated with development. This prevents you from measuring
the progress of development- you can't tell when something starts working or when
something stops working. Using JUnit you can cheaply and incrementally build a test
suite that will help you measure your progress, spot unintended side effects, and focus
your development efforts.
Further Information available at:
http://junit.sourceforge.net/doc/testinfected/testing.htm

StrutsTestCase - Unit testing web applications written with Struts StrutsTestCase for
JUnit is an extension of the standard JUnit TestCase class that provides facilities for
testing code based on the Struts framework. Action Servlet plays a key Role in
performing the JUnit & allows developers to test action mappings, form beans, and
forwards declarations. StrutsTestCase is compliant with the Java Servlet 2.2, 2.3, and
2.4 specifications, and supports Struts 1.2, and Cactus 1.6.1 and JUnit 3.8.1.
StrutsTestCase is no longer backwards compatible with Struts 1.0.
Further Information available at: http://strutstestcase.sourceforge.net/

Eclipse IDE - Wonderful refactoring tool.
Further Information available at:: http://www.eclipse.org/

What’s refactoring?
Refactoring (Fowler, 1999) is a technique to restructure code in a disciplined way, a
technique that is a fundamental practice of XP. The basic idea is that you make small
changes to your code, called refactorings, to support new requirements and/or to keep
your design as simple as possible. The advantage of refactoring is that it enables
programmers to safely and easily evolve their code to fulfil new requirements or to
improve its quality.

Conclusion:
The array of tools that have emerged and are emerging proves there’s a lot of work
going on Agile Java. Once these become de facto standards the development effort
will be considerably cut down and the quality of development is certainly going to
improve.
[ Read More ]
Read more...

Access Domino Database from Java Applications

Posted by Admin at 11:19 AM – 0 comments
 
There are two primary ways to Access Domino database from a Java Application. 
  1. Use Domino java APIs to connect to Domino Database over DIIOP 
  2. Install Servlets over Domino Server to accept HTTP request 
Prerequisites:-
The java program/component accessing the domino objects should be compiled with
compatible JDK/JRE version. For Domino 6.5 use jdk 1.4. Check compatibility for later
versions. For queries search on Notes.net.
The Classpath should have Notes.jar or NCSO.jar files
e.g.:-
set classpath=%classpath%;c:\lotus\domino\Notes.jar
or
set classpath=%classpath%;c:\lotus\domino\data\domino\java\NCSO.jar
depending on whether the machine hosting java component will access the domino
database locally(Machine will have lotus notes client installed) or remotely (over TCP/IP
network) using DIIOP protocol
Notes.jar, ncso.jar files supplies packages containing domino specific classes. These files
are supplied with the Domino client and server software respectively.

Code:-
The lotus.domino package has NotesFactory class which can be used to create new
domino session.
The local calls require that the NotesThread class manage threads. NotesThread extends
java.lang.Thread to include special initialization and termination code for Domino. You
have three options:
  • Execute threads through inheritance 
  • Execute threads through the Runnable interface 
  • Execute threads through the static methods 
Execute threads through inheritance
To execute threads through inheritance, extend NotesThread instead of Thread and
include a runNotes method instead of run. Start a NotesThread thread the same way as
TCS Public any other thread with the start method. This technique is easy to use and less error prone
than the static methods .

import lotus.domino.*;
public class myClass extends NotesThread { 
    public static void main(String argv[])  {  
          myClass t = new myClass();  
          t.start();  
   }  

    public void runNotes() { // entry point for Notes thread  
          try  {  
              Session s = NotesFactory.createSession();  
            // Operational code goes here  
        } catch (Exception e)  {  
                   e.printStackTrace(); 
        } 
   } 
} 


Execute threads through the Runnable interface
To execute threads through the Runnable interface, implement Runnable and include a
run method as you would for any class using threads. This technique can be used when
you cannot extend NotesThread because you're extending another class.
import lotus.domino.*;

public class myClass implements Runnable {
 public static void main(String argv[]) {
  myClass t = new myClass();
  NotesThread nt = new NotesThread((Runnable) t);
  nt.start();
 }

 public void run() {// entry point for thread 
   try { 
    Session s = NotesFactory.createSession(); 
    // Operational code goes here 
   } catch (Exception e)  { 
     e.printStackTrace(); 
   } 
 }
}

Execute threads through the static methods
To execute threads through the static methods, call sinitThread() to initialize a thread and
stermThread() to terminate the thread. Call stermThread() exactly one time for each call
to sinitThread(); putting stermThread in a "finally" block is recommended. The static
methods can be used when inheritance is not possible or when event-based threads need
fine control.

import lotus.domino.*; 
public class myClass
{
 public static void main(String argv[])
 {
  try
  {
   NotesThread.sinitThread(); // start thread
   Session s = NotesFactory.createSession();
   // Operational code goes here
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
  finally
  {
   NotesThread.stermThread(); // must terminate every thread
  }
 }
}

Each thread of an application making local calls must initialize a NotesThread object.
This includes AWT threads that access the Domino Objects. Listener threads must use
the static methods because they cannot inherit from NotesThread.
The remote calls require that the createSession signature whose first parameter is a non-
empty string makes remote calls. The first parameter identifies the computer containing
the Domino server. For example:
Session s = NotesFactory.createSession("myhost.east.acme.com")
or
Session s = NotesFactory.createSession("myhost.east.acme.com:63148")
The machine hosting the java application/ component should have NCSO.jar in the 
classpath.
for example:
set classpath := %classpath%;c:\lotus\domino\data\domino\java\NCSO.jar
The code would be similar e.g.
 
import lotus.domino.*;

public class myClass
{
 public static void main(String argv[])
 {
  try
  {
   String host = "myhost.east.acme.com:63148";
   Session s = NotesFactory.createSession(host);
   // Operational code goes here
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
 }
}
These piece of codes can be used in java application to access domino object. These
methods allow only unsecured connection.
[ Read More ]
Read more...
Newer Posts Older Posts
Subscribe to: Posts ( Atom )

List of Java Programs

  • Java Program to check Greater between the Two Number
  • Java Program to find that given number is Palindrome or not
  • Java Program to Demonstrate the Use of Pre and Post Operator
  • Java Program to Reverse the Given Number
  • Java Program to Print Number in the Given Data Type
  • Program to Demonstrate Skipping using Continue
  • Program to find whether entered character is a vowel or Consonant
  • Java Program to Calculate the Sum of Digits of Given Number
  • How to swap two numbers using only two variables
  • Checking the Given Number is Armstrong or Not
  • Average an Array of Values
  • Display ASCII Code Instead of Character
  • Comparison of Two Variable using If
  • Printing Table In java using While Loop
  • Generate Random Number Using Math.Random Function
  • To Find roots of Quadratic Equation
  • Performing Arithmetic Opration on Two Variable
  • Concatenation of Two String in Java
  • Command Line Argument in JAVA
  • Java Hello World Program
  • Calculate Circle Perimeter | Java Program
  • Calculate the Area of Circle | Java Program
  • To Find Whether Given Year is a Leap Year or not
  • Popular
  • Recent
  • Archives

Total Pageviews

Sparkline

Followers

Popular Posts of This Week

  • Count the PDF Pages using Java
    To get number of pages in the PDF import java.io.*; import com.lowagie.text.pdf.PdfReader; public class PDFSize { //static String P...
  • Barcodes Encoding Decoding Java Example
    General Overview of BarCodes and using them to encode and decode BitMatrix bitMatrix = null;// initialize bitMatrix = new PDF417Writer()....
  • To Sort an Interger Array using Shell Sort
    To Sort an Interger Array using Shell Sort class ShellSort { public static int[] shellSort(int[] array) { int N = array.length; ...
  • Sending mail through java API
    if the SMTP host is connecting, then only we can send the mails. And more over API jars are necessary public void sendEmailCommPaymentD...
  • Java Program to Print Number in the Given Data Type
    Here is Java Program to print number given in the data types public class second{ public static void main(String[] args){ int n; ...
  • Verifying in Runtime that dose the class exists within a program
    public class Main { public static boolean doesClassExist(String name) { try { Class c = Class.forName(name); i...
  • Function to Check Given Date is Older Than 900 days
    The code snippet will results in a boolean using which we can identify that given date is older than 900 days or not. /** * @param arg...
  • To Capture screen shots using Java
    import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.image.BufferedImage...
  • Send outlook meeting request using Java Mail API
    This Program is useful to send meeting request to the users using Java mail API.We need to include mail.jar in the classpath. import ja...
  • Craeting Thumnails from images
    This code sniipet will tell us how to create thumbnails from images through java code private void createThumbnail(String filename, i...
Powered by Blogger.

Archives

  • ▼  2014 ( 4 )
    • ▼  August ( 4 )
      • Java program to create a Binary Heap and Perform v...
      • Create an Adjacency matrix Graph and perform Add a...
      • To Sort an Interger Array using Shell Sort
      • Sort an Integer array with Bucket Sort
  • ►  2013 ( 6 )
    • ►  August ( 1 )
    • ►  April ( 5 )
  • ►  2012 ( 673 )
    • ►  November ( 9 )
    • ►  October ( 223 )
    • ►  September ( 272 )
    • ►  August ( 2 )
    • ►  June ( 1 )
    • ►  February ( 67 )
    • ►  January ( 99 )
 

Our Blogs

  • Linux Tutorial
  • C Programming Tutorial

Labels

  • Agile Methodology ( 1 )
  • Algorithm ( 3 )
  • AntiSamy ( 1 )
  • Arithmetic Operation ( 1 )
  • Array Example ( 9 )
  • ArrayList Examples ( 11 )
  • Average an Array of Values ( 1 )
  • Barcode Example ( 1 )
  • Basic Java Programs ( 34 )
  • Bing API Example ( 2 )
  • BitSet Example ( 1 )
  • Boolean Example ( 1 )
  • Bouncy Castle API ( 1 )
  • Break Statement ( 2 )
  • BufferedReader Example ( 2 )
  • Calendar Example ( 1 )
  • Chart Generation Example ( 1 )
  • Command Line Argument ( 1 )
  • Comparator Example ( 1 )
  • Concatenation of String ( 1 )
  • Continue Statement ( 1 )
  • Control Structure ( 1 )
  • Copy File Example ( 1 )
  • CRC Example ( 1 )
  • CSV Example ( 6 )
  • Data Structure ( 5 )
  • Date Example ( 2 )
  • Directory Example ( 1 )
  • Do - While Loop Example ( 1 )
  • Domino Database ( 1 )
  • Email Example ( 8 )
  • Encryption Example ( 3 )
  • Excel Example ( 15 )
  • Factorial Example ( 1 )
  • File Upload Example ( 1 )
  • Find Roots of Quadratic Equation ( 1 )
  • FTP Example ( 2 )
  • Graph Examples ( 1 )
  • Greater between Two Numbers ( 1 )
  • GSON Library ( 1 )
  • HashMap Example ( 1 )
  • HashSet Example ( 1 )
  • Hello World Program ( 1 )
  • If Condition ( 2 )
  • Inner Class Example ( 1 )
  • iText Example ( 3 )
  • JAR File ( 1 )
  • JAVA Applet ( 1 )
  • Java Applications ( 1 )
  • Java AWT Example ( 9 )
  • Java Certification ( 1 )
  • Java Class Examples ( 15 )
  • Java Collection Example ( 1 )
  • Java Command Example ( 4 )
  • Java Constructor Examples ( 1 )
  • Java Currency Example ( 1 )
  • Java Database Example ( 3 )
  • Java Date and Time Example ( 3 )
  • Java DateFormat Example ( 3 )
  • Java Examples ( 2 )
  • Java Exception Example ( 5 )
  • Java File Example ( 22 )
  • Java GUI Example ( 1 )
  • Java Image Examle ( 3 )
  • Java Inheritance Example ( 3 )
  • Java Input Output Example ( 1 )
  • Java IO Example ( 3 )
  • Java Jar Example ( 1 )
  • Java JSON Example ( 3 )
  • Java Mail Examples ( 4 )
  • Java Map Example ( 5 )
  • Java MapReduce Example ( 2 )
  • Java MultiThreading Example ( 7 )
  • Java Network Example ( 9 )
  • Java Package ( 1 )
  • Java Programs ( 1 )
  • Java RMI ( 1 )
  • Java Robot Class Examples ( 2 )
  • Java Runtime Example ( 1 )
  • Java Swing Example ( 9 )
  • Java Util Example ( 1 )
  • Java Vector Example ( 4 )
  • Java Voice Example ( 1 )
  • Java Webservice Example ( 1 )
  • Java XML Example ( 3 )
  • Java Zip Class Examples ( 2 )
  • JDBC ( 9 )
  • JDK Version Comparison ( 1 )
  • JFrame Example ( 3 )
  • JOptionPane Dialog Example ( 1 )
  • JPanel Example ( 1 )
  • JSP Example ( 2 )
  • JSTL Example ( 1 )
  • jUnit Example ( 2 )
  • LinkedList Example ( 2 )
  • List Example ( 1 )
  • Long Variable ( 1 )
  • Lottery Nubmer ( 1 )
  • MD5 Hashing Example ( 3 )
  • Memory Management Example ( 1 )
  • Method Override ( 1 )
  • MIDI Sound ( 8 )
  • Module Operator Example ( 2 )
  • Multiplication Table ( 1 )
  • Observer Interface Example ( 1 )
  • Operator Example ( 5 )
  • Pagination ( 1 )
  • Palindrome Number ( 1 )
  • Pass By Reference Example ( 1 )
  • Pass By Value Example ( 1 )
  • PDF File Example ( 3 )
  • PDF Generation Example ( 4 )
  • Pre and Post Operator ( 2 )
  • Prime Number ( 3 )
  • Progress Bar Example ( 1 )
  • Property List Example ( 2 )
  • Random Function ( 7 )
  • Recursion Example ( 2 )
  • Regex Example ( 2 )
  • Remote Host Example ( 2 )
  • Robot Class ( 4 )
  • Searching Example ( 3 )
  • Slideshow ( 1 )
  • Sorting Example ( 7 )
  • SpringLayout Example ( 1 )
  • Stack Example ( 4 )
  • Static Variable ( 1 )
  • StreamTokenizer Example ( 2 )
  • String Example ( 19 )
  • Struts2 Example ( 1 )
  • Sum of Digits ( 1 )
  • Swap Two Numbers ( 1 )
  • Switch Case ( 3 )
  • Tapestry Components ( 1 )
  • Thumbnail Example ( 2 )
  • TimerTask Example ( 2 )
  • To Calculate Volume ( 1 )
  • To Check Armstrong Number ( 1 )
  • Tree Example ( 1 )
  • TreeMap Example ( 1 )
  • TreeSet Example ( 1 )
  • Two Dimensional Array Example ( 1 )
  • UUID ( 1 )
  • Validation Example ( 2 )
  • Variable Casting ( 1 )
  • While Loop ( 1 )
  • XML Parsing ( 7 )
  • XSS Attacks ( 1 )
  • Zip File ( 15 )

Popular Posts

  • Creating Dynamic Macro Enabled Excel by Java
    We can create a dynamic macro enabled excel by java: We need to create a excel sheet template with macro on server. we can copy the...
  • Java program to create a Binary Heap and Perform various operation
    A binary heap (min-heap) is a complete binary tree with elements from a partially ordered set, such that the element at every node is less ...
  • To Sort an Interger Array using Shell Sort
    To Sort an Interger Array using Shell Sort class ShellSort { public static int[] shellSort(int[] array) { int N = array.length; ...
  • Implementation of a basic generic tree, with labels of type T - Data Structure
    // This implements a basic generic tree, with labels of type T, // pointer to the parent node, and a singly linked list of children nodes...
  • Create an Adjacency matrix Graph and perform Add and Remove operation
    import java.util.ArrayList; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import...
  • Printing Table In java using While Loop
    Here is a Java Program to Print the Table public class Table { public static void main(String[] args) { int no = Integer.p...
  • Merge-Sort Algorithm implementation in JAVA
    Merge-Sort Function void MergeSort(int low, int high) // a[low : high] is a global array to be sorted. // Small(P) is true if there...
  • Sort an Integer array with Bucket Sort
    Here is a java program to Sort an Integer array with Bucket Sort class BucketSort { public int[] bucketSort(int[] array) { /...
  • Stack implemented as array - Data Structure
    // Stack implemented as array public class ArrayStack<T> { private T[] stack; private int numElements = 0; // points to s...
  • Java Program to Generate the Lottery Number between 1 to 49
     A lottery requires that you select six different numbers from the integers 1 to 49. Write a program to do this for you and generate five s...
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger