Java and XML – Tutorial

1. XML Introduction

1.1. XML Overview

XML stands for Extensible Markup Language and was defined 1998 by the World Wide Web Consortium (W3C).

A XML document consists out of elements, each element has a start tag, content and an end tag. A XML document must have exactly one root element, e.g. one tag which encloses the remaining tags. XML makes a difference between capital and non-capital letters.

A XML file is required to be well-formated.

Well-formated XML must apply to the following conditions:

  • A XML document always starts with a prolog (see below for an explanation of what a prolog is)
  • Every tag has a closing tag.
  • All tags are completely nested.


A XML file is valid if it is well-formated and if it is contains a link to a XML schema and is valid according to the schema.

In general the following is considered as advantages in using XML for data processing / representation.

  • XML is Plain text
  • XML allows the data identification without any display information
  • Style can be defined via XSL
  • Easily processed due to it regular and consistent notation
  • XML files are hierarchical


1.2. XML Example

The following is a valid, well-formated XML file.


<?xml version="1.0"?>
<!-- This is a comment -->
	<name>Lars </name>
	<street> Test </street>
	<telephon number= "0123"/>


1.3. XML Elements

1.3.1. Prolog

A XML document always starts with a prolog which describes XML file. This prolog can be minimal, e.g. <?xml version=”1.0″?> or can contain other information, e.g. the encoding, e.g. <?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes” ?>

1.3.2. Empty Tag

A tag which doesn’t enclose any content is know as an “empty tag”. For example: <flag/>

1.3.3. Commends

Comments in XML are defined as: <! COMMENT>

2. Java XML Overview

Java contains several methods to access XML. The following is a short overview of the available methods.

Java provides the DOM API (Document Object Model). In DOM your access the XML document over an object tree. DOM can be used to read and write XML files.

SAX (Simple API for XML) is an Java API to sequential reading of XML files. SAX can only read XML documents. SAX provides an Event-Driven XML Processing following the Push-Parsing Model. What this model means is that in SAX, Applications will register Listeners in the form of Handlers to the Parser and will get notified through Call-back methods. Here the SAX Parser takes the control over Application thread by Pushing Events to the Application. Both DOM and Sax are older API’s and I recommend not to use them anymore.

Stax (Streaming API for XML) is an API for reading and writing XML Documents. Introduced in Java 6.0 and considered as superior to SAX and DOM.

Java Architecture for XML Binding ( JAXB ) is a Java standard that defines how Java objects are converted to/from XML (specified using a standard set of mappings. JAXB defines a programmer API for reading and writing Java objects to / from XML documents and a service provider which / from from XML documents allows the selection of the JAXB implementation JAXB applies a lot of defaults thus making reading and writing of XML via Java very easy.

The following will explain the Stax interface, for an introduction into JAXB please see JAXB tutorial.

3. Streaming API for XML (StaX)

3.1. Overview

Streaming API for XML, called StaX, is an API for reading and writing XML Documents.

StaX is a Pull-Parsing model. Application can take the control over parsing the XML documents by pulling (taking) the events from the parser.

The core StaX API falls into two categories and they are listed below. They are

  • Cursor API
  • Event Iterator API


Applications can any of these two API for parsing XML documents. The following will focus on the event iterator API as I consider it more convenient to use.

3.2. Event Iterator API

The event iterator API has two main interfaces: XMLEventReader for parsing XML and XMLEventWriter for generating XML.

3.3. XMLEventReader – Read XML Example

This example is stored in project “de.vogella.xml.stax.reader”.

Applications loop over the entire document requesting for the Next Event. The Event Iterator API is implemented on top of Cursor API.

In this example we will read the following XML document and create objects from it. file.


<?xml version="1.0" encoding="UTF-8"?>
	<item date="January 2009">
	<item date="February 2009">
	<item date="December 2009">


Define therefore the following class to store the individual entries of the XML file.


package de.vogella.xml.stax.model;

public class Item {
	private String date; 
	private String mode;
	private String unit;
	private String current;
	private String interactive;

	public String getDate() {
		return date;

	public void setDate(String date) { = date;
	public String getMode() {
		return mode;
	public void setMode(String mode) {
		this.mode = mode;
	public String getUnit() {
		return unit;
	public void setUnit(String unit) {
		this.unit = unit;
	public String getCurrent() {
		return current;
	public void setCurrent(String current) {
		this.current = current;
	public String getInteractive() {
		return interactive;
	public void setInteractive(String interactive) {
		this.interactive = interactive;

	public String toString() {
		return "Item [current=" + current + ", date=" + date + ", interactive="
				+ interactive + ", mode=" + mode + ", unit=" + unit + "]";


The following reads the XML file and creates a List of object Items from the entries in the XML file.



import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


import de.vogella.xml.stax.model.Item;

public class StaXParser {
	static final String DATE = "date";
	static final String ITEM = "item";
	static final String MODE = "mode";
	static final String UNIT = "unit";
	static final String CURRENT = "current";
	static final String INTERACTIVE = "interactive";

	@SuppressWarnings({ "unchecked", "null" })
	public List<Item> readConfig(String configFile) {
		List<Item> items = new ArrayList<Item>();
		try {
			// First create a new XMLInputFactory
			XMLInputFactory inputFactory = XMLInputFactory.newInstance();
			// Setup a new eventReader
			InputStream in = new FileInputStream(configFile);
			XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
			// Read the XML document
			Item item = null;

			while (eventReader.hasNext()) {
				XMLEvent event = eventReader.nextEvent();

				if (event.isStartElement()) {
					StartElement startElement = event.asStartElement();
					// If we have a item element we create a new item
					if (startElement.getName().getLocalPart() == (ITEM)) {
						item = new Item();
						// We read the attributes from this tag and add the date
						// attribute to our object
						Iterator<Attribute> attributes = startElement
						while (attributes.hasNext()) {
							Attribute attribute =;
							if (attribute.getName().toString().equals(DATE)) {


					if (event.isStartElement()) {
						if (event.asStartElement().getName().getLocalPart()
								.equals(MODE)) {
							event = eventReader.nextEvent();
					if (event.asStartElement().getName().getLocalPart()
							.equals(UNIT)) {
						event = eventReader.nextEvent();

					if (event.asStartElement().getName().getLocalPart()
							.equals(CURRENT)) {
						event = eventReader.nextEvent();

					if (event.asStartElement().getName().getLocalPart()
							.equals(INTERACTIVE)) {
						event = eventReader.nextEvent();
				// If we reach the end of an item element we add it to the list
				if (event.isEndElement()) {
					EndElement endElement = event.asEndElement();
					if (endElement.getName().getLocalPart() == (ITEM)) {

		} catch (FileNotFoundException e) {
		} catch (XMLStreamException e) {
		return items;



You can test the parser via the following test program. Please note that the file config.xml must exist in the Java project folder.



import java.util.List;

import de.vogella.xml.stax.model.Item;

public class TestRead {
	public static void main(String args[]) {
		StaXParser read = new StaXParser();
		List<Item> readConfig = read.readConfig("config.xml");
		for (Item item : readConfig) {


3.4. Write XML File- Example

This example is stored in project “de.vogella.xml.stax.writer”.

Lets assume you would like to write the following simple XML file.


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


StaX does not provide functionality to format the XML file automatically. So you have to add end-of-lines and tab information to your XML file.


package de.vogella.xml.stax.writer;



public class StaxWriter {
	private String configFile;

	public void setFile(String configFile) {
		this.configFile = configFile;

	public void saveConfig() throws Exception {
		// Create a XMLOutputFactory
		XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
		// Create XMLEventWriter
		XMLEventWriter eventWriter = outputFactory
				.createXMLEventWriter(new FileOutputStream(configFile));
		// Create a EventFactory
		XMLEventFactory eventFactory = XMLEventFactory.newInstance();
		XMLEvent end = eventFactory.createDTD("\n");
		// Create and write Start Tag
		StartDocument startDocument = eventFactory.createStartDocument();

		// Create config open tag
		StartElement configStartElement = eventFactory.createStartElement("",
				"", "config");
		// Write the different nodes
		createNode(eventWriter, "mode", "1");
		createNode(eventWriter, "unit", "901");
		createNode(eventWriter, "current", "0");
		createNode(eventWriter, "interactive", "0");

		eventWriter.add(eventFactory.createEndElement("", "", "config"));

	private void createNode(XMLEventWriter eventWriter, String name,
			String value) throws XMLStreamException {

		XMLEventFactory eventFactory = XMLEventFactory.newInstance();
		XMLEvent end = eventFactory.createDTD("\n");
		XMLEvent tab = eventFactory.createDTD("\t");
		// Create Start node
		StartElement sElement = eventFactory.createStartElement("", "", name);
		// Create Content
		Characters characters = eventFactory.createCharacters(value);
		// Create End node
		EndElement eElement = eventFactory.createEndElement("", "", name);




And a little test.


package de.vogella.xml.stax.writer;

public class TestWrite {

	public static void main(String[] args) {
		StaxWriter configFile = new StaxWriter();
		try {
		} catch (Exception e) {


For another (more complex example of using Stax please see Reading and creating RSS feeds via Java (with Stax)

4. XPath

4.1. Overview

XPath (XML Path Language) is a language for selecting / searching nodes from an XML document. Java 5 introduced the javax.xml.xpath package which provides a XPath library.

The following explains how to use XPath to query an XML document via Java.

4.2. Using XPath

The following explains how to use XPath. Create a new Java project called “UsingXPath”.

Create the following xml file.


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


Create a new package “myxml” and a new Java class “QueryXML”.


package myxml;


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

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class QueryXML {
	public void query() throws ParserConfigurationException, SAXException,
			IOException, XPathExpressionException {
		// Standard of reading a XML file
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder;
		Document doc = null;
		XPathExpression expr = null;
		builder = factory.newDocumentBuilder();
		doc = builder.parse("person.xml");

		// Create a XPathFactory
		XPathFactory xFactory = XPathFactory.newInstance();

		// Create a XPath object
		XPath xpath = xFactory.newXPath();

		// Compile the XPath expression
		expr = xpath.compile("//person[firstname='Lars']/lastname/text()");
		// Run the query and get a nodeset
		Object result = expr.evaluate(doc, XPathConstants.NODESET);

		// Cast the result to a DOM NodeList
		NodeList nodes = (NodeList) result;
		for (int i=0; i<nodes.getLength();i++){

		// New XPath expression to get the number of people with name lars
		expr = xpath.compile("count(//person[firstname='Lars'])");
		// Run the query and get the number of nodes
		Double number = (Double) expr.evaluate(doc, XPathConstants.NUMBER);
		System.out.println("Number of objects " +number);

		// Do we have more then 2 people with name lars?
		expr = xpath.compile("count(//person[firstname='Lars']) >2");
		// Run the query and get the number of nodes
		Boolean check = (Boolean) expr.evaluate(doc, XPathConstants.BOOLEAN);


	public static void main(String[] args) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {
		QueryXML process = new QueryXML();


5. Thank you


JavaScript Form Validation : quick and easy!

Using client side JavaScript is an efficient way to validate the user input in web forms. When there are many fields in the form, the JavaScript validation becomes too complex.

The JavaScript class presented here makes the form validations many times easier.


  1. Download the JavaScript form validation script
  2. Using the form validation script
  3. Adding a custom validation
  4. Table of Validation Descriptors
  5. Showing the form validation errors next to the element
  6. ‘Conditional’ form validations
  7. Form validation without coding!

How to add JavaScript Form Validation quickly

First, download the JavaScript form validation script here.
The zip file contains the javascript file, examples.

The script has a catalog of almost all the common validation types built-in.

The idea is to create a set of “validation descriptors” associated with each element in a form. The “validation descriptor” is nothing but a string specifying the type of validation to be performed.

Each field in the form can have zero one or more validations. For example, you can have an input field that should not be empty, should be less than 25 chars and should be alpha-numeric.

In other words, in order to validate a field, you just associate a set of validation descriptors for each input field in the form.

Just Choose Validations!
Simfatic Forms is a feature-rich web form maker.
You just have to choose the validations. More info & downloads

Using the form validation script

  1. Include gen_validatorv4.js in your html file just before closing the HEAD tag
<script src="gen_validatorv4.js" type="text/javascript"></script>
  1. Just after defining your form, create a Validator() object passing the name of the form
<form id='myform' action="">
 <!----Your input fields go here -->
<script type="text/javascript">
 var frmvalidator  = new Validator("myform");
                     //where myform is the name/id of your form
  1. Now, add the validations required
frmvalidator.addValidation("FirstName","req","Please enter your First Name");

The format of the addValidation() function is:

frmvalidator.addValidation(Field Name, Validation Descriptor, Error String);

See below for the complete list of validation descriptors. The third parameter ( Error string ) is optional.
You can add any number of validations to a field.

frmvalidator.addValidation("FirstName","req","Please enter your First Name");
                                          "Max length for FirstName is 40");


Here is a complete example:

<form action="" id="myform" >
    <label for='FirstName'>First Name:</label>
    <input type="text" id="FirstName" name="FirstName" />
    <label for='LastName'>Last Name:</label>
    <input type="text" id="LastName" name="LastName" />
    <label for='EMail'>EMail:</label>
    <input type="text" id="EMail" name="EMail" />
    <label for='Phone'>Phone:</label>
    <input type="text" id="Phone" name="Phone" />
    <label for='Address'>Address:</label>
    <textarea cols="20" rows="5" id="Address" name="Address"></textarea>
    <label for='Country'>Country:</label>
    <select id="Country"  name="Country">
        <option value="000" selected="selected">[choose yours]</option>
        <option value="008">Albania</option>
        <option value="012">Algeria</option>
        <option value="016">American Samoa</option>
        <option value="020">Andorra</option>
        <option value="024">Angola</option>
        <option value="660">Anguilla</option>
        <option value="010">Antarctica</option>
        <option value="028">Antigua And Barbuda</option>
        <option value="032">Argentina</option>
        <option value="051">Armenia</option>
        <option value="533">Aruba</option>
    <input type="submit" name="submit" value="Submit">
<script  type="text/javascript">
 var frmvalidator = new Validator("myform");
 frmvalidator.addValidation("FirstName","req","Please enter your First Name");
        "Max length for FirstName is 20");

Some Additional Notes

  • The form validators should be created only after defining the HTML form (only after the tag. )
  • Your form should have a distinguished name. If there are more than one form in the same page, you can add validators for each of them. The names of the forms and the validators should not clash.
  • You can’t use the javascript onsubmit event of the form if it you are using this validator script. It is because the validator script automatically overrides the onsubmit event. If you want to add a custom validation, see the section below

Adding a custom validation

If you want to add a custom validation, which is not provided by the validation descriptors, you can do so. Here are the steps:

  1. Create a javascript function which returns true or false depending on the validation
function DoCustomValidation()
  var frm = document.forms["myform"];
  if(frm.pwd1.value != frm.pwd2.value)
    sfm_show_error_msg('The Password and verified password does not match!',frm.pwd1);
    return false;
    return true;

sfm_show_error_msg() function displays the error message in your chosen style. The first parameter is the error message and the second parameter is the input object.

  1. Associate the validation function with the validator object.

The custom validation function will be called automatically after other validations.

If you want to do more than one custom validations, you can do all those validations in the same function.

function DoCustomValidation()
  var frm = document.forms["myform"];
  if(false == DoMyValidationOne())
    sfm_show_error_msg('Validation One Failed!');
    return false;
  if(false == DoMyValidationTwo())
    sfm_show_error_msg('Validation Two Failed!');
    return false;
    return true;

where DoMyValidationOne() and DoMyValidationTwo() are custom functions for validation.

Clear All Validations

In some dynamically programmed pages, it may be required to change the validations in the form at run time. For such cases, a function is included which clears all validations in the validator object.


This function call clears all validations you set.

Set focus on validation failure

By default, if there is a validation error, the focus is set on the input element having the error. You can disable this behavior by calling:


Table of Validation Descriptors

Validation Descriptor Usage
required or
The field should not be empty.Note that this validation if for fields like Textbox and multi-line text box. For ‘selections’ like drop down and radio group, use an appropriate validation like ‘dontselect’ or ‘selone_radio’.
maxlen=??? or
Limits the length of the input.
For example, if the maximum size permitted is 25, give the validation descriptor as “maxlen=25″
minlen=??? or
Checks the length of the entered string to the required minimum.
Example “minlen=5″
alphanumeric or
The input can contain alphabetic or numeric characters only.
(Note that space or punctuation also are not allowed since those characters are not alpha numeric)
Allows only alphabetic, numeric and space characters
Allow numbers only
Allow only alphabetic characters.
Allows alphabetic and space characters
email Validates the field to be a proper email address.
(Note, However that the validation can’t check whether the email address exists or not)
Verify the data to be less than the value passed. Valid only for numeric fields.
Example: if the value should be less than 1000 give validation description as “lt=1000″
Verify the data to be greater than the value passed. Valid only for numeric fields.
Example: if the value should be greater than 10 give validation description as “gt=10″
regexp=??? Match the input with a regular expression.
Example: “regexp=^[A-Za-z]{1,20}$” allow up to 20 alphabetic characters.
dontselect=?? This validation descriptor is valid only for drop down lists. The drop down select list boxes usually will have one item saying ‘Select One’ (and that item will be selected by default). The user should select an option other than this ‘Select One’ item.
If the valueof this default option is ’000′, the validation description should be “dontselect=000″Dropdown box with default selected

Drop down list source

dontselectchk=?? This validation descriptor is only for check boxes. The user should not select the given check box. Provide the value of the check box instead of ??
For example, dontselectchk=on
shouldselchk=?? This validation descriptor is only for check boxes. The user should select the given check box. Provide the value of the check box instead of ??
For example, shouldselchk=on
selone_radio One of the radio buttons should be selected.

Compare two input elements
eqelmnt=??? Compare two input elements. For example: password and confirm password. Replace ??? with the name of the other input element.

 "The confirmed password is not same as password");
neelmnt=??? The value should not be equal to the other input element

"The password should not be same as username");
ltelmnt=??? The input should be less than the other input. Give the name of the other input instead of ???
leelmnt=??? The input should be less than or equal to the other input. Give the name of the other input instead of ???
gtelmnt=??? The input should be greater than the other input. Give the name of the other input instead of ???
geelmnt=??? The input should be greater than or equal to the other input. Give the name of the other input instead of ???

Go to the second part of this post to learn about the advanced features of this validation script.

Javascript Lover

Fantastic JavaScript 3D Libraries

Ever imagined if the tiny JavaScript code could render amazing out of the box 3D? Then be ready to enjoy wonderful 3D effects in simple JavaScript code. These JavaScript 3D Libraries let you render smooth yet attractive 3D effects with great ease.

JS3D – The 3d Javascript Graphics Layer

JS3D is a library which allows you to have interactive 3d objects on your website, such as the spinning cube at the top of the page. The 3d effect is created using actual text, try selecting the text on the cube.

JavaScript Raytracer

The JavaScript Raytracer is a 3D rendering engine written entirely in JavaScript. It implements the raytracing algorithm to create images of mathematically defined shapes such as spheres.

3d graphics in JavaScript

Just because I do not do enough silly things with JavaScript already and a raytracer, here are some 3d graphics done with just JavaScript. You should see a TIE fighter rotating, and moving left and right.

Realtime 3D Triangles in Javascript

A wonderful real time 3d triangle generated using javascript.

Javascript Wolfenstein 3D

This a Javascript implementation of id Software 1992 game, Wolfenstein 3D. Should work in all canvas-enabled browsers, that is it means no Internet Explorer.

JavaScript-Powered Web 3D

JavaScript is the standard scripting language of Web development, and a far larger number of people know JavaScript than Java. JavaScript is easy to learn and fun to experiment with. No compiler or development environment is required. So lets learn how to create awesome 3D in JacaScript.

Incredible JavaScript and Canvas 3D demos from Japan

Mr. Satoshi Ueyama hacked out the new era of JavaScript 3D tech by unveiling the real of Google Chrome s power. Satoshi is one of the great JavaScript hackers in Japan. He has introduced the brand new JavaScript technique using Canvas for 3D on his post.

C3DL – Canvas 3D JavaScript Library

The Canvas 3D JS Libary (C3DL) is a javascript library that will make it easier to write 3D applications using canvas 3d. It will provide a set of math, scene, and 3d object classes to make the canvas more accessible for developers that want to develop 3D content in browser but do not want to have to deal in depth with the 3D math needed to make it work.

3D Javascript Chess

This is a work-in-progress 3D Javascript chess game, rendered using the canvas element and this Javascript 3D renderer. Special chess moves are not implemented yet and the interface needs a bit of work.

SVG-VML-3D Javscript Libraries

SVG-VML-3D is a free JavaScript library which can be used to draw and manipulate 3D objects in html pages by using SVG or VML. The JavaScript code which has to be typed into the html page to define the Scene (3D Objects, Viewer Position, Light.) is the same for SVG and VML.

Share and Enjoy:

  • MisterWong
  • Y!GG
  • Webnews
  • Digg
  • StumbleUpon
  • Reddit

5 Examples of when to use silence ?

1. During arguments. One of the best times to use the power of silence is during  an argument is to stay silent. The ego will be trying to force its way out of you and finish the argument but you are the controller, not the ego. When someone is shouting at you, looking for an argument or just picking on you can literally take all the power away from them and keep all your energy by simply looking at them and saying absolutely nothing. This is extremely difficult to do but very powerful.

2. Gossiping. When there is a crowd of people in the workplace there are gossipers who speak about other people. The thing with gossiping is that it is contagious. When we don’t like someone and someone else starts speaking about them we naturally tend to voice our opinion, I’ve done it lots of times and have to stop myself.

Try and stop yourself from catching the virus of gossiping and use the power of silent whenever it occurs. If you are a gossiper yourself and people around start to notice that you are ‘not your usual self’, don’t give an explanation just leave saying you’ve got work to do or whatever, pretty soon you’ll be out of the gossiping loop.

3. When someone is talking. Silence is a great tool for counselors if used in the right way. It’s also great when listening to friends and family.

Just let people talk and listen to them and use your facial expressions and movements to acknowledge that you are listening. This can be a tough thing to do but extremely powerful for both you, as the listener, and the talker.

You will find that as you practice this, more people come to talk to you as you will be known as a listener. Obviously there are times to speak during the conversation, however when you do, make sure it is to paraphrase what the talker is saying or asking questions to get more information, don’t make it about yourself.

When people want to know more about you they will ask you questions, this is the time to talk about yourself but always have the listener be part of the conversation.

4. When the house is empty. The silence of the home can be quite disturbing to some people as there is a natural need to fill the void of silence. We turn on the radio, play some music, call friends or family, or turn on the TV to fill this void. Having a completely silent home when you are alone does not mean you are alone it simply means you are recharging your mind and giving it some downtime.

Silence helps us to work through, in our minds, the events of the day or project what we want to happen during the day ahead. I am a night owl and also a morning lark. I love the silence when I know everyone is safe and tucked up in bed and I can write or work on the computer. At the weekends I go to bed with my wife to talk about days events or our plans and just have a laugh or whatever. My wife, who loves her sleep, has gone to sleep I kiss her goodnight and get up for a few hours to write as this is the time I am most inspired. I am also the first person up in the morning which means I have another 2 hours to write or work on my online projects.

I know it’s harder when you are alone, however silent time can be used to think about the life you want and work out ways to get it.

5. Quiet reflection. This is a fantastic way to connect with world in a way that is not possible when you are surrounded by hubbub noise. 15 minutes in the morning, 15 minutes in the evening simply focusing on your breath can do wonders for both mind and body. I truly believe that with practice quiet reflection can help us reach a level of deep inner calm.

The state of silence is a way of reaching another part of your mind not possible when going about your daily routine. This other part of your mind is connected in every way to the world around you and with practice you can tap into this knowledge.

How do I pass Scriptlet in JSP to JavaScript values ?

JavaScript variable =”<%=   there is your java code     %>”;

like …….

var companyId:<%=request.getParameter();%>


Conversion PDF to Byte and Vice verse

Simple conversion easily enjoy the word of JAVA……………….

public static byte[] convertPDFToByteArray(String sourcePath) {
byte[] bytes=null;
InputStream inputStream;

File file = new File(sourcePath);

try {
inputStream = new FileInputStream(file);
bytes = new byte[(int)file.length()];
int read =;
} catch (IOException ex) {

DesktopApplication3View.class.getName()).log(Level.SEVERE, null, ex);
}return bytes;


public void convertByteArrayToPDF(String sourcePath,byte[] bytes) {
OutputStream out;
try {
out = new FileOutputStream(sourcePath);
try {
} catch (IOException ex) {
Logger.getLogger(DesktopApplication3View.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(DesktopApplication3View.class.getName()).log(Level.SEVERE, null, ex);


Web Services – Web Services Tutorials

In this section of the Web Services tutorial you will be familiarized with the Web Services.


The next generation of distributed computing has arrived. A Web service is a unit of managed code that can be remotely invoked using HTTP, that is, it can be activated using HTTP requests.

Historically speaking, remote access to binary units required platform-specific and sometimes language-specific protocols. For example, DCOM clients access remote COM types using tightly coupled RPC calls. CORBA requires the use of tightly coupled protocol referred to as Internet Inter-ORB Protocol (IIOP), to activate remote types. Enterprise JavaBeans (EJBs) requires a Remote Method Invocation (RMI) Protocol and by and large a specific language (Java). Thus each of these remote invocation architectures needs proprietary protocols, which typically require a tight connection to the remote source.

One can access Web services using nothing but HTTP. Of all the protocols in existence today, HTTP is the one specific wire protocol that all platforms tend to agree on. Thus , using Web services, a Web service developer can use any language he wish and a Web service consumer can use standard HTTP to invoke methods a Web service provides. The bottom line is that we have true language and platform integration . Simple Object Access Protocol (SOAP) and XML are also two key pieces of the Web services architecture.

What is a Web Service

Web services constitute a distributed computer architecture made up of many different computers trying to communicate over the network to form one system. They consist of a set of standards that allow developers to implement distributed applications – using radically different tools provided by many different vendors – to create applications that use a combination of software modules called from systems in disparate departments or from other companies.

A Web service contains some number of classes, interfaces, enumerations and structures that provide black box functionality to remote clients. Web services typically define business objects that execute a unit of work (e.g., perform a calculation, read a data source, etc.) for the consumer and wait for the next request. Web service consumer does not necessarily need to be a browser-based client. Console-baed and Windows Forms-based clients can consume a Web service. In each case, the client indirectly interacts with the Web service through an intervening proxy. The proxy looks and feels like the real remote type and exposes the same set of methods. Under the hood, the proxy code really forwards the request to the Web service using standard HTTP or optionally SOAP messages.

Web Service Standards

Web services are registered and announced using the following services and protocols. Many of these and other standards are being worked out by the UDDI project, a group of industry leaders that is spearheading the early creation and design efforts.

Universal Description, Discovery, and Integration (UDDI) is a protocol for describing available Web services components. This standard allows businesses to register with an Internet directory that will help them advertise their services, so companies can find one another and conduct transactions over the Web. This registration and lookup task is done using XML and HTTP(S)-based mechanisms.

Simple Object Access Protocol (SOAP) is a protocol for initiating conversations with a UDDI Service. SOAP makes object access simple by allowing applications to invoke object methods or functions, residing on remote servers. A SOAP application creates a request block in XML, supplying the data needed by the remote method as well as the location of the remote object itself.

Web Service Description Language (WSDL), the proposed standard for how a Web service is described, is an XML-based service IDL (Interface Definitition Language) that defines the service interface and its implementation characteristics. WSDL is referenced by UDDI entries and describes the SOAP messages that define a particular Web service.

ebXML (e-business XML) defines core components, business processes, registry and repository, messaging services, trading partner agreements, and security.

Implementing Web Services

Here comes a brief step-by-step on how a Web service is implemented.

  • A service provider creates a Web service
  • The service provider uses WSDL to describe the service to a UDDI registry
  • The service provider registers the service in a UDDI registry and/or ebXML registry/repository.
  • Another service or consumer locates and requests the registered service by querying UDDI and/or ebXML registries.
  • The requesting service or user writes an application to bind the registered service using SOAP in the case of UDDI and/or ebXML
  • Data and messages are exchanged as XML over HTTP

Web Service Infrastructure

Even though Web services are being built using existing infrastructure, there exists a strong necessity for a number of innovative infrastructures. The core architectural foundation of Web services are XML, XML namespaces, and XML schema. UDDI, SOAP, WSDL, ebXML and security standards are being developed in parallel by different vendors

Web Services Technologies and Tools

There are a number of mechanisms for constructing Web services. Microsoft has come out with a new object-oriented language C# as the development language for Web services and .NET framework. Microsoft has an exciting tool called Visual Studio .NET in this regard. The back end database can be Microsoft SQL Server 2000 in Windows 2000 Professional.

Sun Microsystems has its own set of technologies and tools for facilitating Web services development. Java Servlets, Java Server Pages (JSPs), Enterprise JavaBeans (EJB) architecture and other Java 2 Enterprise Edition (J2EE) technologies play a very critical role in developing Web services.

There are a number of tools for developing Web services. They are Forte Java IDE, Oracle JDeveloper, and WebGain Studio.

Sun Microsystems has taken an initiative called Sun ONE (Open Network Environment) and is planning to push Java forward as a platform for Web services. It is developing Java APIs for XML-based remote procedure calls and for looking up services in XML registries – two more JAX family APIs: JAX/RPC (Java API for XML Remote Procedure Calls) and JAXR (Java API for XML Registries). These will wrap up implementations of Web services standards, such as SOAP and UDDI.

IBM also for its part has already developed a suite of early-access tools for Web services development. They are Web Services Toolkit (WSTK), WSDL Toolkit, and Web Services Development Environment (WSDE).

Apache Axis is an implementation of the SOAP (“Simple Object Access Protocol”) submission to W3C.

From the draft W3C specification:

SOAP is a lightweight protocol for exchanging structured information in a decentralized, distributed environment. It is an XML based protocol that consists of three parts: an envelope that defines a framework for describing what is in a message and how to process it, a set of encoding rules for expressing instances of application-defined datatypes, and a convention for representing remote procedure calls and responses.

Apache Axis is an Open Source SOAP server and client. SOAP is a mechanism for inter-application communication between systems written in arbitrary languages, across the Internet. SOAP usually exchanges messages over HTTP: the client POSTs a SOAP request, and receives either an HTTP success code and a SOAP response or an HTTP error code. Open Source means that you get the source, but that there is no formal support organization to help you when things go wrong.


For the last few years, XML has enabled heterogeneous computing environments to share information over the Web. It now offers a simplified means by which to share process as well. From a technical perspective, the advent of Web services is not a revolution in distributed computing. It is instead a natural evolution of XML application from structured representation of information to structured representation of inter-application messaging.

Prior to the advent of Web services, enterprise application integration (EAI) was very difficult due to differences in programming languages and middleware used within organizations. This led to the situation where interoperability was cumbersome and painful. With the arrival of Web services, any application can be integrated as long as it is Internet-enabled.

It is difficult to avoid the popularity and hype that is surrounding Web services. Each software vendor has some initiative concerning Web services and there is always great speculation about the future of the market for them. Whichever way it turns out, Web service architectures provide a very different way of thinking about software development. From client-server to n-tier systems, to distributed computing, Web service applications represent the culmination of each of these architectures in combination with the Internet.

Java Building a Simple Web Service ? A Tutorial Tutorial




this tutorial we will create a simple web service and a client web application
using eclipse IDE along with
will also deploy and test the web service on Tomcat 5.5.4 web application
server. This application, while simple, provides a good introduction to Web
service development and some of the Web development tools available.


















JDK (in D:\j2sdk1.4.2_04)


Tomcat (in E:\Tomcat5.5)


Eclipse (in E:\Eclipse3.1)


Lomboz (in E:\Eclipse3.1)


Setting up


  1. Set
    up the installed JRE in eclipse (Windows -> Preferences -> Java ->
    Installed JREs)



  1. Set
    up the installed runtime for server in eclipse (Windows -> Preferences
    -> Server -> Installed Runtimes)



  1. Set
    up the Server view in eclipse (Windows -> Show View -> Other)




  1. Set
    up the Tomcat Server by right clicking and selecting New -> Server option
    from the Server view in eclipse







Creating a Web service


  1. Create
    a new Dynamic Web Project in eclipse (File -> New -> Other)




  1. Enter
    name as ?WebServiceTutorial?, select project location as ?E:\Test?
    and select Apache Tomcat v5.5 as the Target server.




  1. Now
    create a new Java class from the Project Explorer (Dynamic Web Projects
    -> Java Source -> New -> Class)




  1. Enter
    name as ?Hello? and package as ?com.tutorial?.



  1. Add
    a simple method in the ?Hello? class as below.

public String sayHello(String name){


return “Hello ” + name;






  1. Save
    and build the project.
  2. Create
    a new Web service in eclipse (File -> New -> Other)



  1. Select
    Generate a proxy.
  2. Select
    Test the Web service.
  3. Select
    Overwrite files without warning.



  1. Select
    or enter the Bean name as ?com.tutorial.Hello?. This is the java class
    that we just now created.



  1. Continue
    the wizard by clicking Next and finish.
  2. On
    Finish, the Tomcat server starts up and launches the Test client.
  3. Verify
    the generated contents. Look for Hello.class and the generated JSPs as






  1. Verify
    the Tomcat folder and ensure the newly created web applications ?
    WebServiceTutorial, WebServiceTutorialClient.





  1. We
    can also run the following url from the browser to access/test the Web




  1. If
    servlet error ? cannot be resolved or is
    not a type? is thrown on the browser, then copy the webserviceutils.jar
    file from the E:\Eclipse3.1\eclipse\plugins\
    into the WEB-INF\lib folder of the WebServiceTutorialClient application and
    restart the Tomcat server.
  1. The
    browser displays the methods available in the web service.




  1. Click
    on the sayHello(..) method, enter your name (for e.g. ?Jeeva?) in
    the inputs section and click ?Invoke?.




  1. The
    browser greets using the web service.






  1. The
    WSDL for the Hello Web service can be found in E:\Test\WebServiceTutorial\WebContent\wsdl\Hello.wsdl.
    On double-click, the WSDL opens in a graphical editor.




  1. Right-click
    on the WSDL file and explore the options to test the web service / publish
    the WSDL file / generate client / etc.







In this
tutorial we learned how to create a simple web service and a client web
application using eclipse IDE along with
also deployed and tested the web service on Tomcat 5.5.4 web application server.
This application, while simple, provides a good introduction to Web service
development and some of the Web development tools available.

Reference #


Java PDF Generation with IText

Multi Site Keyword Extractor Tool
Analyze Keywords

First Method creates ur PDF File and Second Download your file from the relative Path in JSF

public String mypdfGeneratorAmd() {
// fileCreation();
List mylist = this.getListDfAmd();
if (mylist != null) {
Document pdf = new Document();
Date today = new Date();
ServletContext servletContext = null;
// (ServletContext)
// FacesContext.getCurrentInstance().getExternalContext().getContext();
// String logo1 = servletContext.getRealPath(“”) + “/” +
// “WebContent”
// + “/” + “reports” + “/”;

String fileName = “AssistedMaintenanceDocking.pdf”;

File f;
String fileTitle = “AssistedMaintenanceDocking ”
+ (new Date().toString());
servletContext = (ServletContext) FacesContext.getCurrentInstance()
String logo = servletContext.getRealPath(“”) + “/” + “images” + “/”
+ “user-image.jpg”;

int rowCount = mylist.size();
PdfPTable t = new PdfPTable(5);
Paragraph title1 = new Paragraph();
try {
Image img = Image.getInstance(logo);
String mypdfFile = servletContext.getRealPath(“”) + “/”
+ “reports” + “/” + “DefectAndHistory.pdf”;
f = new File(mypdfFile);
// “/home/shussain/workspace2/DNRMS-PMSA/WebContent/reports/”+
// “AssistedMaintenanceDocking.pdf”);
if (!f.exists()) {
try {
.println(“New file ‘AssistedMaintenanceDocking.pdf’ has been created to the current directory”);
} catch (IOException e) {
// TODO Auto-generated catch block
} else {
.println(“File ‘AssistedMaintenanceDocking.pdf’ Already in the current directory”);
PdfWriter.getInstance(pdf, new FileOutputStream(f));
pdf.setMargins((float) 1.5, (float) 1.5, 30, 30);
pdf.addSubject(“Assisted Maintenance Docking”);;

title1.add(new Paragraph(“Assisted Maintenance Docking” + “\n”
+ (new Date().toString()), FontFactory.getFont(
FontFactory.HELVETICA, 20, Font.BOLD,
new Color(0, 0, 0))));
Chapter chapter1 = new Chapter(title1, 1);

addEmptyLine(title1, 2);
Phrase phraseOfImage = new Phrase();
phraseOfImage.add(new Chunk(img, 18, -18));


Phrase phrase1 = null;

float[] columnWidths = { 200, 200, 200, 200, 200 };

PdfPCell c1 = new PdfPCell(new Phrase(“Ship/Unit”,
FontFactory.getFont(FontFactory.HELVETICA, 12,
Font.BOLD, Color.BLACK)));


c1 = new PdfPCell(new Phrase(“Last AMD”, FontFactory.getFont(
FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK)));

c1 = new PdfPCell(new Phrase(“AMD Plan”, FontFactory.getFont(
FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK)));

c1 = new PdfPCell(new Phrase(“Duration”, FontFactory.getFont(
FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK)));

c1 = new PdfPCell(new Phrase(“Package”, FontFactory.getFont(
FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK)));


for (int i = 0; i < rowCount; i++) {

dfamd = (DfAmd) mylist.get(i);




// section1.add(t);


} catch (DocumentException e) {
} catch (IOException ex) {
try {
} catch (IOException e) {
// TODO Auto-generated catch block
} else {
msging = new FacesMessage(FacesMessage.SEVERITY_WARN, "Error",
"Your Report Is Empty Please Search Some Data");
// msging ="Your Report Is Empty Please Search Some Data";

FacesContext.getCurrentInstance().addMessage(null, msging);
return "success";

// put new line after specific Element
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i 0) {
output.write(buffer, 0, length);

// Finalize task.
} finally {
// Gently close streams.


private static void close(Closeable resource) {
if (resource != null) {
try {
} catch (IOException e) {