Professional Documents
Culture Documents
StephanFischli
Winter2015/16
Objectives
Understandtheconceptofwebservices
Knowtherelevantstandardsofwebservices
KnowthedifferentJavaAPIsusedtorealizewebservices
Contents
1Introduction
2SOAPProtocolandAPI
3WebServicesDescriptionLanguage
4JavaAPIforXMLWebServices
5JavaAPIforRESTfulWebServices
1Introduction
Definition
WebServicesareselfcontained,modularapplicationsthatcanbe
described,published,locatedandinvokedoveranetwork,generallythe
WorldWideWeb.
(IBM,September2000)
Introduction
Motivation
Bottomupview:
Webservicesallowremoteprocedurecallsthroughfirewalls
Topdownview
Webservicesprovidethemeansforapplicationintegration,
especiallybetweenbusinesspartners
Historicalview:
Internet:networkofcomputers
WorldWideWeb:networkofdocuments
Webservices:networkofapplications
Introduction
Architecture
Webservicesusestandardizedprotocolsanddataformats(e.g.HTTP,
XML,SOAP)
Theaccessofawebserviceisindependentofitsimplementationand
deploymentplatform
Theservicedescriptionprovidesallthedetailsnecessarytoinvokea
webservice
WebServer
Client
SOAP
Library
Introduction
HTTP
SOAP
Web
Service
SOAP
Engine
JDBC
RMI
EJB
JMS
AppServer
DBServer
WebServiceModel
Theendpointinterfacedefinestheoperationsofawebservice
Abindingmapstheendpointinterfacetoaprotocolstack
Aportdefinestheendpointaddressthataclientcanusetoaccess
thewebservice
WebService
Client
WebService
EndpointInterface
SOAP
HTTP
SOAP
SMTP
Other
Binding
Port
Introduction
Standards
W3C(www.w3.org):
XMLandXMLSchema
SimpleObjectAccessProtocol(SOAP)
WebServicesDefinitionLanguage(WSDL)
OASIS(www.oasisopen.org)
UniversalDescription,DiscoveryandIntegration(UDDI)
ElectronicBusinessusingXML(ebXML)
WebServicesSecurity(WSS)
BusinessProcessExecutionLanguage(BPEL)
WSI(www.wsi.org)
Introduction
WebServicesInteroperabilityProfile
10
JavaAPIs
ApplicationCode
JavaAPIfor
XMLWebServices
SOAPwithAttach
mentsAPIforJava
JAXWS
JAXRS
SAAJ
JAXB
SOAP
WSDL
JavaAPIfor
RESTfulWebServices
JavaArchitecture
forXMLBinding
XML/HTTP
Introduction
11
References
Introduction
MartinKalin
JavaWebServices:UpandRunning,O'Reilly,2013
BillBurke
RESTfulJavawithJAXRS,O'Reilly,2013
12
2SOAPProtocol
Definition
SOAPisanXMLbasedcommunicationprotocolthatdefines
SOAP
thestructureofmessages(envelope)
bindingstotransportprotocols(e.g.HTTP)
encodingrulesfordatatypes
conventionsforremoteprocedurecalls
amechanismforerrorhandling
14
StructureofaSOAPMessage
Protocolwrapper
SOAPEnvelope
SOAPHeader
SOAPBody
Theenvelopeisthemessage
container
Theoptionalheadermaycontain
processingorroutinginformation
Thebodycontainsarbitrary
XMLdataoraSOAPfault
SOAP
15
ExampleofaSOAPMessage
POST /contactbook/soap HTTP/1.1
...
Content-Type: text/xml; charset=utf-8
Content-Length: 210
Host: distsys.ch:8080
SOAPAction: ""
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header/>
<soap:Body>
<tns:findContact xmlns:tns="http://example.org/contactbook">
<id>5</id>
</tns:findContact>
</soap:Body>
</soap:Envelope>
SOAP
16
SOAPMessageswithAttachments
SOAPPart
MIMEwrapper
SOAPEnvelope
SOAPHeader
SOAPBody
Attachment
Part
MIMEwrapper
Attachment
Attachmentsmaycontain
anynonXMLdata
SOAP
17
SOAPHeaders
SOAPHeadersarenotstandardizedandmaycontainadditional
informationsuchas
SOAP
authenticationandauthorization
transactionmanagement
tracingandauditing
paymentinformation
18
SOAPIntermediaries
SOAPintermediariesallowtorouteamessagetomultiplerecipients
Headerelementsmaybeassociatedtoaspecificrecipientbythe
actorattribute
ThemustUnderstandattributesayswhethertherecipientisrequired
toprocessthecorrespondingheaderelement
Requestor
Intermediary
Provider
SOAP
19
ExampleofaSOAPMessagewithHeader
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<tns:basicAuthentication xmlns:tns="http://example.org/contactbook"
soap:actor="urn:security" soap:mustUnderstand="1">
<username>admin</username>
<password>*****</password>
</tns:basicAuthentication>
</soap:Header>
<soap:Body>
<tns:createContact xmlns:tns="http://example.org/contactbook">
<name>John Doe</name>
<phone>+1 123-456-7890</phone>
<email>jd@example.org</email>
</tns:createContact>
</soap:Body>
</soap:Envelope>
SOAP
20
SOAPFaults
ProcessingerrorsofarequestarereportedthroughSOAPfaultsinthe
bodyoftheresponsemessage
SOAPEnvelope
SOAPBody
SOAPFault
FaultCode
FaultString
FaultActor
DetailObject
DefaultcodesareVersionMismatch,
MustUnderstand,ClientandServer
Descriptionoftheerror
Causeroftheerror(optional)
Errordetails(optional)
SOAP
21
ExampleofaSOAPMessagewithFault
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>Contact not found</faultstring>
<detail>
<tns:NotFoundFault xmlns:tns="http://example.org/contactbook">
Contact not found
</tns:NotFoundFault>
</detail>
</soap:Fault>
</soap:Body>
</soap:Envelope>
SOAP
22
SOAPwithAttachmentAPIforJava(SAAJ)
SAAJisasimpleAPIformanipulatingandsendingSOAPmessages
SAAJisespeciallysuitableforaccessingdocumentorientedweb
services
SAAJcanbeusedtoaccessawebserviceevenifitsoperationsare
unknownatcompiletime
SOAP
23
AnatomyofaSAAJMessage
ASAAJmessageconsistsofahierarchyofobjectsrepresentingthe
differentpartsoftheSOAPmessageandtheXMLelements
SOAPMessage
SOAPPart
SOAPEnvelope
SOAPHeader
SOAPHeaderElement
SOAPBody
SOAPElement
Text
AttachmentPart
SOAP
24
InterfacesandClasses
Thefollowinginterfacesandclassesareusedtobuiltthestructureofa
SAAJmessage
SOAPMessage
SOAPPart
getMimeHeaders()
getSOAPPart()
getSOAPHeader()
getSOAPBody()
createAttachmentPart()
writeTo()
getEnvelope()
SOAPEnvelope
getHeader()
getBody()
SOAPHeader
SOAPBody
addDocument()
addFault()
addHeaderElement()
SOAP
25
InterfacesandClasses(cont.)
ThefollowinginterfacesareusedtoconstructtheXMLcontentofaSAAJ
message
Node
get/setParentElement()
get/setValue()
detachNode()
SOAPElement
Text
getElementName()
addChildElement()
getChildElements()
add/removeAttribute()
addTextNode()
SOAP
26
CreatingaMessage
AnewlycreatedmessagecontainsaSOAPEnvelopewithanempty
SOAPHeaderandanemptySOAPBodyelement
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage request = factory.createMessage();
request.getSOAPHeader().detachNode();
SOAPBody body = request.getSOAPBody();
SOAP
27
AddingContenttoaMessage
ContentcanbeaddedtoamessagebycreatingaSOAPBodyElementand
addingchildelementstoit
String namespace = "http://example.org/contactbook";
SOAPElement bodyElement =
body.addChildElement("findContact", "tns", namespace);
SOAPElement idElement = bodyElement.addChildElement("id");
idElement.addTextNode(id);
SOAP
28
AddingaDocumenttoaMessage
Insteadofsettingthecontentofamessage,itispossibletoaddanentire
DOMdocumenttothebodyofamessage
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("findRequest.xml");
body.addDocument(document);
SOAP
29
SendingaMessage
AmessagecanbesentbycreatingaSOAPConnectionandprovidingthe
endpointaddressofthewebservice
String endpoint = "http://distsys.ch:8080/contactbook/soap";
SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
SOAPConnection connection = factory.createConnection();
SOAPMessage response = connection.call(request, endpoint);
connection.close();
SOAP
30
ReadingtheContentofaMessage
ThecontentofamessagecanbereadbyretrievingtheSOAPBody
Elementanditschildelements
SOAPBody body = response.getSOAPBody();
SOAPElement bodyElement = (SOAPElement)body.getFirstChild();
SOAPElement contactElement = (SOAPElement)bodyElement.getFirstChild();
Iterator<SOAPElement> iter = contactElement.getChildElements();
System.out.println("Name: " + iter.next().getValue());
System.out.println("Phone: " + iter.next().getValue());
System.out.println("Email: " + iter.next().getValue());
SOAP
31
ReadingFaultInformation
Ifamessagecontainsafault,itsinformationcanbereadbyretrieving
theSOAPFaultelementfromthebody
if (body.hasFault()) {
SOAPFault fault = body.getFault();
String faultCode = fault.getFaultCode();
String faultString = fault.getFaultString();
String faultActor = fault.getFaultActor();
Detail detail = fault.getDetail();
...
}
SOAP
32
3WebServicesDescriptionLanguage
(WSDL)
Introduction
WSDL
WSDLisanXMLlanguagethatisusedtodescribetheinterfaceofa
webservice
WSDLisplatform,protocolandprogramminglanguageindependent
TheWSDLdocumentofawebserviceispublishedatawellknown
URLorinaregistry
ProvidertoolscanparseWSDLandgeneratethecodenecessaryto
implementortoaccessawebservice
34
OverviewofWSDLDocument
AWSDLdocumentdescribesawebserviceintermsof
theoperationsthatthewebserviceprovides
thedatatypesthateachoperationrequiresbyitsinputand
outputmessages
thebindingthatmapstheinputandoutputmessagesontoa
protocol
theaddressatwhichtheservicecanbeaccessed
PortType
Operation
Service
Binding
Port
Message
WSDL
35
StructureofaWSDLDocument
<definitions xmlns="http://schemas.xmlsoap.org/wsdl/" ...>
<import ...>
<types>
<xsd:schema>...</xsd:schema>
</types>
<message name="findContact">...</message>
<message name="findContactResponse">...</message>
...
<portType name="ContactBook">
<operation name="findContact">...</operation>
...
</portType>
<binding>
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" ... />
...
</binding>
<service>
<port><soap:address location="..."/></port>
</service>
</definitions>
WSDL
36
Definitions
ThedefinitionselementistherootelementofaWSDLdocument
Thenamegiventothewebserviceisfordocumentationpurposeonly
Thetargetnamespacedeterminestowhichnamespacetheelements
belongusedtodescribethewebservice
<definitions name="ContactBookService"
xmlns="http://schemas.xmlsoap.org/wsdl/"
targetNamespace="http://example.org/contactbook"
xmlns:tns="http://example.org/contactbook"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
...
</definitions>
WSDL
37
Imports
Animportelementallowstoimportdatatypedefinitionsfroma
separateXMLschemadocument(notrecommended)
AnimportelementallowstoincludeanotherWSDLdocumentand
thustoseparatethegenericdefinitionofawebservicefromits
bindingsanditslocation
<import namespace="http://example.org/contactbook"
location="ContactBookTypes.xsd"/>
<import namespace="http://example.org/contactbook"
location="ContactBookGeneric.wsdl"/>
WSDL
38
DataTypes
Thetypeselementdefinesthedatatypesthatareusedinthe
messagesofthewebservice
ThedatatypesshouldbedefinedusingtheXMLschemalanguage
(eitherinlineorbyimportinganexternalschema)
<types>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://example.org/contactbook">
<element name="findContact" type="tns:findContact"/>
<complexType name="findContact">
<sequence><element name="id" type="long"/></sequence>
</complexType>
...
</schema>
</types>
WSDL
39
Messages
Themessageelementsdefinethemessagesusedbytheoperationsof
thewebservice
Eachmessagemaycontainanynumberofpartelementsthat
representanitemofdata
Thedatatypeofamessagepartisdeclaredbyanelementoratype
attributereferencingastandardtypeorauserdefinedtype
<message name="findContact">
<part name="parameters" element="tns:findContact"/>
</message>
<message name="findContactResponse">
<part name="parameters" element="tns:findContactResponse"/>
</message>
<message name="NotFoundFault">
<part name="fault" element="tns:NotFoundFault"/>
</message>
...
WSDL
40
ThePortType
TheportTypeelementdefinestheoperationsofawebservice
Eachoperationcanhaveaninput,anoutputandanynumberoffault
messages
<portType name="ContactBook">
<operation name="findContact">
<input message="tns:findContact"/>
<output message="tns:findContactResponse"/>
<fault message="tns:NotFoundFault" name="NotFoundFault"/>
</operation>
...
</portType>
WSDL
41
OperationTypes
Theappearanceandorderoftheinputandoutputmessagesdetermine
thetypeofanoperation
Type
RequestResponse
OneWay
SolicitResponse*
Notification*
Messages
Input,Output,Fault
Input
Output,Input,Fault
Output
*NotsupportedbyWSIandJAXWS
WSDL
42
ProtocolBindings
Thebindingelementsdefineforeachporttypehowtheinputand
outputmessagesofitsoperationsaremappedtoconcreteprotocol
messages
Theadditionalelementsnecessaryforaconcretebindingaredefined
byindividualprotocolspecifications
<binding name="ContactBookBinding" type="tns:ContactBook">
...
<operation name="findContact">
...
<input>...</input>
<output>...</output>
<fault>...</fault>
</operation>
...
</binding>
WSDL
43
TheSOAPBinding
TheSOAPbindingdefines
thetransportprotocolusedtocarrytheSOAPmessages
thestyleoftheoperations(documentorRPC)
thevalueoftheSOAPActionheaderusedtoaccesstheservice
theappearance(bodyorheader)andencoding(literalorencoded)of
eachmessage
<binding ...>
<soap:binding style="document"
transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="findContact">
<soap:operation soapAction=""/>
<input><soap:body use="literal"/></input>
<output><soap:body use="literal"/></output>
<fault><soap:fault use="literal" name="NotFoundFault"/></fault>
</operation>
</binding>
WSDL
44
OperationStyles
ThestyleofanoperationdetermineshowtheSOAPmessagesare
constructedfromtheWSDLdescription
Document:
thebodycontainsoneormorechildelementsthatcorrespondto
thepartsofthecorrespondingmessage
thepartelementsintheWSDLdocumentpointtoschema
elements,thereforethemessagebodycaneasilybevalidated
thebodyconsistsofasingle(wrapper)elementnamedforthe
operationbeinginvoked
thewrapperelementcontainsachildelementforeachparameter
definedbythepartsofthecorrespondingmessage
RPC:
Therecommendedstyleisdocumentwrapped
WSDL
45
MessageEncodings
Theencodingrulesofamessagedeterminestheserializationformatof
themessageparts
Literal:
dataisserializedaccordingtoaschemadefinitionusually
expressedintheXMLschemalanguage
thetypesoftheelementsintheSOAPmessageimplicitlyrelyon
theschema
Encoded:
WSDL
dataisserializedaccordingtosomeencodingrulesusuallythe
SOAPsection5rules
theelementsintheSOAPmessagecarryexplicittype
qualification
46
TheEndpointAddress
AportelementmapsabindingofaporttypetoaURIwhichcanbe
usedtoaccessit
Aserviceelementgroupstogetherasetofrelatedports
<service name="ContactBookService">
<port name="ContactBookPort" binding="tns:ContactBookBinding">
<soap:address location="http://distsys.ch:8080/contactbook/soap"/>
</port>
</service>
WSDL
47
4JavaAPIforXMLWebServices
(JAXWS)
Introduction
JAXWS
JAXWSprovidesahighlevelAPIfortheimplementationofweb
servicesandwebserviceclients
JAXWSmapsawebserviceendpointinterfacegiveninWSDLtoa
Javainterfaceandviceversa
JAXWSdelegatesthemappingofJavadatatypestoandfromXML
definitionstoJAXB
JAXWSisbasedonstandardtechnologiesandsupportstheWSI
BasicProfile
50
JAXWSArchitecture
Client
Application
Service
Implementation
Stub
Tie
JAXWS
Runtime
JAXWS
Runtime
SOAPMessages
HTTPTransport
TheclientinvokesastubmethodwhichisdelegatedtotheJAXWS
runtimeinordertosendanappropriateSOAPmessagetotheserver
Ontheserverside,thetieconvertsthereceivedmessagebackintoa
methodcallontheactualserviceimplementation
Thestubandtieclassesaredynamicallygeneratedbytheprovider
platform
JAXWS
51
UsingWSDLwithJAXWS
JAXWScangenerateaWSDLdocumentfromtheJava
implementationofawebservice(codefirst)
JAXWScanimportaWSDLdocumenttogeneratetheJavacode
requiredtoimplementawebserviceorawebserviceclient(contract
first)
WSDL
wsimport
Client
JAXWS
Service
Interface
wsgen
Service
Impl
52
JavatoWSDLMapping
Javapackagesaremappedtonamespaces
JavaclassesaremappedtoportTypeelements
Javamethodsaremappedtooperationelementswithcorresponding
inputandoutputmessages
Javaexceptionsaremappedtofaultelements
public class ContactBook {
public Contact findContact(long id) throws NotFoundFault { ... }
}
<wsdl:portType name="ContactBook">
<wsdl:operation name="findContact">
<wsdl:input message="tns:findContact"/>
<wsdl:output message="tns:findContactResponse"/>
<wsdl:fault message="tns:NotFoundFault"/>
</wsdl:operation>
</wsdl:portType>
JAXWS
53
DevelopingaCodefirstWebService
1. Implementandcompilethewebserviceclass
2. OptionallygeneratetheWSDLdocumentusingthewsgenutility
3. Packagetheservicecodeintoawebarchive
4. Deploythewebarchiveintoarunningwebcontainer
ContactBook
WebService
Contact
NotFoundFault
JAXWS
54
TheWebServiceClass
Thewebserviceclassmustbeannotatedwiththe@WebService
annotationwhichdefinesthenamesandthetargetnamespaceofthe
webservice
The@SOAPBindingannotationcanbeusedtospecifytheoperation
styleandmessageencoding
@WebService(name="ContactBook",
portName="ContactBookPort", serviceName="ContactBookService",
targetNamespace="http://example.org/contactbook")
@SOAPBinding(style=DOCUMENT, use=LITERAL,
parameterStyle=WRAPPED)
public class ContactBookWebService {
...
}
JAXWS
55
TheWebServiceLifecycle
Thewebserviceclassmusthaveapublicnoargumentconstructor
The@PostConstructand@PreDestroyannotationscanbeusedfor
lifecyclecallbackevents
ResourcescanbeobtainedbyJNDIlookuporbyinjection
@WebService(...)
public class ContactBookWebService {
@PostConstruct
protected void init() { ... }
@PreDestroy
protected void destroy() { ... }
...
}
JAXWS
56
TheWebServiceMethods
ThemethodsofawebservicemusthaveJAXBcompatibleparameters
andreturntypes
The@WebMethod,@WebParamand@WebResultannotationscan
beusedtocustomizethemappingofthemethodnames,parameters
andreturnvalues
@WebService(...)
public class ContactBookWebService {
@WebMethod(operationName="findContact")
@WebResult(name="contact")
public Contact findContact(@WebParam(name="id") long id)
throws NotFoundFault {
...
}
}
JAXWS
57
Exceptions
JAXWSexceptionsalwayscontainafaultinformationinadditionto
theerrormessage
The@WebFaultannotationdefinesthenameofthefaultinformation
andshouldmatchthenameoftheexception
@WebFault(name="NotFoundFault")
public class NotFoundFault extends Exception {
public NotFoundFault(String message) {
super(message);
}
public String getFaultInfo() { return getMessage(); }
}
JAXWS
58
OnewayOperations
Ifanoperationhasnoreturnvalueandthrowsnoexceptions,itcan
beannotatedwiththe@OneWayannotation
Whenaclientinvokesaonewayoperation,itimmediatelyreturns
anddoesnothavetowaitfortheprocessingoftheoperation
@WebService(...)
public class ContactBookWebService {
...
@Oneway @WebMethod(...)
public void deleteContact(@WebParam(name="id") long id) { ... }
}
JAXWS
59
DevelopingaWebServiceClient
1. Generatetheartifactsneededtoconnecttothewebserviceusing
thewsimportutility
2. Implementandcompiletheclientapplication
3. Runtheclient
Service
ContactBook
Service
ContactBook
Client
ContactBook
Contact
NotFoundFault
JAXWS
60
GenerationofClientArtifacts
ThewsimporttoolreadstheWSDLdocumentofawebserviceand
generatestheportableartifactsusedtoimplementaclient
Thecodegenerationcanbecustomizedbycommandlineoptionsand
byprovidingabindingsfile
Thegeneratedfilesincludeaservicefactory,theendpointinterface
andwrapperclasses
wsimport -d build -s generated
-p org.contacts.soap -b bindings.xml
http://distsys.ch:8080/contactbook/soap?wsdl
JAXWS
61
GenerationofClientArtifacts(cont.)
BindingdeclarationscanbeusedtocustomizetheWSDLtoJava
mapping,e.g.togenerateasynchronousmethods,todisablethe
generationofwrapperstylemethods,ortoconfigurehandlerchains
<bindings xmlns="http://java.sun.com/xml/ns/jaxws">
<enableAsyncMapping>true</enableAsyncMapping>
<enableWrapperStyle>false</enableWrapperStyle>
<handler-chains>...</handler-chains>
...
</bindings>
JAXWS
ThegeneratedservicefactorycontainstheURLoftheWSDL
documentwhichisparsedagainatruntime,butthewsdlLocation
optioncanbeusedtoconfigurealocalpath
62
TheClientImplementation
Theclientcreatesaservicefactoryobject,obtainsastubfromitand
invokesitsmethods
Optionally,thedefaultendpointaddressofthestubcanbe
overriddenusingtheBindingProviderinterface
public class ContactBookClient {
private static String endpoint = "http://distsys.ch:8080/contactbook/soap";
public static void main(String[] args) throws Exception {
ContactBookService service = new ContactBookService();
ContactBook contactBook = service.getContactBookPort();
((BindingProvider)contactBook).getRequestContext().put(
ENDPOINT_ADDRESS_PROPERTY, endpoint);
Contact contact = contactBook.findContact(id);
...
}
}
JAXWS
63
DevelopingaContractfirstWebService
1. ProvidetheWSDLdocumentofthewebservice
2. GeneratetheJavaserviceinterfaceandportableartifactsusingthe
wsimportutility
3. Implementthegeneratedwebserviceinterfaceandcompiletheweb
serviceclass
4. PackagetheservicecodeandoptionallytheWSDLdocumentintoa
webarchive
5. Deploythewebarchiveintoarunningwebcontainer
@WebService(endpointInterface="org.contacts.soap.ContactBook",
wsdlLocation="ContactBook.wsdl", ...)
public class ContactBookWebService implements ContactBook {
...
}
JAXWS
64
AdvancedFeatures
MessageHandlersareinterceptorswhichcanbeusedforadditional
processingofmessages(e.g.logging,filtering,security)
BydefaultthereisnoschemavalidationofSOAPmessagesbutthe
proprietary@SchemaValidationannotationoftheJAXWSreference
implementationcanbeappliedtowebserviceclasses
Clientscaninvokewebserviceoperationsasynchronously,eitherby
pollingorbyusingacallback
TheProviderandDispatchinterfacesallowwebserviceendpointsand
webserviceclientstoworkatthemessagelevel
TheMessageTransmissionandOptimizationMechanism(MTOM)
specifieshowXMLbinarydatacanbesendasattachment
JAXWS
65
MessageHandlers
Protocolhandlersarespecifictoaprotocolandcanaccessorchange
anypartofthemessagesinparticularmessageheaders
Logicalhandlersareprotocolagnosticandonlyactonthepayloadof
themessages
Handlersaregroupedintohandlerchainswhichareinsertedinthe
processingpathontheclient,theserverorboth
Foranoutboundmessagethelogicalhandlersareexecutedbefore
theprotocolhandlers,foraninboundmessageviceversa
JAXWS
JAXWS
Client
Service
Runtime
JAXWS
Runtime
66
WritingaMessageHandler
AmessagehandlermustimplementtheSOAPHandlerorthe
LogicalHandlerinterface
Themessagecontextpassedtothehandlemethodscontainsa
SOAPMessageoraLogicalMessagewhichcanbemanipulatedusing
SAAJorJAXB,respectively
Thebooleanreturnvaluesindicatewhethertocontinueprocessingof
thehandlerchainornot
public class LoggingHandler
implements SOAPHandler<SOAPMessageContext> {
public boolean handleMessage(SOAPMessageContext context) {
SOAPMessage message = context.getMessage();
if (!(Boolean) context.get(MESSAGE_OUTBOUND_PROPERTY))
message.writeTo(System.out);
return true;
}
...
}
JAXWS
67
ConfiguringaMessageHandler
Amessagehandlerispartofahandlerchainwhichisdefinedinan
XMLdeploymentdescriptor
<handler-chains xmlns="http://java.sun.com/xml/ns/javaee">
<handler-chain>
<handler>
<handler-name>LoggingHandler</handler-name>
<handler-class>org.contacts.soap.LoggingHandler</handler-class>
</handler>
</handler-chain>
</handler-chains>
Ahandlerchaincanbeassociatedwithawebservicethroughthe
@HandlerChainannotationwhichreferencesthedescriptor
@WebService(...)
@HandlerChain(file="handler-chain.xml")
public class ContactBookWebService { ... }
JAXWS
68
AsynchronousClients
Whengeneratingtheclientartifacts,abindingdeclarationcanbe
usedtogenerateasynchronousmethods,oneforpollingandone
usingcallbacks
@WebService(...)
public interface ContactBook {
public Contact findContacts(long id);
public Response<FindContactResponse> findContactAsync(long id);
public Future<?> findContactAsync(
String name, AsyncHandler<FindContactResponse> asyncHandler);
...
}
JAXWS
69
AsynchronousPolling
Theclientinvokesthepollingmethodonthestubandrepeatedly
checksforaresponseonthereturnedResponseobject
public class ContactBookClient {
public static void main(String[] args) {
ContactBookService service = new ContactBookService();
ContactBook contactBook = service.getContactBookPort();
Response<FindContactResponse> response =
contactBook.findContactAsync(long id);
while (!response.isDone()) {
...
}
Contact contact = response.get().getContact();
...
}
}
JAXWS
70
AsynchronousCallback
TheclientprovidesanAsyncHandlerobjectwhichwillbecalledas
soonastheresponseisavailable
public class ContactBookClient {
public static void main(String[] args) {
ContactBookService service = new ContactBookService();
ContactBook contactBook = service.getContactBookPort();
contactBook.findContactAsync(name, new FindContactHandler());
...
}
}
public class FindContactHandler
implements AsyncHandler<FindContactResponse> {
public void handleResponse(Response<FindContactResponse> response) {
Contact contact = response.get().getContact();
...
}
}
JAXWS
71
WebServicesandEJB
Statelesssessionbeanscanbeexposedaswebservicesbyannotating
thebeanwiththe@WebServiceannotationorbydefiningaseparate
webserviceinterfacewhichisimplementedbythebean
Inanyenterprisebean,the@WebServiceRefannotationcanbeused
toinjecttheservicefactoryofawebserviceordirectlytheweb
serviceinterfacetype
@Stateless
public class AdminServiceBean implements AdminService {
@WebServiceRef(ContactBookService.class)
private ContactBook contactBook;
...
}
JAXWS
72
WebServiceEndpointAddress
Forservletbasedwebservicesthedefaultendpointaddressis
http://<host>:<port>/<context-root>/<servlet-url-mapping>
IfthereisnoservlettoURLmappinginthewebdeployment
descriptor,theserviceNameattributeofthe@WebService
annotationisusedinstead
ForEJBbasedwebservicesthedefaultendpointaddressis
http://<host>:<port>/<service-name>/<port-type-name>
wheretheserviceandporttypenamesaretakenfromthe
serviceNameandnameattributesofthe@WebServiceannotation
JAXWS
73
5JavaAPIforRESTfulWebServices
(JAXRS)
Introduction
JAXRS
REST(representationalstatetransfer)isanarchitecturalstyleinwhich
dataandfunctionalityareconsideredresources
ThefundamentalprinciplesofRESTare
addressability:everyresourceisreachablethroughaunique
identifier(URI)
state:resourceshavestatebutthecommunicationwiththe
serverisstateless
uniforminterface:resourcesaremanipulatedbyafinitesetof
operations(HTTPmethods)
representationoriented:resourcesmayhavedifferent
representations(MIMEtypes)
HATEOAS(hypermediaastheengineofapplicationstate):
clientscaninteractwithresourcesusinghyperlinksprovidedby
theserver
76
UniformInterface
WithaRESTfulwebservice,HTTPmethodsareusedtoprocessthe
resources
Method
Purpose
Safe
Idempotent
POST
Createaresource
no
no
GET
Readaresource
yes
yes
PUT
Createorupdatearesource
no
yes
DELETE
Deletearesource
no
yes
HEAD
Getinformationonaresource
yes
yes
OPTIONS
Getcommunicationoptions
yes
yes
IncontrasttothePOSTmethod,theclientknowstheidentityofthe
resourceitiscreatingorupdating,whenusingthePUTmethod
JAXRS
77
JAXRSDevelopment
JAXRS
JAXRSisaJavaAPIdesignedtodevelopRESTfulwebservices
Javaclassesareannotatedtodefineresourcesandtheactionstobe
performedonthoseresources
HTTPrequestsaredispatchedtoJavamethodsdependingonthe
method,pathandmimetypeoftherequests
Resourceclassesandartifactsarepackagedintoawebarchiveand
deployedtoaJavaEEserver
78
JAXRSAnnotations
Annotation
Description
@Path
relativeURIoftheresource
@POST,@GET
@PUT,@DELETE
@HEAD,@OPTIONS
methoddesignatorsindicatingtheHTTP
requesttypetobeprocessed
@Path,@Query
@Form,@Header
@CookieParam
parameterstobeextractedfromtheHTTP
requestforuseintheresourceclass
@Consumes
@Produces
MIMEmediatypesofrepresentationsa
resourcecanconsumeorproduce
@Provider
informationfortheJAXRSruntimesuchas
messagebodyreaderandwriter
@Context
informationrelatedtoarequest
JAXRS
79
ThePathAnnotation
The@PathannotationidentifiesthepartialURIpathofaresource
andcanbespecifiedattheclassandmethodlevel
Thepathofamethodisappendedtothepathoftheserviceclass
ThepathsareinterpretedrelativetotheURLoftheserver,the
contextrootandtheapplicationpath
Apathmaycontainvariableswhosevaluesaremappedtomethod
parametersusingthe@PathParamannotation
@Path("contacts")
public class ContactBookResource {
@Path("{id}")
public Contact findContact(@PathParam("id") long id) { ... }
...
}
JAXRS
80
RequestMethodAnnotations
Therequestmethodannotations(@POST,@GET,@PUT,@DELETE)
areusedtomapHTTPrequeststocorrespondingmethodsofthe
resourceclass
Theresourcemethodsmustreturnvoid,aJavatypeoraResponse
object
@Path("contacts")
public class ContactBookResource {
@GET @Path("{id}")
public Contact findContact(@PathParam("id") long id) { ... }
@POST
public long addContact(Contact contact) { ... }
@PUT @Path("{id}")
public void updateContact(Contact contact) { ... }
@DELETE @Path("{id}")
public void deleteContact(@PathParam("id") long id) { ... }
}
JAXRS
81
MediaTypeAnnotations
The@Consumesand@ProducesannotationsspecifytheMIME
mediatypesaresourcecanconsumeorproduce
Aclientspecifiesthemediatypeofrequestorresponsedatausing
theHTTPheadersContentTypeandAccept
Ifaresourceisnotabletoconsumeortoproducetherequested
mediatype,anHTTPerrorstatus(unsupportedmediatype,not
acceptable)isreturned
@Path("contacts")
public class ContactBookResource {
@POST
@Consumes({APPLICATION_XML, APPLICATION_JSON})
@Produces(TEXT_PLAIN)
public long addContact(Contact contact) { ... }
...
}
JAXRS
82
ParameterbasedAnnotations
Parametersofaresourcemethodmaybeannotatedtoextract
informationfromtheHTTPrequest
Annotation
ParameterSource
@PathParam
RequestURIpath
@QueryParam
RequestURIquery
@FormParam
RequestURIpathorbody
@HeaderParam
HTTPheaders
@CookieParam
Cookierelatedheaders
Parameterswhicharenotannotated,aremappedfromtheHTTP
requestbody(entityparameters)
@GET
public List<Contact> searchContacts(@QueryParam("name") String name) { ... }
JAXRS
83
ExceptionHandling
Ifanerroroccursinaresourcemethod,aWebApplicationException
canbethrownwhichproducesanHTTPerrorresponse
@GET @Path("id")
public Contact findContact(@PathParam("id") long id) {
try { return contactBook.find(id); }
catch (NotFoundException ex) {
throw new WebApplicationException(ex.getMessage(),
Response.status(NOT_FOUND).entity(ex.getMessage()).build());
}
}
JAXRS
84
EntityProviders
Messagebodyreadersandwriterssupplymappingsbetween
representationsofresourcesandtheircorrespondingJavatypes
JAXRSsupportssomestandardtypessuchasbyte[],StringandJAXB
classeswhicharemappedautomatically
@Provider
@Produces("text/csv")
public class CSVMessageWriter
implements MessageBodyWriter<List<Contact>> {
public void writeTo(List<Contact> contacts, ..., OutputStream stream) {
PrintWriter writer = new PrintWriter(stream);
for (Contact c : contacts)
writer.println(c.getName() + "," + c.getPhone() + "," + c.getEmail());
writer.flush();
}
...
}
JAXRS
85
ContextInformation
The@Contextannotationcanbeusedtoobtaininformationabout
theHTTPrequest
@Path("contacts")
public class ContactBookResource {
@Context Request request;
@Context UriInfo uriInfo;
@Context HttpHeaders headers;
...
private void log() {
System.out.println(request.getMethod());
System.out.println(uriInfo.getRequestUri());
System.out.println(headers.getRequestHeaders());
}
}
JAXRS
86
ApplicationConfiguration
TheresourcesandprovidersofaJAXRSapplicationmustbe
configuredviaasubclassofApplication
The@ApplicationPathannotationisusedtospecifytheapplication
pathwhichwillbepartoftheresources'URIs
@ApplicationPath("rest")
public class ApplicationConfig extends Application {
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<>();
classes.add(ContactBookResource.class);
classes.add(CSVMessageWriter.class);
return classes;
}
}
JAXRS
87
RESTfulWebServiceClientAPI
JAXRSprovidesastandardizedclientAPItoeasilyconsumeRESTful
webservices
AclientapplicationfirstcreatesaninstanceoftheClientclasswhich
configuresandmanagestheHTTPconnections
TheClientobjectisalsoafactoryforWebTargetobjectswhich
encapsulateresourcesidentifiedbyaURI
String resourceURI = "http://distsys.ch:8080/contactbook/rest/contacts"
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target(resourceURI);
JAXRS
88
SendingaRequest
TheWebTargetobjectcanbeusedtospecifytherelativepathofthe
resourceandqueryparameters
Whenbuildingtherequest,theacceptedresponsemediatypesand
otherheaderscanbeadded
Finally,theHTTPmethodisinvoked,possiblypassinganEntityobject
whichwillbeincludedintherequestbody
webTarget.path(id).request(APPLICATION_XML).get();
webTarget.queryParam("name", name).request(APPLICATION_XML).get();
webTarget.request(TEXT_PLAIN).post(Entity.xml(contact));
webTarget.path(id).request().put(Entity.xml(contact));
webTarget.path(id).request().delete();
JAXRS
89
ReceivingaResponse
TheinvocationoftheHTTPmethodreturnsaResponseobjectfrom
whichtheresponsestatusandheaderscanbeobtained
Inordertogetaresponsebody,thereadEntitymethodisinvoked
passingtheobjecttypeofthebody
Response response = webTarget.path(id).request(APPLICATION_XML).get();
if (response.getStatus() == Status.OK.getStatusCode()) {
Contact contact = response.readEntity(Contact.class);
...
}
JAXRS
90
AdvancedFeatures
JAXRS
ExceptionmapperscanbeusedtomapexceptionstoHTTPresponses
ServersideasynchronousHTTPallowstoimplementlongpolling
interfacesorserversidepush
WithasynchronousclientAPI,clientapplicationsobtaintheHTTP
responseusingpollingoracallback
FiltersallowtomodifyorprocessincomingandoutgoingHTTP
messages
EntityInterceptorsareconcernedwiththemarshalingand
unmarshalingofmessagebodies
91