Sei sulla pagina 1di 61

Java Web Services

Mark Hansen
Founder & President
AgileIT
http://agileitinc.com

Overall Presentation Goal

Understand the different ways that SOAP and REST


endpoints can be implemented using Java Web Services.
Please Ask Questions!

http://agileitinc.com

Speakers Qualifications

Mark Hansen is the Founder and President


of AgileIT
Author of SOA Using
Java Web Services
Developed the
SOA-J Framework
PhD from MITs Lab
for Computer Science
http://agileitinc.com

Java WS have improved since J2EE 1.4 and JAX-RPC.

JAXB

standard XML Binding

JAX-WSmuch better than JAX-RPC

JAX-RS

REST API being developed


for Java EE 6 (JSR-311)

http://agileitinc.com

Outline

Web Services Platform Architecture


(WSPA)
Basic REST with HttpServlet
WSDL, SOAP, and Java/XML Binding
JAXB and JAX-WS
JAX-RS for REST
The ServiceLayerTM Framework

http://agileitinc.com

SOA Using Java Web Services - Introduction

Am I Stupid, or Is Java Web Services


Really Hard?

http://agileitinc.com

SOA Using Java Web Services - Introduction

http://agileitinc.com

Web Services are Hard

Java OO Programming Paradigm


Web Services Message Exchange
Paradigm

creates an
.
Impedance Mismatch

http://agileitinc.com

Impedance Mismatch
Java Objects

Java Objects

Impedance Matcher
(Object Relational
Mapping)

Impedance Matcher
(Java/XML Binding)

Relational Tables

XML Documents

Table

Table
XML

Table

XML
XML

http://agileitinc.com

Web Services Platform Architecture (WSPA)


WSPA Identifies Three Components of JWS

Invocation

Marshalling (Impedance Matcher)

Proxies Represent Web Services in Java


Interface to Messaging System (HTTP)
QoS (Handlers)
Java/XML Binding

Deployment

Implement Web Service Endpoints (SOAP,


REST) with Java
http://agileitinc.com

Invocation

param

return

SEI : Java Proxy

param

param

Invocation Subsystem
(Server Side)

Java Method
Invocation

Request :
SOAP

Request :
SOAP

param

param

Response :
SOAP

Response :
SOAP

SEI : Java Proxy

param

Invocation Subsystem
(Client Side)

return

SOAP Message
Exchange
(Specified by WSDL)

http://agileitinc.com

Java Method
Invocation

Target :
Java Object

Java Proxies Represent Web Services

http://agileitinc.com

Marshalling and Unmarshalling

http://agileitinc.com

Deployment
Web Services Platform
Web Services Directory
(e.g., UDDI)
Container (e.g., J5EE,
Servlets, Axis)

WSDL
+someOperation()

Endpoint Listener
-url
WSDL
Deployment

WSDL/Java
Mapping

SOAP
Handlers

Java Target
Binding
Context

Container
Deployment
Descriptors

+someMethod()

http://agileitinc.com

Source Artifacts
(e.g., EJB wrapper)

REST vs. SOAP

REST SOAP
Message Format

XML1

SOAP

Interface Definition None2

WSDL

Transport

HTTP3, FTP, MIME,


JMS, SMTP, etc.

1.
2.
3.

HTTP

Also uses HTTP headers and query string.


XML Schema sometimes provided. And out of band documentation.
Without WS-Addressing, SOAP relies on the message transport for dispatching (e.g., HTTP
context path).

http://agileitinc.com

REST vs. SOAP

REST is best when

Rapid prototyping and quick demos for endusers are


important.
Data is not highly structured or well defined by a schema
so you want to experiment and see the data in a
browser and write code based on that.

SOAP is best when

Bullet-proof integration of systems is important.


Well defined application interfaces are needed.
Data conforms to a schema.
QoS (e.g., guaranteed delivery) issues are important.

http://agileitinc.com

Code Examples
Implementing REST Services
HttpServlet vs. JAX-WS vs. JAX-RS

Basic REST HttpURLConnection (JDK 1.1)


Receiver

Sender
XML Message

GetNewOrders
URL
openConnection(...)
1
HttpURLConnection
InputStream

HTTP response
containing XML
document

read(...)
3
connect(...)
2
Client

HTTP "GET"
request to
download XML
document

Web Service

http://agileitinc.com

Basic REST Dispatch<Source> (JAX-WS 2.0 )


Receiver

Sender
XML Message

GetNewOrders
Service
1

addPort(...)
createDispatch(...)
2

Dispatch<Source>
3

invoke(...)

5
Source

Client

HTTP GET request


to download XML
document

HTTP response
containing XML
document

Web Service

http://agileitinc.com

Basic REST - HttpServlet


Receiver

Sender

XML
Message

HTTP GET request

GetNewOrdersServlet
(extends HTTPServlet)
2

doGet( ... )

getNewOrders( ... )
3

Source
6
HTTP response
containing the XML
new orders
document

( new orders )

Tranformer
transform( )

StreamResult

ServletOutputStream

Client

OrderManager

Servlet Container

http://agileitinc.com

Basic REST Provider<Source>


Receiver

XML
Message

HTTP POST request


1

Sender

GetNewOrdersProvider
(Provider<Source>)
2
invoke( ... )

OrderManager
getNewOrders( ... )
3

Source

Client

HTTP response
containing the XML
new orders document
5

( new orders )

Java EE 5 Container

http://agileitinc.com

REST using JAX-RS (Java EE 6 Preview)


Receiver

XML
Message

Sender

@Path("/orders")
HTTP GET request
1

@ProduceMime("text/xml")
@GET
2
getNewOrders()

Client

HTTP response
containing the XML
new orders document
5

Java EE 6 Container

http://agileitinc.com

Database

The Role of WSDL in Enterprise SOA


subsystem

subsystem

Enterprise System
(e.g., Order Management System)

Web Services Platform


WSDL

ServiceDeployment

subsystem

XML Schema Library


Orders.xsd

datatype
types

datatype
binding

subsystem

Web Services Infrastructure

subsystem

XML Schema Library


Faults.xsd

http://agileitinc.com

operation

Java Method

Mapping WSDL and XML Schema to Java


WSDL

JAXB

types

portType

JAX-WS

Service Endpoint
Implementation (SEI)

operation
+ method()

http://agileitinc.com

Approaches to Web Services Development

WSDL

WSDL

WSDL

Java

Java

Java

Code First

Contract First

Meet in the
Middle

http://agileitinc.com

Code First

Annotate Your Code


Deploy it in a container that supports
JAX-WS
The JAX-WS runtime will:

Generate WSDL.
Translate SOAP request to a Java method
invocation.
Translate method return into a SOAP
response.
http://agileitinc.com

SOA Using Java Web Services Part I


JAX-WS Client Side Invocation with Proxy
Web Service
1
Service
Endpoint
Interface

WSDL to Java
Mapping Tool

WSDL

(e.g., wsimport)
Endpoint URL

javax.xml.ws.Service
4
getPort(...)

SOAP
Request

Proxy Instance
Parameters

(JAXB Generated
Class Instances)

Service
Endpoint
Interface

Invocation
Handler

Return Value
(JAXB Generated
Class Instance)

http://agileitinc.com

SOAP
Response

DEMO
Code First With JAX-WS

Contract First

Compile the WSDL for the service that


you would like to deploy.

wsimport reads the WSDL and generates an


interface for each portType

Create a class that implements each


interface. The business logic of these
classes implements your Web services.
Deploy these Service Endpoint
Implementation classes to a JAX-WS
container.
http://agileitinc.com

SOA Using Java Web Services Part I


JAX-WS Server Side Invocation Subsystem

Publish
WSDL

JSR-109 &
JSR-181
Services

Handler Chain

Web Service
7

Handler
(javax.xml.ws.handler
.soap.SOAPHandler)

JAX-WS and JAXB


Java/XML Binding

SOAP
Response

8 SOAP Fault Processing

mustUnderstand
Processing

3
Dispatcher

SOAP
Request

Endpoint Listener

SOAP Protocol Binding

JAX-WS Runtime Services

Get WSDL

Web Service Client


(Java, .NET, PHP, etc.)

http://agileitinc.com

@WebService or
@WebServiceProvider
SEI
Meta-Data

Other
Implementation
Classes
(e.g., mapped
from WSDL or
user defined)

(e.g., WSDL,
Handler File,
Deployment
Descriptors)

DEMO
Contract First
With JAX-WS

Food For Thought .

What problems do we create for application


programmers if we use @WebService to
deploy Web Services?
Can we use @WebService to enable
production Java applications with Web
Services?

http://agileitinc.com

SOA Application Development Challenges

Too Much Mapping Code

JAX-WS/JAXB generated Java and WSDL leads


to multiple types for similar things (e.g.,
PurchaseOrder).
Lots of code (or XSLT) must be created and
maintained to map/translate between types.

Production Systems are often difficult or


impossible to modify by adding
@WebService type annotations.

http://agileitinc.com

A JAXB Mapping Problem (Impedance Mismatch)


XML

Java

<xs:schema ...
elementFormDefault="qualified"
targetNamespace="http://www.example.com/corp">
<xs:complexType name="AddressType">
<xs:sequence>
<xs:element name="addrLine1" type="xs:string"/>
<xs:element name="addrLine2" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="state" type="xs:string"/>
<xs:element name="zip" type="xs:string"/>
<xs:element name="phone" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>

public class Address implements


java.io.Serializable {

private
private
private
private
private
private
...

int streetNum;
String streetName;
String city;
State state;
int zip;
Phone phoneNumber;

public class Phone implements


java.io.Serializable {

private int areaCode;


private String exchange;
private String number;
...

http://agileitinc.com

Solution 1: Custom Mappings (DIY Recursion)


Class Foo
Class Bar1

Class Bar2

<complexType name=X>
...
<sequence>
<element name= E1
type=ns:Y/>
...
</sequence>
...
<attribute name=A2"
type=ns:Z/>
...
</complexType>

Serializer for <X, Foo>


(1) Serialize P1 to an
element E1 of type ns:Y
using Serializer for <Y, Bar1>

Property P1

(2) Serialize P2 to an
attribute A2 of type ns:Z
using Serializer for <Z, Bar2>

Property P2

recursive
serialization

Class Bar1

(3) Use JAXB to put together


element E1 and attribute
A2 into a JAXB representation
of Foo and the marshal out
to XML.

Serializer for <Y, Bar1>

...

...

<complexType name=Y>
...
</complexType>

recursive
serialization

http://agileitinc.com

Solution 2 Customization with XmlAdapter


Address
int streetNum;
String streetName;
String city;
State state;
int
zip;
Phone phone;

AddressAdapter
(XmlAdapter)
1

AddressXML
String
String
String
State
int
Phone

addrLine1;
addrLine2;
city;
state;
zip;
phone;

IntToStringAdapter
(XmlAdapter)
2

String
Phone
int
areaCode;
String exchange;
String number;

PhoneAdapter
(XmlAdapter)
3

<xs:complexType name="AddressType">
<xs:sequence>
<xs:element name="addrLine1"
type="xs:string"/>
<xs:element name="addrLine2"
type="xs:string"/>
<xs:element name="city"
type="xs:string"/>
<xs:element name="state"
type="xs:string"/>
<xs:element name="zip"
type="xs:string"/>
<xs:element name="phone"
type="xs:string"/>
</xs:sequence>
</xs:complexType>

String

http://agileitinc.com

Meet in the Middle

Start with WSDL and XML Schema


AND existing Java classes.
Two sides of the same problem:

Invoke the Web services using your existing Java classes


as parameters (e.g., PurchaseOrder).
Deploy your existing Java classes to provide Web services
that conform to the existing WSDL and XML Schema.

This is the most common scenario faced by


enterprises that are implementing SOA using Java
Web Services.

http://agileitinc.com

Java Programmers Need a Web Services Framework

Servlets/JSPs Struts
JAX-WS/JAXB ??? JWS Framework ???
A JWS Framework should provide two
capabilities:

Adapter Bindings
Endpoint Mirroring

http://agileitinc.com

Mapping Code Problem

Supplier1
Web Service

Supplier2
Web Service

PO1

Map1

PO2

Map2

Supplier2
Web Service

PO3

Map3

PO

http://agileitinc.com

Adapter Binding

WSDL

Adapter
Binding

Implements Meet in the Middle


Organizes, manages, maintains
the mapping code in a library of
reusable type mappings.
Hides the complexity of mapping
from business logic programmers.

Java

Meet in the
Middle
http://agileitinc.com

Endpoint Mirroring
SOAP

@WebService
Purchasing

Invoker

Production

Duplicate a production API with


a WS publishing system.
Bind the duplicate API to a WS
endpoint using JAX-WS or JAXRS.
No disruption of the production
system.

Purchasing

http://agileitinc.com

DEMO
ServiceLayerTM
Java-WS Framework

Ongoing Research

AgileIT is building a framework called


ServiceLayer for Adapter Bindings and
Mirroring
Community Edition of ServiceLayer will be
available as open source.
Contact me (Mark Hansen) if you are
interested in getting involved.

mark@agileitinc.com

http://agileitinc.com

Q&A

http://agileitinc.com

What is AJAX?

Asynchronous JavaScript
and XML
An Interaction Model
A Set of Technologies for
Rich Client Development
...
A Composite Application
Framework for Flexible
Business Process
Management ???

Ajax In Action, Dave Crane et al.,


Chapter 2 pg 33

http://agileitinc.com

SOA Using JWS and Ajax


Web Browser
1
retrieveURL(url)
(JavaScript Function)
XMLHttpRequest
3

7
4

showSearchingMsg()
(JavaScript Function)
2
processStateChange()
(JavaScript Function)
8

setData()
(Dojo FilteredTable
Function)
9

XML/
HTTP
Internet

5
REST Services
@WebServiceProvider
Provider<Source>
SOAShopper Standard
XML Schema

6
SOAShopper
Internals

eBay API
(SOAP)
Amazon API
(SOAP)
Yahoo API
(REST)

http://agileitinc.com

Internet

Java EE 5 Container

eBay Web
Services
Amazon Web
Service
Yahoo Shopping
Web Services

SOAShopper Architecture
Web Browser
(AJAX)

REST based
Consumer

WSDL/SOAP
based Consumer

POX

SOAP

Internet

Java EE 5 Container

WSDL

SOAShopper Standard
XML Schema

REST Endpoint
Binding REST Services
Provider<Source>

REST
Endpoint

@WebService
Provider

SOAShopper API

@WebService

SOAP
Endpoint

eBay Client
Binding
(SOAP)

eBay Web
Services

Amazon
Client
Binding
(SOAP)

Amazon Web
Service

Internet

SOAP Endpoint
Binding SOAP Services

Yahoo Client
Binding
(REST)

http://agileitinc.com

Yahoo
Shopping
Web Services

eBay WSDL

http://agileitinc.com

Ant Task to Compile eBay WSDL

http://agileitinc.com

Using the Generated eBay API

http://agileitinc.com

A Client Binding Example


SOAShopper API

public List<Offer> offerSearch(


String keywords, Category category,
Price lowprice, Price highprice) {
ShopperImp binding =
BindingService.getBinding(
ShopperImp.class,
EBayAPIInterface.class);

eBay Client
Binding

return
binding.offerSearch(keywords,
category, lowprice, highprice);

Internet
}

eBay Web Services

http://agileitinc.com

Meet in the Middle Service Integration Bridge


SOAShopper Object Model
bridge

Shopper
+offerSearch()

ComputerShopper

-imp

ShopperImp

+offerSearch()

CellphoneShopper
EBayShopperImp

AmazonShopperImp

eBay
Model
-port
EBayAPIInterface

Amazon
Model

Yahoo
Model

-port

-port

AWSECommerceService

http://agileitinc.com

YahooShopperImp

YahooRESTInterface

Meet in the Middle Object Integration Bridge


SOAShopper Object Model
bridge

Offer

-imp

+getSource()
+getThumbnail()
+getPrice()
+getSummary()
+getMerchantName()

ComputerOffer

CellphoneOffer

+getDiskSize()

+getNetwork()

EBayOfferImp

eBay
Model
-port
EBayAPIInterface

OfferImp
+isAuction()
+minimumToBid()

AmazonOfferImp

YahooOfferImp

Amazon
Model

Yahoo
Model

-port

-port

AWSECommerceService

http://agileitinc.com

YahooRESTInterface

Implementing a Binding Service

public abstract class BindingService {


public static <C> C getBinding(
Class<C> client, Class<?> service)
{
...
}
}

http://agileitinc.com

Demo
SOAShopper Integrating Yahoo!,
Amazon, and eBay

Thank you for your


attention

Additional Slides (Time


Allowing)

Flash Demo

http://agileitinc.com

Using the Dojo Table Widget

<table dojoType="filteringTable" id="fromSOAShopperData" multiple="true"


alternateRows="true" cellpadding="0" cellspacing="0" border="0"
style="margin-bottom:24px;">
<thead>
<tr>
<th field="source" dataType="String">Source</th>
<th field="thumbnail" dataType="html" align="center">Image</th>
<th field="price" dataType="String">Price</th>
<th field="summary" dataType="String">Summary</th>
<th field="url" dataType="html">Link</th>
</tr>
</thead>
</table>

http://agileitinc.com

Invoking the REST Endpoint


function retrieveURL(url) {
restURL = url;
showSearchingMsg(restURL);
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = processStateChange;
try {
req.open("GET", url, true);
req.setRequestHeader('Content-type','text/xml');
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
...
}
}

http://agileitinc.com

Loading the Dojo Table

function populateTableFromLiveSOAShopperData()
{
try {
var w =
dojo.widget.byId("fromSOAShopperData");
w.store.setData(theSOAShopperLiveData);
} catch(e) {
alert(e);
}
}
http://agileitinc.com

Potrebbero piacerti anche