Top Banner
Web Services Harish Alwala
32

WebService-Java

Jan 28, 2015

Download

Technology

halwal

Detail Description of WebServices
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: WebService-Java

Web ServicesHarish Alwala

Web ServicesHarish Alwala

Page 2: WebService-Java

2

Agenda

>>>>

>>>>

>>>>

Overview

Architecture

WSDL

>>>>SOAP

>>>>UDDI

>>>>An Example

Page 3: WebService-Java

3

OverviewGeneral Definition

A Web Service is a software component that is described via WSDL and is capable of being accessed via standard network protocols such as but not limited to SOAP over HTTP.

Web service is a software component that provides a consistent, transparent API for invocation of services by using message-oriented transport mechanisms, which can be dynamically located and bound, and by utilizing XML for data representation and transformation

According to Gartner Group:“Web services are software components that interact with one another dynamically via

standard Internet Technologies, making it possible to build bridges between IT systems that otherwise would require extensive development efforts”

Web services are Complementary to existing technology Building blocks (components) used to construct larger applications Evolutionary technology: The latest in a long line of approaches for distributed

applications communication

Web services are NOT A rip and replace technology A solution to all the integration woes

Page 4: WebService-Java

4

OverviewKey Features

Web services are self-contained.

On the client side, no additional software is required. A programming language with XML and HTTP client support is enough to get you started. On the server side, merely a Web server and a SOAP server are required.

Web services are self-describing.

Neither the client nor the server knows or cares about anything besides the format and content of request and response messages (loosely coupled application integration).

Web services can be published, located, and invoked across the Web.

This technology uses established lightweight Internet standards such as HTTP. It leverages the existing infrastructure. Some additional standards that are required to do so include SOAP, WSDL, and UDDI.

Web services are language-independent and interoperable.

Client and server can be implemented in different environments. Existing code does not have to be changed in order to be Web service enabled.

Cntd…

Page 5: WebService-Java

5

Overview

Key Features

Web services are inherently open and standard-based.

XML and HTTP are the major technical foundation for Web services. A large part of the Web service technology has been built using open-source projects.

Therefore, vendor independence and interoperability are realistic goals this time.

Web services build on proven mature technology

There are a lot of commonalities, as well as a few fundamental differences to other distributed computing frameworks. For example, Web services are build with SOA Architecture.

Web services are loosely coupled

Traditionally, application design has depended on tight interconnections at both ends. Web services require a simpler level of coordination that allows a more flexible re-configuration for an integration of the services in question.

Web services provide the ability to wrap existing applications

Already existing stand-alone applications can easily be integrated into the service-oriented architecture by implementing a Web service as an interface.

Page 6: WebService-Java

6

Architecture

Characteristics of the Web service architecture

Webservice that follows the service-oriented architecture employs a loose coupling betweenthe participants. Such a loose coupling provides greater flexibility:

In this architecture, a client is not coupled to a server, but to a service. Thus, the integration of the server to use takes place outside of the scope of the client application programs.

Functional components and their interfaces are separated. Therefore, new interfaces can be plugged in more easily.

Within complex applications, the control of business processes can be isolated. A business rule engine can be incorporated to control the workflow of a defined business process. Depending on the state of the workflow, the engine calls the respective services.

Bindings are specified using configuration files and can thus easily be adapted to new needs.

Page 7: WebService-Java

7

Architecture

Concept of a service-oriented The service provider creates a Web

service and possibly publishes its interface and access information to the service registry.

The service broker (also known as service registry) is responsible for making the Web service interface and implementation access information available to any potential service requestor.

The service requestor locates entries in the broker registry using various find operations and then binds to the service provider in order to invoke one of its Web services.

Page 8: WebService-Java

8

Architecture

The following are the core technologies used for Web services. XML (eXtensible Markup Language)

The markup language that underlies most of the specifications used for Web services. XML is a generic language that can be used to describe any kind of content in a structured way, separated from its presentation to a specific device.

SOAP (Simple Object Access Protocol)SOAP similar to JDBC, is a network, transport, and programming language and platform neutral protocol that allows a client to call a remote service. The message format is XML.

WSDL (Web services description language) WSDL is an XML-based interface and implementation description language. The service provider uses a WSDL document in order to specify the operations a Web service provides, as well as the parameters and data types of these operations. A WSDL document also contains the service access information.

UDDI (universal description, discovery, and integration) UDDI is both a client-side API and a SOAP-based server implementation that can be used to store and retrieve information on service providers and Web services.

Page 9: WebService-Java

9

WSDLWSDL architecture Web Services Description Language

(WSDL) files are written in Extensible Markup Language (XML).

WSDL is one alternative to make service interfaces and implementations available in the UDDI registry.

WSDL includes the workflow description (business process execution language for Web services, BPEL4WS)

WSDL is the base for SOAP server deployment and SOAP client generation.

A WSDL file contains the following parts:

Web service interface definition This is part contains the

elements, as well as the namespaces.

Web service implementation This part contains the definition of

the service and ports.

The following is the structure of the information in a WSDL file : A WSDL file contains the following parts:

Page 10: WebService-Java

10

WSDLA WSDL file describes a Web service with the following elements:

portType The description of the operations and associated messages. The

portType element defines abstract operations.<portType name="EightBall">

<operation name="getAnswer">

<input message="ebs:IngetAnswerRequest"/><output message="ebs:OutgetAnswerResponse"/>

</operation>

</portType>

message The description of input and output parameters and return values.

<message name="IngetAnswerRequest">

<part name="meth1_inType" type="ebs:questionType"/>

</message>

<message name="OutgetAnswerResponse">

<part name="meth1_outType" type="ebs:answerType"/>

</message>

Page 11: WebService-Java

11

WSDL

types The schema for describing XML types used in the messages.

<types>

<xsd:schema targetNamespace="...">

<xsd:complexType name="questionType"><xsd:element name="question" type="string"/></xsd:complexType>

<xsd:complexType name="answerType">

...</types>

binding The bindings describe the protocol that is used to access a portType, as well as the

data formats for the messages that are defined by a particular portType element.<binding name="EightBallBinding" type="ebs:EightBall">

<soap:binding style="rpc”

transport="schemas.xmlsoap.org/soap/http">

<operation name="ebs:getAnswer">

<soap:operation soapAction="urn:EightBall"/>

<input>

<soap:body

namespace="urn:EightBall" ... />

Page 12: WebService-Java

12

WSDL

The services and ports define the location of the Web service Service

The service contains the Web service name and a list of ports. Ports

The ports contain the location of the Web service and the binding used for service access.

<service name="EightBall">

<port binding="ebs:EightBallBinding" name="EightBallPort">

<soap:address location="localhost:8080/axis/EightBall"/>

</port></service>

D:\Program Files\j2sdk_nb\netbeans3.5\to

Page 13: WebService-Java

13

SOAP

SOAP SOAP is a lightweight protocol intended for exchanging structured information in a

decentralized, distributed environment. SOAP uses XML technologies to define an extensible messaging framework, which provides a message construct that can be exchanged over a variety of underlying protocols. The framework has been designed to be independent of any particular programming model and other implementation specific semantics.

It represents the main way of communication between the three key actors in a service oriented architecture (SOA): service provider, service requestor and service broker. The main goal of its design is to be simple and extensible. A SOAP message is used to request a Web service.

Page 14: WebService-Java

14

SOAP

SOAP can be used over any transport protocol such as TCP, HTTP, SMTP

This protocol consists of three parts: An envelope that defines a framework for describing message content and processing

instructions. A set of encoding rules for expressing instances of application-defined data types. A convention for representing remote procedure calls and responses.

SOAP is a protocol-independent transport and can be used in combination with a variety of protocols. In Web services SOAP is used in combination with HTTP, HTTP extension framework and Java Message Service (JMS).

SOAP is also operating-system independent and not tied to any programming language or component technology.

As long as the client can issue XML messages, it does not matter what technology is used to implement the client. Also, both server and client sides can reside on any suitable platform.

Page 15: WebService-Java

15

SOAP

SOAP Schema:

The Envelope element is always the root element of a SOAP message. The Envelope element contains an optional Header element, followed by a mandatory Body element.

The Body element represents the message payload. The Body element is a generic container in that it can contain any number of elements from any namespace. This is ultimately where the data goes that you're trying to send.

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header>

<!-- optional -->

<!-- header blocks go here... -->

</soap:Header>

<soap:Body>

<!-- payload or Fault element goes here... -->

</soap:Body>

</soap:Envelope>

Page 16: WebService-Java

16

SOAP

SOAP Request<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">

<soap:Body> <x:TransferFunds xmlns:x="urn:examples-org:banking">

<from>01-4-2006</from> <to>31-04-2006</to> <amount>100.00</amount>

</x:TransferFunds> </soap:Body>

</soap:Envelope>

SOAP Response

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body>

<x:TransferFundsResponse xmlns:x="urn:examples-org:banking"> <balances>

<account> <id>22-342439</id> <balance>33.45</balance>

</account> </balances>

</x:TransferFundsResponse> </soap:Body>

</soap:Envelope>

Page 17: WebService-Java

17

SOAP

Fault Code<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">

<soap:Body> <soap:Fault>

<faultcode>soap:Server</faultcode> <faultstring>Insufficient funds</faultstring>

<detail> <x:TransferError

xmlns:x="urn:examples-org:banking">

<sourceAccount>22-342439</sourceAccount> <transferAmount>

100.00</transferAmount> <currentBalance>89.23</currentBalance>

</x:TransferError> </detail>

</soap:Fault> </soap:Body>

</soap:Envelope>

Page 18: WebService-Java

18

UDDI The Universal Description, Discovery and Integration (UDDI) define a

way to publish and discover information about Web services. The term “Web service” describes specific business functionality exposed by a company, usually through an Internet connection, for the purpose of providing a way for another company or software program to use the service.

Conceptually, the information provided in a UDDI business registration consists of three components:

white pages address, contact, and known identifiers;

yellow pages industrial categorizations based on standard taxonomies;

green pages the technical information about services that are exposed by the

business. Green pages include references to specifications for Web services, as well as support for pointers to various file and URL based discovery mechanisms if required.

Page 19: WebService-Java

19

Service Styles

Service Styles - RPC, Document, Wrapped, and Message RPC:

RPC services are the default in Axis Axis will deserialize XML into Java objects which can be fed to your service, and will

serialize the returned Java object(s) from your service back into XML. Document

Document services do not use any encoding (so in particular, you won't see multiref object serialization or SOAP-style arrays on the wire) but DO still do XML<->Java databinding

Wrapped Wrapped services are just like document services, except that rather than binding the

entire SOAP body into one big structure, they "unwrap" it into individual parameters Message

Message services receive and return arbitrary XML in the SOAP Envelope without any type mapping / data binding. If you want to work with the raw XML of the incoming and outgoing SOAP Envelopes, write a message service

D:\Program Files\j2sdk_nb\netbeans3.5\to

Page 20: WebService-Java

20

Service Styles

<schema targetNamespace="http://commerce.com/PO"> <complexType name="POType">

<sequence> <element name="item" type="xsd:string"/>

<element name="quantity" type="xsd:int"/>

<element name="description" type="xsd:string"/>

</sequence>

</complexType>

<element name="PurchaseOrder" type="POType"/>

document style service, this would map to a method like this: public void method(PurchaseOrder po)

In other words, the ENTIRE <PurchaseOrder> element would be handed to your method as a single bean with three fields inside it. On the other hand,

• wrapped style service, it would map to a method like this: public void purchaseOrder(String item, int quantity, String description)

Message Servicepublic Element [] method(Element [] bodies); public SOAPBodyElement [] method (SOAPBodyElement [] bodies); public Document method(Document body); public void method(SOAPEnvelope req, SOAPEnvelope resp);

Page 21: WebService-Java

21

Service Styles

Standard mappings from WSDL to Java

Page 22: WebService-Java

22

An Example

Axis Setup Axis software in the form of xml-axis-beta3-bin.zip can be downloaded from

http://archive.apache.org/dist/ws/axis/beta3\ Extract the folder from zip file to c:/xml-axis folder Set “%XML_AXIS% = c:/xml-axis” as environment variable Set classpath = %XML_AXIS%\lib\axis.jar; %XML_AXIS%\ lib\commons-logging.jar;

%XML_AXIS%\lib\jaxrpc.jar;c:\xml-axis\lib\log4j-1.2.4.jar; %XML_AXIS%\lib\tt-bytecode.jar; %XML_AXIS%\lib\wsdl4j.jar;%XML_AXIS%\lib\xmlParserAPIs.jar; %XML_AXIS%\lib\saaj.jar %JAVA_HOME%\lib\tools.jar;

Apache Tomcat Setup Download Apache tomcat (jakarta-tomcat-4.1.31.exe) from

http://mirror.tomato.it/apache/jakarta/tomcat-4/v4.1.31/bin Set “CATALINA_HOME = C:\Apache Tomcat 4.0” as environment variable Also set “path=%path%;CATALINA_HOME\bin” Add the following in server.xml (C:\Apache Tomcat 4.0\conf).

<Context path="/axis" docBase="C:\xml-axis\webapps\axis" debug="0"/> Start tomacat web server

Page 23: WebService-Java

23

An Example

A sample java Classpublic class HelloWorld{

public String sayHello(String reader){System.out.println("Service Called");return "Hi " + reader + " How are you";

}}

Steps to Expose as Web Service Write the following to a text file and name it as HelloWorldService.wsdd.

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

<deployment xmlns=“http://xml.apache.org/axis/wsdd/” xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">

<service name="HelloWorldService" provider="java:RPC">

<parameter name="allowedMethods" value=“sayHello"/>

<parameter name="className" value="HelloWorld"/>

</service>

</deployment>

Page 24: WebService-Java

24

An Example

Use the above wsdd file to expose as web service with the following command. java -classpath "%classpath%;C:\jars\axis.jar;C:\jars\jaxrpc.jar;C:\jars\

commons-logging-1.0.3.jar;C:\jars\commons-discovery-0.2.jar;C:\jars\jndi.jar;C:\jars\saaj.jar;." org.apache.axis.client.AdminClient -h localhost -p 8080 -s WebservicesTest/servlet/AxisServlet "C:\HelloWorldService.wsdd“

Test the exposed web service http://localhost:8080/WebservicesTest/servlet/AxisServlet

Click on “wsdl” to view wsdl file in browser. Use the following command to generate wsdl file for the exposed service

Java org.apache.axis.wsdl.Java2WSDL HelloWorld -l http://localhost:8080/WebservicesTest/services/HelloWorldService

Copy the wsdl file to %XML_AXIS% root

Use the following command to generate the stubs for given wsdl file java org.apache.axis.wsdl.WSDL2Java C:\xml-axis\HelloWorldService.wsdl For the generated stubs write a java class to access the web service.

Page 25: WebService-Java

25

An Example

Java code to access the web service via stubsimport java.rmi.RemoteException;import javax.xml.rpc.ServiceException;public class HelloWorldStubClient {

public static void main(String[] args) { try{

//Fetch HelloWorldService object from Service Locator generated HelloWorldService hWorldService = new HelloWorldServiceLocator(); //Fetch actual service hosted from the service. HelloWorld hWorld = hWorldService.getHelloWorldService(); //call the Service method System.out.println(hWorld.sayHello("Harish"));

}catch(ServiceException sExc){ sExc.printStackTrace(); }catch(RemoteException rExc){ rExc.printStackTrace(); }}

}

Page 26: WebService-Java

26

An Example

java org.apache.axis.utils.tcpmon

Page 27: WebService-Java

27

Documentation

The JAX-WS 2.0 specification demands that the exception annotated with @WebFault must have two constructors and one method:

WrapperException(String message, FaultBean faultInfo)WrapperException(String message, FaultBean faultInfo, Throwable cause)FaultBean getFaultInfo()The WrapperException is replaced by the name of the exception, and FaultBean is replaced by the class name that implements the fault bean. The fault bean is a Java bean that contains the information of the fault and is used by the Web service client to know the cause for the fault.

Sample @javax.xml.ws.WebFault(name="AddNumbersException",

    targetNamespace="http://server.fromjava/jaxws")public class AddNumbersException_Exception extends Exception {    private fromjava.client.AddNumbersException faultInfo;    public AddNumbersException_Exception(String message, AddNumbersException faultInfo) {        super(message);        this.faultInfo = faultInfo;    }

    public AddNumbersException_Exception(String message, AddNumbersException faultInfo,                                         Throwable cause) {        super(message, cause);        this.faultInfo = faultInfo;    }

    public AddNumbersException getFaultInfo() {        return faultInfo;    }}

Page 28: WebService-Java

28

Documentation

HandlerChain

Example:

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

<javaee:handler-chains xmlns:javaee=http://java.sun.com/xml/ns/javaee xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<javaee:handler-chain>

<javaee:handler-chain-name>Service Framework Handlers</javaee:handler-chain-name>

<javaee:handler>

<javaee:handler-name>LoggingHandler</javaee:handler-name>

<javaee:handler-class>com.test.handlers.LoggingHandler

</javaee:handler-class>

</javaee:handler>

<javaee:handler>

<javaee:handler-name>ThrottlingHandler</javaee:handler-name>

<javaee:handler-class>com.test.handlers.ThrottlingHandler

</javaee:handler-class>

</javaee:handler>

</javaee:handler-chain>

</javaee:handler-chains>

Page 29: WebService-Java

29

Documentation

HandlerChain

Example:

Handler Interface

public class LoggingHandler implements SOAPHandler<SOAPMessageContext>public boolean handleFault(SOAPMessageContext context)

public boolean handleMessage(SOAPMessageContext context)

public Set<QName> getHeaders()

Page 30: WebService-Java

30

Documentation

Annotations:JSR 181 (Web Services Metadata) Annotations

2.1 javax.jws.WebService

2.2 javax.jws.WebMethod

2.3 javax.jws.OneWay

2.4 javax.jws.WebParam

2.5 javax.jws.WebResult

2.6 javax.jws.HandlerChain

2.7 javax.jws.soap.SOAPBinding

3. JSR 224 (JAX-WS) Annotations

3.1 javax.xml.ws.BindingType

3.2 javax.xml.ws.RequestWrapper

3.3 javax.xml.ws.ResponseWrapper

3.4 javax.xml.ws.ServiceMode

3.5 javax.xml.ws.WebEndpoint

3.6 javax.xml.ws.WebFault

3.7 javax.xml.ws.WebServiceClient

3.8 javax.xml.ws.WebServiceProvider

3.9 javax.xml.ws.WebServiceRef

4. JSR 222 (JAXB) Annotations

4.1 javax.xml.bind.annotation.XmlRootElement

4.2 javax.xml.bind.annotation.XmlAccessorType

4.3 javax.xml.bind.annotation.XmlType

4.4 javax.xml.bind.annotation.XmlElement

Page 31: WebService-Java

31

Documentation

URLs http://today.java.net/pub/a/today/2006/09/19/asynchronous-jax-ws-web-

services.html

http://java.sun.com/webservices/docs/2.0/tutorial/doc/

http://ws.apache.org/axis/java/user-guide.html#Introduction

Page 32: WebService-Java

Thank You!