Showing posts with label JAX-WS. Show all posts
Showing posts with label JAX-WS. Show all posts

About Java Web Services with Axis and JAX-RPC in Eclipse




Follow the steps for creating he simple Axis and JAX-RPC, Service and Client code with Examples:

Step 1. List of software required for this application if not found in your system, install it:

Step 2. Extract the xml-axis-rc1-bin.zip into your local system

  • Navigate till \xml-axis-rc1-bin\axis-1_0\webapps and copy the axis folder

Step 3. Pest the axis folder (Already copy in above step) into Tomcate x.x \webapps

Step 4. Restart your Tomcate x.x

Step 5. Open the browser and type the http://localhost:port/axis

Note: if tools.jar file is not there in xml-axis-rc1-bin\axis-1_0\webapps\axis\WEB-INF\lib then copy from \jdk1.6.0_26\lib.

Now environment is configured on and off, need service & client code.

Step 6. Server Side Code

//File name : TestServerSideCode.jws save the file ext with jws insteed of java
public class TestServerSideCode{
public String testServerSideCode()
{
return "Working";
}
}

Step 7. Save TestServerSideCode.jws file into \Tomcat x.x\webapps\axis folder

Step 8. Restart the Tomcate x.x

Open the browser and invoke the http://localhost:port/axis/TestServerSideCode.jws?wsdl

Step 9. Client Side code with Dynamic Invocation Interface (DII)

TestClientSideCode.java

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import javax.xml.namespace.QName;

public class TestClientSideCode
{
public static void main(String [] args) {
try {
String endPointURL = "http://localhost:8090/axis/TestServerSideCode.jws";

Service service = new Service();
Call call = (Call) service.createCall();
call.setOperationName(new QName("http://localhost:8090/axis/TestServerSideCode.jws?wsdl", "testServerSideCode"));
call.setTargetEndpointAddress( new java.net.URL(endPointURL) );

String response = (String) call.invoke( new Object[] {} );

System.out.println(" Test data " + response);
} catch (Exception e) {
System.err.println("Exception: " + e);
}
}
}


Step 10. Save the TestClientSideCode.java in your local drive e.g C:\Blogs\AxisWithJAXRPC

Step 11. Open the cmd prompt, type cd then C:\Blogs\AxisWithJAXRPC

Step 12. Copy and pest the below command in command prompt with above steps

set AXIS_HOME=C:\Blogs\xml-axis-rc1-bin\axis-1_0

set CLASSPATH=.;%AXIS_HOME%\lib\axis.jar;%AXIS_HOME%\lib\axis-ant.jar;%AXIS_HOME%\lib\commons-discovery.jar;%AXIS_HOME%\lib\commons-logging.jar;%AXIS_HOME%\lib\jaxrpc.jar;%AXIS_HOME%\lib\saaj.jar;%AXIS_HOME%\lib\wsdl4j.jar;%AXIS_HOME%\lib\log4j-1.2.4.jar

Note: Change the location of xml-axis-rc1-bin\axis-1_0 in your system

Step 13. Compile the TestClientSideCode.java file with C:\Blogs\AxisWithJAXRPC>javac TestClientSideCode.java

Step 14. Run the same C:\Blogs\AxisWithJAXRPC>java TestClientSideCode

You will get out put as Test data Working



Done form my end, must try and do at your end and do let me know if any concerns.

Happy learning and implementation!!!

About JAX-WS (Java API for XML Web Service) as Web Archive WAR in Eclipse deployed on Tomcat

This tutorial, we will discussed more about, JAX-WS (Java API for XML Web Service) as Web Archive WAR in Eclipse deployed on Tomcat.

Software/Hardware requirement:
Eclips
Java 1.6+
Tomcat 6+

Create Dynamic web project in eclipse
Open the eclips from desktop or from existing dire.

Click on the File > New > Dynamic Web Project > Next.
Enter the Project name: jaxwsprj
Click Next > Click Next > Finish
Let be context root and content directory as it is default or change as per your convenient.

Create Web Service Interface

Right click on the src folder located under Java Resources > Next > New > class

Enter the name: GreetingWebService
Package: com.vinod.webservicejaxws

Click on the Finish

GreetingWebService.java

package com.vinod.webservicejaxws;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

/**
* @author Vinod Kumar
* Web Service endpoint interface
*/

@WebService
@SOAPBinding(style = Style.RPC)
public interface GreetingWebService{

/**
* sayWelcome with parameter as string
*/
@WebMethod String sayWelcome(String sName);
}



Create Web Service Implementation
Right click on the src folder located under Java Resources > Next > New > class
Enter the name: GreetingWebServiceImpl
Package: com.vinod.webservicejaxws

Click on the Finish

package com.vinod.webservicejaxws;

import javax.jws.WebService;

import com.vinod.webservicejaxws.GreetingWebService;

/**
*
* @author Vinod Kumar
* This is service implementation class
*/

@WebService(endpointInterface = "com.vinod.webservicejaxws.GreetingWebService")
public class GreetingWebServiceImpl implements GreetingWebService {

@Override
public String sayWelcome(String sName) {
return "Welcome " + sName + " !";
}
}


Add the sun-jaxws.xml

Right click on the WEB-INF folder located under WebContent > File
name of file: sun-jaxws.xml
This is for supporting the jax ws compilation.

< ?xml version="1.0" encoding="UTF-8"?>
< endpoints xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
version="2.0">
<endpoint name="GreetingWebService" implementation="com.vinod.webservicejaxws.impl"
url-pattern="/GreetingWebService" />

< /endpoints>

Modify the web.xml

Just modify the web.xml file as mention bellow:

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

< web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>jaxwsprj</display-name>

<listener>
<listener-class>
com.sun.xml.ws.transport.http.servlet.WSServletContextListener
</listener-class>
</listener>
<servlet>
<servlet-name>GreetingWebService</servlet-name>
<servlet-class>
com.sun.xml.ws.transport.http.servlet.WSServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GreetingWebService</servlet-name>
<url-pattern>/GreetingWebService</url-pattern>
</servlet-mapping>
< /web-app>

Download the jax-ws dependent jars

Copy these jar in /tomcat/lib from http://jax-ws.java.net/

Export the WAR in Tomcat
Right click on the jaxwsprj project > Export > War file


About JAX-WS Java API for XML Web Service as Web Archive WAR on Tomcat, Example, Sample, Tutorial, Step by Step, Eclipse, Tomcat and Code


Start the tomcat from /tomcate/bin/startup.bat

Verify the service
Open the any browser and enter the URL
http://localhost:8080/jaxwsprj/GreetingWebService

Note: Where as tomcat port is running on 8080



Click on link, wsdl will display as below:

< definitions
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy"
xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://webservicejaxws.vinod.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://webservicejaxws.vinod.com/"
name="GreetingWebServiceImplService">
<types />
<message name="sayWelcome">
<part name="arg0" type="xsd:string" />
</message>
<message name="sayWelcomeResponse">
<part name="return" type="xsd:string" />
</message>
<portType name="GreetingWebService">
<operation name="sayWelcome">
<input
wsam:Action="http://webservicejaxws.vinod.com/GreetingWebService/sayWelcomeRequest"
message="tns:sayWelcome" />
<output
wsam:Action="http://webservicejaxws.vinod.com/GreetingWebService/sayWelcomeResponse"
message="tns:sayWelcomeResponse" />
</operation>
</portType>
<binding name="GreetingWebServiceImplPortBinding" type="tns:GreetingWebService">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http"
style="rpc" />
<operation name="sayWelcome">
<soap:operation soapAction="" />
<input>
<soap:body use="literal" namespace="http://webservicejaxws.vinod.com/" />
</input>
<output>
<soap:body use="literal" namespace="http://webservicejaxws.vinod.com/" />
</output>
</operation>
</binding>
<service name="GreetingWebServiceImplService">
<port name="GreetingWebServiceImplPort" binding="tns:GreetingWebServiceImplPortBinding">
<soap:address location="http://localhost:8080/jaxwsprj/GreetingWebService" />
</port>
</service>
< /definitions>

Finishing Word:
Thanks! Put your input if any. Like and share it, if my work looks good.
Happy learning and implementation.

About Simple Object Access Protocol (SOAP)

Simple Object Access Protocol (SOAP) means various things to different people:
• It's a wire protocol.
• It's an RPC mechanism.
• It's an interoperability standard.
• It's a document exchange protocol.
• It's a universal business-to-business communications language.
• SimpleObject Access Protocol – http://www.w3c.org/TR/SOAP/
• A lightweight protocol for exchange of information in a decentralized, distributed environment.
• Two different styles to use: – to encapsulate RPC calls using the extensibility and flexibility
of XML. – to deliver a whole document without any method calls encapsulated




XML messaging using SOAP

About Simple Object Access Protocol (SOAP), SOAP Request Envelope, SOAP Response Envelope, SOAP Structure, Adding Header, SOAP Headers, SOAP Body, SOAP RPC Example, Sample, Basic, Code, Tutorials and Examples.
Add caption


SOAP specification

• The SOAP specification describes four major components: Formatting conventions for encapsulating data. Ex: SOAP envelope, header, body etc., Routing directions in the form of an envelope, a transport or protocol binding, Ex: SOAP sender , receiver etc., Encoding rules An RPC mechanism
• The envelope defines a convention for describing the contents of a message, which in turn has implications on how it gets processed.
• A protocol binding provides a generic mechanism for sending a SOAP envelope via a lower level protocol such as HTTP.
• Encoding rules provide a convention for mapping various application data types into an XML tag-based representation.
• Finally, the RPC mechanism provides a way to represent remote procedure calls and their return values.


SOAP Message Structure

About Simple Object Access Protocol (SOAP), SOAP Request Envelope, SOAP Response Envelope, SOAP Structure, Adding Header, SOAP Headers, SOAP Body, SOAP RPC Example, Sample, Basic, Code, Tutorials and Examples.

Block structure of a SOAP envelope

Block structure of a SOAP envelope

SOAP Request Envelope:
< soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://emp" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<q0:getName>
<q0:sName>Vinod Kumar</q0:sName>
</q0:getName>
</soapenv:Body>
< /soapenv:Envelope>

SOAP Response Envelope:
< soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<getNameResponse xmlns="http://emp">
<getNameReturn>Welcome Vinod Kumar</getNameReturn>
</getNameResponse>
</soapenv:Body>
< /soapenv:Envelope>

SOAP Structure
• A SOAP message is contained in an envelop.
• The envelop element in turn contain (in order)
– An optional header with one or more child entries.
– A body element that can contain one or more child entries.
These child entries may contain arbitrary XML data.

Adding Header
< SOAP-ENV:Header>
<jaws:MessageHeader xmlns:jaws="urn:training-samples">
<From>Me</From>
<To>You</To>
<MessageId>9999</MessageId>
</jaws:MessageHeader>
< /SOAP-ENV:Header>

SOAP Headers
• Headers are really just extension points where you can include elements from other namespaces.
– i.e., headers can contain arbitrary XML.
• Header entries may optionally have a “mustUnderstand” attribute.
– mustUnderstand=1 means the message recipient must process the header element.
– If mustUnderstand=0 or is missing, the header element is optional.

SOAP Body
Body entries are really just placeholders for arbitrary XML from some other namespace.
• The body contains the XML message that you are transmitting.
• The message format is not specified by SOAP.
– The <Body></Body> tag contains actual XML message.
– The recipient decides what to do with the message.
e.g:-
<soapenv:Body>
<getNameResponse xmlns="http://emp">
<getNameReturn>Welcome Vinod Kumar</getNameReturn>
</getNameResponse>
</soapenv:Body>

SOAP RPC Example
A simple example
– Calls with a string public String hello(String name)
– Returns a greeting “Hi!” + name

SOAP RPC Example


Reference:
wiki-SOAP 

About Web Services Definition Language (WSDL)


Web Services Definition Language (WSDL):

• WSDL-Service Description:
Service Description carries information about the service such as the input or output parameter, the location of the service, port type, binding information, and so on.
• Web Services Definition Language
– http://www.w3.org/TR/wsdl/
• An XML-based language for describing Web Services
– what the service does (description)
– how to use it (method signatures)
– where to find the service
• It does not depend on the underlying protocol
• WSDL is an XML grammar for describing a web service as a collection of access endpoints.
• Capable of exchanging messages in a procedure or document-oriented fashion.
• A WSDL document is a recipe used to automate the details involved in application-to-application communication.

About Web Services Definition Language (WSDL), Types, Message, Operation, Port Type, Binding, Port, Service, Tutorials and Examples.

Anatomy of a WSDL Document
The following code shows the major elements that may appear in a WSDL document.
An asterisk (*) next to an element indicates that more than one of these elements may appear.
< definitions>
<import>*<types><schema></schema>*</types>
<message>*<part></part>*</message>
<PortType>*
<operation>*<input></input><output></output><fault></fault>*
</operation>
</PortType>
<binding>*<operation>*<input></input><output></output>
</operation>
</binding>
<service>*<port></port>*</service>
< /definitions >


WSDL Elements
• Types – will give namespace and schema location.
• Message - Request/response messages.
• Operation - Name of operation.
• Port Type – Actual WebService.
• Binding – Binds on particular port.
• Port - URL of WS on which it is running.
• Service – web Service.

<definitions> Element
The <definitions> element in a WSDL document acts as a
container for the service description.
It provides a place to do global declarations of namespaces
that are intended to be visible throughout the rest of the
document.

< definitions targetNamespace="urn:3950" xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/ “ xmlns:tns="urn:3950">

<import> Element
The <import> element serves a purpose similar to the #include directive in the C/C++ programming language.After the <definitions> element, we see an <import> element:

< definitions targetNamespace="urn:3950" xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/“ xmlns:tns="urn:3950">
< import namespace="http://asf.gils.net/xer" location="http://asf.gils.net/xer/ez.xsd"/>

<types> Element
• The <types> element in a WSDL document acts as a container for defining the data types used in <message> elements.
• <message> elements define the format of messages interchanged between a client and a web service.
• The <types> element has zero or more <schema> sub elements.

<message> Element
• The <message> element is used to model the data exchanged as part of a web service.
• <message> elements reference the types defined in the <types> section.
• A message consists of one or more <part> subelements.
• A <part> subelement identifies the individual pieces of data that are part of this data message and the datatypes that the pieces adhere to.

<portType> Element
• The <portType> element specifies a subset of operations supported for an endpoint of a web service.
• In a sense, a <portType> element provides a unique identifier to a group of actions that can be executed at a single endpoint

<binding> Element
A <binding> element is a concrete protocol and data format specification for a <portType>element.
It is where you would use one of the standard binding extensions-HTTP, SOAP, or MIME-or create one of your own.

<service> Element
The <service> element typically appears at the end of a WSDL document and identifies a web service.

< ?xml version="1.0" encoding="UTF-8"?>
< wsdl:definitions targetNamespace="http://emp" mlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:impl="http://emp" xmlns:intf="http://emp" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
< !--WSDL created by Apache Axis version: 1.4 Built on Apr 22, 2006 (06:55:48 PDT)-->

<wsdl:types>
<schema elementFormDefault="qualified" targetNamespace="http://emp" xmlns="http://www.w3.org/2001/XMLSchema">
<element name="getName">
<complexType>
<sequence>
<element name="sName" type="xsd:string"/>
</sequence>
</complexType>
</element>
<element name="getNameResponse">
<complexType>
<sequence>
<element name="getNameReturn" type="xsd:string"/>
</sequence>
</complexType>
</element> </schema> </wsdl:types>

<wsdl:message name="getNameResponse">
<wsdl:part element="impl:getNameResponse" name="parameters"/>
</wsdl:message>
<wsdl:message name="getNameRequest">
<wsdl:part element="impl:getName" name="parameters"/>
</wsdl:message>
<wsdl:portType name="employee">
<wsdl:operation name="getName">
<wsdl:input message="impl:getNameRequest" name="getNameRequest"/>
<wsdl:output message="impl:getNameResponse" name="getNameResponse"/>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="employeeSoapBinding" type="impl:employee">
<wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="getName">
<wsdlsoap:operation soapAction=""/>
<wsdl:input name="getNameRequest">
<wsdlsoap:body use="literal"/>
</wsdl:input>
<wsdl:output name="getNameResponse">
<wsdlsoap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="employeeService">
<wsdl:port binding="impl:employeeSoapBinding" name="employee">
<wsdlsoap:address location="http://localhost:8080/employee/services/employee"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>

Web Service Request/ Response

Web-Services-Definition-Language-WSDL



About Service Oriented Architecture (SOA)


• SOA is not a solution, it is a practice.
• At a high level, SOA is formed out of three core components:
• Service Provider (Service)
• Service Consumer (Consumer)
• Services Directory (enabled by Broker)



• The service provider offers business processes in the form of services.
• The services offered by the provider are called by the consumer to achieve certain sets of business goals.
• The process of services being provided and consumed is achieved by using directory services that lie between the provider and the consumer, in the form of broker.



Objective of using SOA

Loose coupling: The business process being decomposed into independent services will help in bringing down the ependencies on a single process. This in turn will help in faster processing time.
Platform-neutrality: XML-based message information flow enhances the capability to achieve platform neutrality. These XML messages are based on agreed XML schema, eliminating the need to set up other messaging standards that can differ across platforms
Standards: The message flow across the enterprise is in the form of globally accepted standards. The service only has to depend on the service descriptions without worrying about the target standards and removing the dependencies.
Re-usability: The business logic being divided into smaller logical units, the services can easily be re-used. These enhance the utilization of SOA-based solution, which has a cascading affect on service delivery and execution.
Scalability: Again, as the business processes are decomposed into smaller units, adding new business logic is easy to accomplish. The new logic could either be added as an extended unit of the current service, or it can also be constructed as a new service.
Top-down: In a top-down approach, the business use cases are created, which gives the specifications for the creation of services. This would ensure that the functional units are decomposed into smaller processes and then developed.
Bottom-up: Using the bottom-up approach, the current systems within the organization are studied, and suitable business processes are identified for conversion to services.
The Service provider: The provider comes into action when the service is invoked. Once the service is invoked, the provider will execute the business logic. Messaging will depend upon the business logic, in case the consumer expects a message after the execution of business process, the provider will send out the reply.
The Service Consumer: The consumer would send out a message to the provider in order to access the service. This is the requester. It would either be done directly by a service-to-service call or through the directory services. Services required for processing are identified by their service descriptions.
The same service can act as the provider as well as the requester of the service. But this is seldom seen in practice.

The Service Handler: The service handler acts as a collaboration agent between the provider and the consumer. The handler contains the realization logic, which will search the appropriate service provided and bind it to the consumer request.

end of service oriented architecture SOA.

Response your input. Happy learning and Implementation if service oriented architecture SOA.

About Web Services (SOA)


Introduction to Web Services Technology

About Web Services, XML-based, Loosely coupled, Supports Remote Procedure Calls (RPCs), Ability to be synchronous or asynchronous,  Supports document exchange, Interoperable, Economical, Automatic, Accessible, Available and Scalable.


What is Web Services

Programming language and platform independent infrastructure for loosely-coupled, app2app communication over the Internet(Globe). 
or
A web service is a piece of business logic, located somewhere on the Internet, that is accessible through standard-based Internet protocols such as HTTP or SMTP. 
or
Web services framework is an XML-based distributed object/service/component system. Intended to support machine-to-machine interactions over the network.

Characteristics of Web Services

A web service has special behavioral characteristics:

XML-based: As a data transport, XML eliminates any networking, operating system, or platform binding that a protocol has.

Loosely coupled: The web service interface can change over time without compromising the client's ability to interact with the service.
Adopting a loosely coupled architecture tends to make software systems more manageable and allows simpler integration between different systems.

Supports Remote Procedure Calls (RPCs): Web services allow clients to invoke procedures, functions and methods on remote objects using an XML-based protocol.
Remote procedures expose input and output parameters that a web service must support

Ability to be synchronous or asynchronous: 
Synchronicity refers to the binding of the client to the execution of the service. In synchronous invocations, the client blocks and waits for the service to complete its operation before continuing.
Asynchronous operations allow a client to invoke a service and then execute other functions. Asynchronous clients retrieve their result at a later point in time, while synchronous clients receive their result when the service has completed.
Asynchronous capability is a key factor in enabling loosely coupled systems.

Supports document exchange: 
Web services support the transparent exchange of documents to facilitate business integration.

Why Web Service?

Interoperable - Connect across heterogeneous networks using ubiquitous web-based standards.
Economical - Recycle components, no installation and tight integration of software
Automatic - No human intervention required even for highly complex transactions.
Accessible - Legacy assets & internal apps are exposed and accessible on the web.
Available -Services on any device, anywhere, anytime. 
Scalable -No limits on scope of applications and amount of heterogeneous applications.

There are two kind of approach generally used to implement a Web Services: 
1. Code First Approach (Buttom-Up) :- In the Code First Approach, development of the service is started from a code. So the developer can write a service without knowing anything about WSDL. Code First approach is simple, less time consuming and easy to use for people who are not familiar with Web Services standards because WSDL is somewhat hard to understand and use for a beginner. Code First is a good approach to convert a lagacy code into a Web Services. 
2. Contract First Approach (top-Down Approach) :- In the Contract First Approach, development of the service is started from a WSDL definition, which becomes a contract between the service provider and the client. Once WSDl is finalize between the business, the client side and server work can start parallel on basis of finalized WSDL. This approach is more complex compared to Code First Approach and also it requires an in depth understanding of WEB Services. But it is the more popular and recommended. 

JAX-WS Java API XML Web Services with JDK1.6 + wsimport Utility Client Code Examples by Code First Approach




How to generate the stub client for jax-ws web services by wsimport java utility?
It's so simple, we need WSDL file or services publish then we can use it as end point URL in wsimport tool.

For writing the wsdl client we need to generate all the JAXWS artifacts from the wsdl. We already generated wsdl file in previous tutorial, link mentioned on top with note section.

In this session, we will learn, how to write the java web services with help of wsimport utility in jdk1.6+ and JAX-WS. 

What we need before start the code, I'm using as mention below environments, software and already installed in my system:
1. JDK1.6 or +
2. Eclipse
3. Windows OS
4. Basic knowledge of java


Let's start:


Verify the JDK installation

Open the command prompt and verify the java installation
Type the 
C:\>javac -version
javac 1.7.0_25

C:\>java -version
java version "1.7.0_25"
Java(TM) SE Runtime Environment (build 1.7.0_25-b17)
Java HotSpot(TM) Client VM (build 23.25-b01, mixed mode, sharing)

Now java installation got verified, as installed JDK1.7.0_25


Verify the Eclipse installation


Go the the installation directory of eclipse and click on the eclipse.exe
e.g C:\eclipse\eclipse-java-mars-1-win32\eclipse\eclipse.exe

JAX-WS Java API XML Web Services with JDK1.6 + wsgen Utility Code Examples by Code First Approach


Eclipse installation got verified.


Open the Eclipse


Create the new java project
File
New
Java Project
Type the name of project: 
JAX-WS Java API XML Web Services with JDK1.6 + wsimport Utility Code Examples by Code First Approach-Client

Run the earlier service by Click me

Verify the earlier service running or not 

Open the browser and enter the URL:
http://localhost:8088/AToZExamplesService?wsdl

You will get the WSDL details.

Uses of wsimport utility:

Open the command prompt and change the directory as current directory of client project.
e.g:

C:\workspace>cd "C:\workspace\JAX-WS Java API XML Web Services with JDK1.6 + wsimport Utility Code Examples by Code First Approach-Client"

C:\workspace\JAX-WS Java API XML Web Services with JDK1.6 + wsimport Utility Code Examples by Code First Approach-Client>

Type the wsimport command


C:\workspace\JAX-WS Java API XML Web Services with JDK1.6 + wsimport Utility Code Examples by Code First Approach-Client>wsimport

Missing WSDL_URI





Usage: wsimport [options] <WSDL_URI>



where [options] include:

  -b <path>                 specify jaxws/jaxb binding files or additional schemas

                            (Each <path> must have its own -b)

  -B<jaxbOption>            Pass this option to JAXB schema compiler

  -catalog <file>           specify catalog file to resolve external entity references

                            supports TR9401, XCatalog, and OASIS XML Catalog format.

  -d <directory>            specify where to place generated output files

  -extension                allow vendor extensions - functionality not specified

                            by the specification.  Use of extensions may

                            result in applications that are not portable or

                            may not interoperate with other implementations

  -help                     display help
  -httpproxy:<host>:<port>  specify a HTTP proxy server (port defaults to 8080)
  -keep                     keep generated files
  -p <pkg>                  specifies the target package
  -quiet                    suppress wsimport output
  -s <directory>            specify where to place generated source files
  -target <version>         generate code as per the given JAXWS spec version
                            Defaults to 2.2, Accepted values are 2.0, 2.1 and 2.2
                            e.g. 2.0 will generate compliant code for JAXWS 2.0 spec
  -verbose                  output messages about what the compiler is doing
  -version                  print version information
  -wsdllocation <location>  @WebServiceClient.wsdlLocation value
  -clientjar <jarfile>      Creates the jar file of the generated artifacts along with the
                            WSDL metadata required for invoking the web service.

Extensions:
  -XadditionalHeaders              map headers not bound to request or response message to
                                   Java method parameters
  -Xauthfile                       file to carry authorization information in the format
                                   http://username:password@example.org/stock?wsdl
  -Xdebug                          print debug information
  -Xno-addressing-databinding      enable binding of W3C EndpointReferenceType to Java
  -Xnocompile                      do not compile generated Java files
  -XdisableSSLHostnameVerification disable the SSL Hostname verification while fetching
                                   wsdls

Examples:
  wsimport stock.wsdl -b stock.xml -b stock.xjb
  wsimport -d generated http://example.org/stock?wsdl


C:\workspace\JAX-WS Java API XML Web Services with JDK1.6 + wsimport Utility Code Examples by Code First Approach-Client>


We got the description of wsimport command as mention bellow which 
is self explanatory.

Now generate the client artificts with help of wsimport utility of jdk1.6 or higher

JAX-WS Java API XML Web Services with JDK1.6 + wsimport Utility Code Examples by Code First Approach-Client



C:\workspace\JAX-WS Java API XML Web Services with JDK1.6 + wsimport Utility Code Examples by Code First Approach-Client>wsimport -keep -s src -verbos
e -d class http://localhost:8088/AToZExamplesService?wsdl
parsing WSDL...



Generating code...

com\atozexamples\atozexamplesservice\AToZExamplesService.java
com\atozexamples\atozexamplesservice\AToZExamplesServiceService.java
com\atozexamples\atozexamplesservice\ObjectFactory.java
com\atozexamples\atozexamplesservice\PrintGreeting.java
com\atozexamples\atozexamplesservice\PrintGreetingResponse.java
com\atozexamples\atozexamplesservice\package-info.java

Compiling code...

javac -d C:\workspace\JAX-WS Java API XML Web Services with JDK1.6 + wsimport Utility Code Examples by Code First Approach-Client\class -classpath C:\
java1.7\jdk1.7.0_25/lib/tools.jar;C:\java1.7\jdk1.7.0_25/classes -Xbootclasspath/p:C:\java1.7\jdk1.7.0_25\jre\lib\rt.jar;C:\java1.7\jdk1.7.0_25\jre\li
b\rt.jar C:\workspace\JAX-WS Java API XML Web Services with JDK1.6 + wsimport Utility Code Examples by Code First Approach-Client\src\com\atozexamples
\atozexamplesservice\AToZExamplesService.java C:\workspace\JAX-WS Java API XML Web Services with JDK1.6 + wsimport Utility Code Examples by Code First
 Approach-Client\src\com\atozexamples\atozexamplesservice\AToZExamplesServiceService.java C:\workspace\JAX-WS Java API XML Web Services with JDK1.6 +
wsimport Utility Code Examples by Code First Approach-Client\src\com\atozexamples\atozexamplesservice\ObjectFactory.java C:\workspace\JAX-WS Java API
XML Web Services with JDK1.6 + wsimport Utility Code Examples by Code First Approach-Client\src\com\atozexamples\atozexamplesservice\PrintGreeting.jav
a C:\workspace\JAX-WS Java API XML Web Services with JDK1.6 + wsimport Utility Code Examples by Code First Approach-Client\src\com\atozexamples\atozex
amplesservice\PrintGreetingResponse.java C:\workspace\JAX-WS Java API XML Web Services with JDK1.6 + wsimport Utility Code Examples by Code First Appr
oach-Client\src\com\atozexamples\atozexamplesservice\package-info.java

C:\workspace\JAX-WS Java API XML Web Services with JDK1.6 + wsimport Utility Code Examples by Code First Approach-Client>



Client code generated now.

AToZExamplesService.java

package com.atozexamples.atozexamplesservice;

import javax.jws.WebMethod;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.Action;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;


/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.4-b01
 * Generated source version: 2.2
 *
 */
@WebService(name = "AToZExamplesService", targetNamespace = "http://www.atozexamples.com/AToZExamplesService")
@XmlSeeAlso({
    ObjectFactory.class
})
public interface AToZExamplesService {


    /**
     *
     * @return
     *     returns java.lang.String
     */
    @WebMethod
    @WebResult(targetNamespace = "")
    @RequestWrapper(localName = "printGreeting", targetNamespace = "http://www.atozexamples.com/AToZExamplesService", className = "com.atozexamples.atozexamplesservice.PrintGreeting")
    @ResponseWrapper(localName = "printGreetingResponse", targetNamespace = "http://www.atozexamples.com/AToZExamplesService", className = "com.atozexamples.atozexamplesservice.PrintGreetingResponse")
    @Action(input = "http://www.atozexamples.com/AToZExamplesService/AToZExamplesService/printGreetingRequest", output = "http://www.atozexamples.com/AToZExamplesService/AToZExamplesService/printGreetingResponse")
    public String printGreeting();

}


AToZExamplesServiceService.java



package com.atozexamples.atozexamplesservice;

import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;


/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.4-b01
 * Generated source version: 2.2
 *
 */
@WebServiceClient(name = "AToZExamplesServiceService", targetNamespace = "http://www.atozexamples.com/AToZExamplesService", wsdlLocation = "http://localhost:8088/AToZExamplesService?wsdl")
public class AToZExamplesServiceService
    extends Service
{

    private final static URL ATOZEXAMPLESSERVICESERVICE_WSDL_LOCATION;
    private final static WebServiceException ATOZEXAMPLESSERVICESERVICE_EXCEPTION;
    private final static QName ATOZEXAMPLESSERVICESERVICE_QNAME = new QName("http://www.atozexamples.com/AToZExamplesService", "AToZExamplesServiceService");

    static {
        URL url = null;
        WebServiceException e = null;
        try {
            url = new URL("http://localhost:8088/AToZExamplesService?wsdl");
        } catch (MalformedURLException ex) {
            e = new WebServiceException(ex);
        }
        ATOZEXAMPLESSERVICESERVICE_WSDL_LOCATION = url;
        ATOZEXAMPLESSERVICESERVICE_EXCEPTION = e;
    }

    public AToZExamplesServiceService() {
        super(__getWsdlLocation(), ATOZEXAMPLESSERVICESERVICE_QNAME);
    }

    public AToZExamplesServiceService(WebServiceFeature... features) {
        super(__getWsdlLocation(), ATOZEXAMPLESSERVICESERVICE_QNAME, features);
    }

    public AToZExamplesServiceService(URL wsdlLocation) {
        super(wsdlLocation, ATOZEXAMPLESSERVICESERVICE_QNAME);
    }

    public AToZExamplesServiceService(URL wsdlLocation, WebServiceFeature... features) {
        super(wsdlLocation, ATOZEXAMPLESSERVICESERVICE_QNAME, features);
    }

    public AToZExamplesServiceService(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }

    public AToZExamplesServiceService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
        super(wsdlLocation, serviceName, features);
    }

    /**
     *
     * @return
     *     returns AToZExamplesService
     */
    @WebEndpoint(name = "AToZExamplesServicePort")
    public AToZExamplesService getAToZExamplesServicePort() {
        return super.getPort(new QName("http://www.atozexamples.com/AToZExamplesService", "AToZExamplesServicePort"), AToZExamplesService.class);
    }

    /**
     *
     * @param features
     *     A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy.  Supported features not in the <code>features</code> parameter will have their default values.
     * @return
     *     returns AToZExamplesService
     */
    @WebEndpoint(name = "AToZExamplesServicePort")
    public AToZExamplesService getAToZExamplesServicePort(WebServiceFeature... features) {
        return super.getPort(new QName("http://www.atozexamples.com/AToZExamplesService", "AToZExamplesServicePort"), AToZExamplesService.class, features);
    }

    private static URL __getWsdlLocation() {
        if (ATOZEXAMPLESSERVICESERVICE_EXCEPTION!= null) {
            throw ATOZEXAMPLESSERVICESERVICE_EXCEPTION;
        }
        return ATOZEXAMPLESSERVICESERVICE_WSDL_LOCATION;
    }

}



ObjectFactory.java



package com.atozexamples.atozexamplesservice;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;


/**
 * This object contains factory methods for each
 * Java content interface and Java element interface
 * generated in the com.atozexamples.atozexamplesservice package.
 * <p>An ObjectFactory allows you to programatically
 * construct new instances of the Java representation
 * for XML content. The Java representation of XML
 * content can consist of schema derived interfaces
 * and classes representing the binding of schema
 * type definitions, element declarations and model
 * groups.  Factory methods for each of these are
 * provided in this class.
 *
 */
@XmlRegistry
public class ObjectFactory {

    private final static QName _PrintGreeting_QNAME = new QName("http://www.atozexamples.com/AToZExamplesService", "printGreeting");
    private final static QName _PrintGreetingResponse_QNAME = new QName("http://www.atozexamples.com/AToZExamplesService", "printGreetingResponse");

    /**
     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.atozexamples.atozexamplesservice
     *
     */
    public ObjectFactory() {
    }

    /**
     * Create an instance of {@link PrintGreetingResponse }
     *
     */
    public PrintGreetingResponse createPrintGreetingResponse() {
        return new PrintGreetingResponse();
    }

    /**
     * Create an instance of {@link PrintGreeting }
     *
     */
    public PrintGreeting createPrintGreeting() {
        return new PrintGreeting();
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link PrintGreeting }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://www.atozexamples.com/AToZExamplesService", name = "printGreeting")
    public JAXBElement<PrintGreeting> createPrintGreeting(PrintGreeting value) {
        return new JAXBElement<PrintGreeting>(_PrintGreeting_QNAME, PrintGreeting.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link PrintGreetingResponse }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://www.atozexamples.com/AToZExamplesService", name = "printGreetingResponse")
    public JAXBElement<PrintGreetingResponse> createPrintGreetingResponse(PrintGreetingResponse value) {
        return new JAXBElement<PrintGreetingResponse>(_PrintGreetingResponse_QNAME, PrintGreetingResponse.class, null, value);
    }

}


package-info


@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.atozexamples.com/AToZExamplesService")
package com.atozexamples.atozexamplesservice;


PrintGreeting.java



package com.atozexamples.atozexamplesservice;

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


/**
 * <p>Java class for printGreeting complex type.
 *
 * <p>The following schema fragment specifies the expected content contained within this class.
 *
 * <pre>
 * &lt;complexType name="printGreeting">
 *   &lt;complexContent>
 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       &lt;sequence>
 *       &lt;/sequence>
 *     &lt;/restriction>
 *   &lt;/complexContent>
 * &lt;/complexType>
 * </pre>
 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "printGreeting")
public class PrintGreeting {


}



PrintGreetingResponse.java



package com.atozexamples.atozexamplesservice;

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


/**
 * <p>Java class for printGreetingResponse complex type.
 *
 * <p>The following schema fragment specifies the expected content contained within this class.
 *
 * <pre>
 * &lt;complexType name="printGreetingResponse">
 *   &lt;complexContent>
 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       &lt;sequence>
 *         &lt;element name="return" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       &lt;/sequence>
 *     &lt;/restriction>
 *   &lt;/complexContent>
 * &lt;/complexType>
 * </pre>
 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "printGreetingResponse", propOrder = {
    "_return"
})
public class PrintGreetingResponse {

    @XmlElement(name = "return")
    protected String _return;

    /**
     * Gets the value of the return property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *    
     */
    public String getReturn() {
        return _return;
    }

    /**
     * Sets the value of the return property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *    
     */
    public void setReturn(String value) {
        this._return = value;
    }

}



Writhe the calling or AToZExamplesClient which will have the client code and main method

Right click on the src folder
New
Class
Type the name:AToZExamplesClient
Type the package name:com.atozexamples.client
Finish

AToZExamplesClient.java


package com.atozexamples.client;

import com.atozexamples.atozexamplesservice.AToZExamplesService;
import com.atozexamples.atozexamplesservice.AToZExamplesServiceService;

public class AToZExamplesClient {

       public AToZExamplesClient() {
              // TODO Auto-generated constructor stub
       }

       public static void main(String[] args) {
              //
              AToZExamplesServiceService objAToZExamplesServiceService = new AToZExamplesServiceService();
              AToZExamplesService objMathService = objAToZExamplesServiceService.getAToZExamplesServicePort();
              System.out.println(objMathService.printGreeting());

       }

}



Run the  AToZExamplesClient

Right click, run as, java application.

Out put:

Hello from AToZExamples.com!!

Happy learning and implementation!!!