Posts Tagged ‘webseo.com.au’

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 -->
<address>
	<name>Lars </name>
	<street> Test </street>
	<telephon number= "0123"/>
</address>

 

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"?>
<config>
	<item date="January 2009">
		<mode>1</mode>
		<unit>900</unit>
		<current>1</current>
		<interactive>1</interactive>
	</item>
	<item date="February 2009">
		<mode>2</mode>
		<unit>400</unit>
		<current>2</current>
		<interactive>5</interactive>
	</item>
	<item date="December 2009">
		<mode>9</mode>
		<unit>5</unit>
		<current>100</current>
		<interactive>3</interactive>
	</item>
</config>

 

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) {
		this.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;
	}

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

 

				
package de.vogella.xml.stax.read;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

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
								.getAttributes();
						while (attributes.hasNext()) {
							Attribute attribute = attributes.next();
							if (attribute.getName().toString().equals(DATE)) {
								item.setDate(attribute.getValue());
							}

						}
					}

					if (event.isStartElement()) {
						if (event.asStartElement().getName().getLocalPart()
								.equals(MODE)) {
							event = eventReader.nextEvent();
							item.setMode(event.asCharacters().getData());
							continue;
						}
					}
					if (event.asStartElement().getName().getLocalPart()
							.equals(UNIT)) {
						event = eventReader.nextEvent();
						item.setUnit(event.asCharacters().getData());
						continue;
					}

					if (event.asStartElement().getName().getLocalPart()
							.equals(CURRENT)) {
						event = eventReader.nextEvent();
						item.setCurrent(event.asCharacters().getData());
						continue;
					}

					if (event.asStartElement().getName().getLocalPart()
							.equals(INTERACTIVE)) {
						event = eventReader.nextEvent();
						item.setInteractive(event.asCharacters().getData());
						continue;
					}
				}
				// 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)) {
						items.add(item);
					}
				}

			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (XMLStreamException e) {
			e.printStackTrace();
		}
		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.

 

				
package de.vogella.xml.stax.read;

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) {
			System.out.println(item);
		}
	}
}

 

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"?>
<config>
	<mode>1</mode>
	<unit>900</unit>
	<current>1</current>
	<interactive>1</interactive>
</config>

 

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;

import java.io.FileOutputStream;

import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

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();
		eventWriter.add(startDocument);

		// Create config open tag
		StartElement configStartElement = eventFactory.createStartElement("",
				"", "config");
		eventWriter.add(configStartElement);
		eventWriter.add(end);
		// 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"));
		eventWriter.add(end);
		eventWriter.add(eventFactory.createEndDocument());
		eventWriter.close();
	}

	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);
		eventWriter.add(tab);
		eventWriter.add(sElement);
		// Create Content
		Characters characters = eventFactory.createCharacters(value);
		eventWriter.add(characters);
		// Create End node
		EndElement eElement = eventFactory.createEndElement("", "", name);
		eventWriter.add(eElement);
		eventWriter.add(end);

	}

}

 

And a little test.

 

				
package de.vogella.xml.stax.writer;

public class TestWrite {

	public static void main(String[] args) {
		StaxWriter configFile = new StaxWriter();
		configFile.setFile("config2.xml");
		try {
			configFile.saveConfig();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

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"?>
<people>
	<person>
		<firstname>Lars</firstname>
		<lastname>Vogel</lastname>
		<city>Heidelberg</city>
	</person>
	<person>
		<firstname>Jim</firstname>
		<lastname>Knopf</lastname>
		<city>Heidelberg</city>
	</person>
	<person>
		<firstname>Lars</firstname>
		<lastname>Strangelastname</lastname>
		<city>London</city>
	</person>
	<person>
		<firstname>Landerman</firstname>
		<lastname>Petrelli</lastname>
		<city>Somewhere</city>
	</person>
	<person>
		<firstname>Lars</firstname>
		<lastname>Tim</lastname>
		<city>SomewhereElse</city>
	</person>
</people>

 

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

 

				
package myxml;

import java.io.IOException;

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();
		factory.setNamespaceAware(true);
		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++){
			System.out.println(nodes.item(i).getNodeValue());
		}

		// 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);
		System.out.println(check);

	}

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

 

5. Thank you

 

  

import java.sql.CallableStatement;

import java.sql.Connection;

import java.sql.DriverManager;

public class Main {

  public static void main(String[] argsthrows Exception {

    Connection conn = getOracleConnection();

    // Step-2: identify the stored procedure

    String proc3StoredProcedure = “{ call proc3(?, ?, ?) }”;

    // Step-3: prepare the callable statement

    CallableStatement cs = conn.prepareCall(proc3StoredProcedure);

    // Step-4: set input parameters …

    // first input argument

    cs.setString(1“abcd”);

    // third input argument

    cs.setInt(310);

    // Step-5: register output parameters …

    cs.registerOutParameter(2, java.sql.Types.VARCHAR);

    cs.registerOutParameter(3, java.sql.Types.INTEGER);

    // Step-6: execute the stored procedures: proc3

    cs.execute();

    // Step-7: extract the output parameters

    // get parameter 2 as output

    String param2 = cs.getString(2);

    // get parameter 3 as output

    int param3 = cs.getInt(3);

    System.out.println(“param2=” + param2);

    System.out.println(“param3=” + param3);

    conn.close();

  }

  private static Connection getHSQLConnection() throws Exception {

    Class.forName(“org.hsqldb.jdbcDriver”);

    System.out.println(“Driver Loaded.”);

    String url = “jdbc:hsqldb:data/tutorial”;

    return DriverManager.getConnection(url, “sa”“”);

  }

  public static Connection getMySqlConnection() throws Exception {

    String driver = “org.gjt.mm.mysql.Driver”;

    String url = “jdbc:mysql://localhost/demo2s”;

    String username = “oost”;

    String password = “oost”;

    Class.forName(driver);

    Connection conn = DriverManager.getConnection(url, username, password);

    return conn;

  }

  public static Connection getOracleConnection() throws Exception {

    String driver = “oracle.jdbc.driver.OracleDriver”;

    String url = “jdbc:oracle:thin:@localhost:1521:caspian”;

    String username = “mp”;

    String password = “mp2”;

    Class.forName(driver)// load Oracle driver

    Connection conn = DriverManager.getConnection(url, username, password);

    return conn;

  }

}

           

         

    

  

CallStoresProcedureInOracleAndPassInOutParameters.zip( 3,849 k)

In The Line of Fire [Kala Bagh Exclusive] Dawn News 12th Jan 2012

Posted: January 13, 2012 in Random Posts
Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

In The Line of Fire [Kala Bagh Exclusive] Dawn News 12th Jan 2012

Conversion PDF to Byte and Vice verse

Posted: January 13, 2012 in Random Posts
Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

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 = inputStream.read(bytes);
} catch (IOException ex) {
Logger.getLogger(

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 {
out.write(bytes);
out.close();
} 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

Posted: January 12, 2012 in Random Posts
Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

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

Introduction

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.

Conclusion

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.

Creating webservices in NetBeans.

In this example program I will show you how you can make webservices in the Netbeans IDE. NetBeans IDE provides necessary GUI Tool to help the developers to quickly develop and deploy web services.

In this example we will

a) Develop webservices

b) Test the webservice

c) Develop client and call the webservice there

d) Finally deploy and test the application

Web Service can be added in a Web project or in Ejb project. Netbeans IDE helps the developers to easily develop and test the webservices.
It’s easy to make the Web Service program in Netbeans, which has Glassfish server by default.

Web Service program in Web Project

In Netbeans take new web project in figure 1

Web Services Example

Figure 1

Give project name webservice1 as shown in figure 2

Web Services Example

Figure 2

Select the server name in figure 3

Web Services Example

Figure 3

Now Rt Click on the Web Service project in figure 4

Select New->WebService

Web Services Example

Figure 4

Now give the name of the Web Service and package name figure 5

Web Services Example

Figure 5

Now In design view of Web Service click on Add Operation in figure 6

Web Services Example

Figure 6

Here give the operation name and parameter name and type as shown in figure 7

Web Services Example

Figure 7

Now in source view change the return null to return “hello ”+name as in figure 8

Web Services Example

Figure 8

Now Rt Click on the project and deploy it on the server as in figure 9

Web Services Example

Figure 9

It will deploy the war file on to the server

Now test the web service program

Rt click on the MyWebService in web services folder and select Test Web Operation as in figure 10

Web Services Example

Figure 10

It will open the Web Service program in browser as in figure 11

Web Services Example

Figure 11

Click on WSDL File in blue color .It will open the WSDL file in the browser as in figure 12

Web Services Example

Figure 12

Now as in fig type the roseindia in the text field and click on show button as in figure 13

Web Services Example

Figure 13

It will return hello roseindia

It also give the SOAP request and SOAP response pf the Web Service as in figure 14

Web Services Example

Figure 14

Now make the client file.Client file can be java servlet , jsp and standalone java file

Start a new web project as in figure 15.

Give project name as Webservice1-client

Web Services Example

Now Rt. Click on the project select NewàWeb Service client

Here now select the WSDL file of the Web Service as in figure 15

Click on the Browse.

Web Services Example

Now select the webservice1àMyWebService

Web Services Example

Figure 15

It creates the Client environments for the Web Service in the given project

Now make a Client file by just taking a new Jsp file as in figure 16

Web Services Example

Figure 16

Give the file name as client.jsp

Rt click in client.jsp file code and select Web Service Client resources –>Call Web Service Operation in figure 17

Web Services Example

Figure 17

Select the web service project ->web service file->web service port->operation name as in figure 18

Web Services Example

Figure 18

Change the name =”null” to name=”roseindia” as in figure 19

Web Services Example

Figure 19

Rt click in client.jsp and select run client.jsp

Web Services Example

Download Code

·

Introduction

 

In
this tutorial we will create a simple web service and a client web application
using eclipse IDE along with
Lomboz
plug
in.
We
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.

 

·
Environment

 

J2SDK
1.4.2

http://java.sun.com/

 

Eclipse
3.1

 

http://www.eclipse.org/

 

 

Tomcat
5.5.4

 

http://tomcat.apache.org/

 

 

Lomboz
3.1RC2

http://lomboz.objectweb.org/

 

 

 

·
Installation

 

Install
JDK (in D:\j2sdk1.4.2_04)

 

Install
Tomcat (in E:\Tomcat5.5)

 

Install
Eclipse (in E:\Eclipse3.1)

 

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

 

 

 

 

 

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

http://localhost:8080/WebServiceTutorialClient/sampleHelloProxy/TestClient.jsp

 

 

  1. If
    servlet error ?org.eclipse.jst.ws.util.JspUtils 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\org.eclipse.jst.ws.consumption_0.7.0
    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.
     

 

 

 

 

·
Conclusion

 

In this
tutorial we learned how to create a simple web service and a client web
application using eclipse IDE along with
Lomboz
plug
in.
We
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 # http://www.roseindia.net/webservices/buildingsimplewebservice.shtml