java web services training-12 13 october 2015
TRANSCRIPT
-
7/26/2019 Java Web Services Training-12 13 October 2015
1/120
Java Web Services Training- Sandeep Satheesh
Oct 12 & 13, 2015
-
7/26/2019 Java Web Services Training-12 13 October 2015
2/120
What Are Web Services?
As the name suggests, a web service is a kind of webified
application, that is, an application typically delivered overHTTP (Hyper Text Transport Protocol).
A web service is thus a distributed application whose
components can be deployed and executed on distinctdevices.
-
7/26/2019 Java Web Services Training-12 13 October 2015
3/120
Web services can be divided roughly into two groups,
SOAP-based and REST-style.
The distinction is not sharp because, a SOAP-basedservice delivered over HTTP is a special case of a REST-
style service.
-
7/26/2019 Java Web Services Training-12 13 October 2015
4/120
SOAP originally stood for Simple Object Access Protocol.
SOAP is officially no longer an acronym.
SOAP is just anXML dialect in which documents aremessages.
-
7/26/2019 Java Web Services Training-12 13 October 2015
5/120
the SOAP is mostly unseen infrastructure
Request/ Response message exchange pattern (MEP)
-
7/26/2019 Java Web Services Training-12 13 October 2015
6/120
REST stands for REpresentational State Transfer.
-
7/26/2019 Java Web Services Training-12 13 October 2015
7/120
Key to web service interoperability
A major appeal of web services is language transparency:
the service and its clients need not be written in the samelanguage.
-
7/26/2019 Java Web Services Training-12 13 October 2015
8/120
If a SOAP-based web service written in Java can have a
Perl or a Ruby consumer, there must be an intermediarythat handles the differences in data types between theservice and the requester languages.
XML technologies, which support structured document
interchange and processing, act as the intermediary.
-
7/26/2019 Java Web Services Training-12 13 October 2015
9/120
Several features distinguish web services from other
distributed software systems. Here are three:Open infrastructure
Language transparency
Modular design
-
7/26/2019 Java Web Services Training-12 13 October 2015
10/120
What Good Are Web Services?
Language- and Platform-neutral.
Web services are inherently distributed systems thatcommunicate mostly over HTTP.
The communication payloads of web services arestructured text (that is, XML documents), which can beinspected, transformed, persisted, and otherwiseprocessed with widely and even freely available tools.
Web services also can deliver binary payloads.
-
7/26/2019 Java Web Services Training-12 13 October 2015
11/120
A First Example
The Service Endpoint Interface and Service
Implementation Bean
rpc.ts.TimeServerrpc.ts.TimeServerImplrpc.ts.TimeServerPublisher
-
7/26/2019 Java Web Services Training-12 13 October 2015
12/120
Testing the Web Service with a Browser
.
.
-
7/26/2019 Java Web Services Training-12 13 October 2015
13/120
A Java Requester of the Web Service
rpc.ts.client.TimeClient
-
7/26/2019 Java Web Services Training-12 13 October 2015
14/120
The Hidden SOAP - HTTP request for the TimeServer service
POST http://127.0.0.1:9876/ts HTTP/ 1.1
Accept: text/xml
Accept: multipart/*
Accept: application/soap
Content-Length: 434
Content-Type: text/xml; charset=utf-8
SOAPAction: "
http://ts.ch01/http://ts.ch01/ -
7/26/2019 Java Web Services Training-12 13 October 2015
15/120
The Hidden SOAP - HTTP response from the TimeServer service
HTTP/1.1 200 OK
Content-Length: 323
Content-Type: text/xml; charset=utf-8
Client-Date: Mon, 1 Jun 2015 02:12:54 GMT
Client-Peer: 127.0.0.1:9876
Client-Response-Num: 1
Mon Jun 1 14:12:54 CST 2015
-
7/26/2019 Java Web Services Training-12 13 October 2015
16/120
Whats Clear So Far?
The web service operations should appear to the requester
as independent and self-contained.
-
7/26/2019 Java Web Services Training-12 13 October 2015
17/120
MEP
Request/Response
One-Way
Notification
Solicit/Response
Infrastructure needed
Message transport
Service contract
Type system
-
7/26/2019 Java Web Services Training-12 13 October 2015
18/120
An Example with Richer Data Types
1. The source files are compiled in the usual way.
2. In the working directory, invoke the wsgen utility, whichcomes with core Java 6:
% wsgen -cp . document.team.Teams
3. Execute the TeamsPublisher application.
4. In the src directory, invoke the wsimport utility, whichlikewise comes with core Java 6:
% wsimport -p client -keep http://localhost:8888/teams?wsdl
5.Client Code document.team.*teamC.TeamClient
http://localhost:8888/teams?wsdlhttp://localhost:8888/teams?wsdl -
7/26/2019 Java Web Services Training-12 13 October 2015
19/120
WSDL
Package inversion
-
7/26/2019 Java Web Services Training-12 13 October 2015
20/120
Generating Client-Support Code from a WSDL
Wsimport
Try it for TimeServer example!
client.*
-
7/26/2019 Java Web Services Training-12 13 October 2015
21/120
Steps
First, construct a Service object.
Invoke the get...Port method on the constructed Serviceobject.
-
7/26/2019 Java Web Services Training-12 13 October 2015
22/120
The @WebResult Annotation
@WebService
@SOAPBinding(style = Style.RPC) // more on this laterpublic interface TimeServer {
@WebMethod
@WebResult(partName = "time_response")
String getTimeAsString();
@WebMethod
@WebResult(partName = "time_response")
long getTimeAsElapsed();}
-
7/26/2019 Java Web Services Training-12 13 October 2015
23/120
Result
-
7/26/2019 Java Web Services Training-12 13 October 2015
24/120
Result
The SOAP response
document from the web service likewise reflects the change:
Mon Jun 1 21:20:09 CDT 2015
-
7/26/2019 Java Web Services Training-12 13 October 2015
25/120
WSDL Structure
At a high level, a WSDL document is a contract between a
service and its consumers.The contract provides such critical information as theservice endpoint, the service operations, and the datatypes required for these operations.
The service contract also indicates, in describing themessages exchanged in the service, the underlyingservice pattern, for instance, request/response orsolicit/response.
-
7/26/2019 Java Web Services Training-12 13 October 2015
26/120
The types section, which is optional, provides data type
definitions under some data type system such as XMLSchema.
The message section defines the messages that
implement the service.
The portType section presents the service as namedoperations, with each operation as one or more messages.
The binding section is where the WSDL definitions go fromthe abstract to the concrete.
-
7/26/2019 Java Web Services Training-12 13 October 2015
27/120
style use
document Literaldocument Encoded
Rpc Literal
rpc encoded
Of the four possible combinations listed, only two occur regularly incontemporary SOAP-based web services: document/literal and rpc/literal. Forone thing, the encoded use, though valid in a WSDL document, does notcomply with the WS-I (Web Services-Interoperability) guidelines (see http://www.ws-i.org).
-
7/26/2019 Java Web Services Training-12 13 October 2015
28/120
Key Features of Document-Style Services
The document style indicates that a SOAP-based web
services underlying messages contain full XMLdocuments;
By contrast, the rpc style indicates that the underlyingSOAP messages contain parameters in the request
messages and return values in the response messages.
-
7/26/2019 Java Web Services Training-12 13 October 2015
29/120
Under the rpc-style, the messages carry the names of the
@WebMethods; under the document-style, there is anadded level of complexity in that the messages carry the
names of XSD types defined in the WSDLs types section.
Under the rpc style, the messages are named but notexplicitly typed; under the document style, the messagesare explicitly typed in an XSD document.
-
7/26/2019 Java Web Services Training-12 13 October 2015
30/120
From an architectural perspective, the document style is
the simpler of the two in that the body of a SOAP messageis a self-contained, precisely defined document. The rpcstyle requires messages with the names of the associatedoperations (in Java, the @WebMethods) with parameters
as subelements.
From a developer perspective, however, the rpc style isthe simpler of the two because the wsgen utility is not
needed to generate Java types that correspond to XMLSchema types.
-
7/26/2019 Java Web Services Training-12 13 October 2015
31/120
Finally, the use attribute determines how the services data
types are to be encoded and decoded. The WSDL servicecontract has to specify how data types used in theimplementation language (for instance, Java) areserialized to WSDL-compliant types (by default, XML
Schema types).
-
7/26/2019 Java Web Services Training-12 13 October 2015
32/120
The setting:
use = 'literal'means that the services type definitions literally follow theWSDL documents XML Schema.
By contrast, the setting:
use = 'encoded'
means that the services type definitions come fromencoding rules, typically the encoding rules in the SOAP1.1 specification.
-
7/26/2019 Java Web Services Training-12 13 October 2015
33/120
On the receiving end, a document-style SOAP message
can be validated straightforwardly against the associatedXML Schema. In rpc-style, by contrast, the validation istrickier precisely because there is no associated XMLSchema.
-
7/26/2019 Java Web Services Training-12 13 October 2015
34/120
The Wrapped and Unwrapped Document Styles
The gist of the wrapped convention, which is unofficial but
widely followed, is to give a document-style service thelook and feel of an rpc-style service. The wrappedconvention seeks to combine the benefits of document andrpc styles.
-
7/26/2019 Java Web Services Training-12 13 October 2015
35/120
Unwrapped document style
27
94
Wrapped document style
27
94
G f
-
7/26/2019 Java Web Services Training-12 13 October 2015
36/120
Guidelines for the wrapped document convention
The SOAP envelopes body should have only one part, that is, it should contain a single XML elementwith however many XML subelements are required.
The relationship between the WSDLs XSD and the single XML element in the SOAP body is welldefined.
The XML elements in the XSD serve as the wrappers for the SOAP message body.
The request wrapper has the same name as the service operation (for instance, addNums), and theresponse wrapper should be the request wrappers name with Response appended (for instance,addNumsResponse).
The WSDL portType section now has named operations (e.g., getTimeAsString) whose messagesare typed.
By default, a Java SOAP-based web service is wrapped doc/lit, that is, wrapped document style withliteral encoding.
U d
-
7/26/2019 Java Web Services Training-12 13 October 2015
37/120
Unwrapped
wsimport -keep -p -b custom.xml
false
T d ff B t th RPC d D t St l
-
7/26/2019 Java Web Services Training-12 13 October 2015
38/120
Tradeoffs Between the RPC and Document Styles
One familiar complaint against the rpc style is that it
imposes the request/response pattern on the service.However, this pattern remains the dominant one in real-world, SOAP-based web services.
-
7/26/2019 Java Web Services Training-12 13 October 2015
39/120
Here are some upsides of the rpc style:
The automatically generated WSDL is relatively short andsimple because there is no types section.
Messages in the WSDL carry the names of theunderlying web service operations, which are
@WebMethods in a Java-based service. The WSDL thushas a what you see is what you get style with respect tothe services operations.
Message throughput may improve because the
messages do not carry any typeencoding information.
-
7/26/2019 Java Web Services Training-12 13 October 2015
40/120
Here are some downsides to the rpc style:
The WSDL, with its empty types section, does not provide an XSDagainst which the body of a SOAP message can be validated.
The service cannot use arbitrarily rich data types because there is noXSD to define such types. The service is thus restricted to relativelysimple types such as integers, strings, dates, and arrays of such.
This style, with its obvious link to the request/response pattern,encourages tight coupling between the service and the client..
Java services written in this style may not be consumable in otherframeworks, thus undermining interoperability. Further, long-termsupport within the web services community and from the WS-I group is
doubtful.
-
7/26/2019 Java Web Services Training-12 13 October 2015
41/120
Some upsides of the document style:
The body of a SOAP message can be validated against the XSD inthe types section of the WSDL.
A service in this style can use arbitrarily rich data types, as the XMLSchema language supports not only simple types such as integers,strings, and dates, but also arbitrarily rich complex types.
There is great flexibility in how the body of a SOAP message isstructured so long as the structure is clearly defined in an XSD.
The wrapped convention provides a way to enjoy a key upside of therpc stylenaming the body of a SOAP message after thecorresponding service operationwithout enduring the downsides of
the rpc style.
-
7/26/2019 Java Web Services Training-12 13 October 2015
42/120
Some downsides of the document style:
In the unwrapped variant, the SOAP message does not carry thename of the service operation, which can complicate the dispatching ofmessages to the appropriate program code.
The wrapped variant adds a level of complexity, in particular at theAPI level.
The wrapped variant does not support overloaded service operationsbecause the XML wrapper element in the body of a SOAP messagemust have the name of the service operation. In effect, then, there canbe only one operation for a given element name.
A A h Cli t
-
7/26/2019 Java Web Services Training-12 13 October 2015
43/120
An Asynchronous Client
port.getAsync(, new MyHandler());
// The handler class implements handleResponse, which executes
// if and when there's a response.
static class MyHandler implements AsyncHandler {
public void handleResponse(Response future) {
try {
response = future.get();//do your logic here}
catch(InterruptedException e) { System.err.println(e); }
catch(ExecutionException e) { System.err.println(e); }
}
}
% wsimport -p client -keep http://localhost:9876/ts?wsdlb custom.xml
true
Th Utilit d JAX B A tif t
http://localhost:9876/ts?wsdlhttp://localhost:9876/ts?wsdl -
7/26/2019 Java Web Services Training-12 13 October 2015
44/120
The wsgen Utility and JAX-B Artifacts
The wsgen utility produces the classes required to build the WSDL,
classes known as wsgen artifacts.The wsgen utility generates a Java classhence, a Java data typefor each of these messages.
A SOAP-based web service, in either document or rpc style, should be
interoperable: a client application written in one language should beable to interact seamlessly with a service written in another despiteany differences in data types between the two languages. A sharedtype system such as XML Schema is, therefore, the key tointeroperability. The document style extends typing to the service
messages; and typed messages requires the explicit binding of Javaand XML Schema types.
Under the hood, this utility uses the packages associated with JAX-B(Java API for XML-Bin ding ). In a nu tshel l , JAX-B suppo rts
convers ions between Java and XML types.
A JAX B Example
-
7/26/2019 Java Web Services Training-12 13 October 2015
45/120
A JAX-B Example
The @XmlType and @XmlRootElement annotations direct
the marshaling of Skier objects, where marshaling is theprocess of encoding an in-memory object (for example, a
Skier) as an XML document so that, for instance, theencoding can be sent across a network to be unmarshaled
or decoded at the other end. In common usage, thedistinction between marshal and unmarshal is very closeand perhaps identical to the serialize/deserialize
distinction.
jaxb.*
Marshaling and wsgen Artifacts
-
7/26/2019 Java Web Services Training-12 13 October 2015
46/120
Marshaling and wsgen Artifacts
Refer to the generated artifacts
An Overview of Java Types and XML Schema Types
-
7/26/2019 Java Web Services Training-12 13 October 2015
47/120
An Overview of Java Types and XML Schema Types
Java type XML Schema type
int Xsd:intbyte Xsd:byte
java.lang.String xsd:string
java.util.Calendar Xsd:date, xsd:time, xsd:datetime
BigDecimal Xsd:decimal
What JAX-B brings to the table is a framework for binding arbitrarily rich Javatypes, with the Skier class as but a hint of the possibilities, to XML types.Instances of these Java types can be marshaled to XML documentinstances, which in turn can be unmarshaled to instances of either Javatypes or types in some other language.
Summary of wsgen & JAX B packages interaction
-
7/26/2019 Java Web Services Training-12 13 October 2015
48/120
Summary of wsgen & JAX-B packages interaction
A Java web service in document rather than rpc style has a nonemptytypes section in its WSDL. This section defines, in the XML Schemalanguage, the types required for the web service.
The wsgen utility generates, from the SIB, Java classes that arecounterparts of XSD types. These wsgen artifacts are available for theunderlying JWS libraries, in particular for the JAX-B family ofpackages, to convert (marshal) instances of Java types (that is, Javain-memory objects) into XML instances of XML types (that is, into XMLdocument instances that satisfy an XML Schema document). Theinverse operation is used to convert (unmarshal) an XML documentinstance to an in-memory object, an object of a Java type or acomparable type in some other language.
The wsgen utility thus produces the artifacts that supportinteroperability for a Java-based web service. The JAX-B librariesprovide the under-the-hood support to convert between Java and XSDtypes.
Generating a WSDL with the wsgen Utility
-
7/26/2019 Java Web Services Training-12 13 October 2015
49/120
Generating a WSDL with the wsgen Utility
The wsgen utility also can be used to generate a WSDL
document for a web service.For example, the command:
wsgen -cp "." -wsdl rpc.ts.TimeServerImpl
Code First Versus Contract First
-
7/26/2019 Java Web Services Training-12 13 October 2015
50/120
Code First Versus Contract First
Code first approach short-comings:
If the service changes, the WSDL automatically changes.The code-first approach usually results in a servicecontract that provides few, if any, provisions for handlingtricky but common problems.
If the service implementation is complicated or evenmessy, these features carry over into a WSDL.
The code-first approach seems to go against thelanguage-neutral theme of SOAP based web services.
-
7/26/2019 Java Web Services Training-12 13 October 2015
51/120
Contract first approach short-comings:
Real-world programming practice.
A Code First Contract Aware Approach
-
7/26/2019 Java Web Services Training-12 13 October 2015
52/120
A Code-First, Contract-Aware Approach
Java, however, does provide annotations that the
programmer can use in order to determine, in criticalareas, how the generated WSDL or, in turn, WSDL-generated artifacts will turn out.
cfca.*
A Code First Contract Aware Approach Example
-
7/26/2019 Java Web Services Training-12 13 October 2015
53/120
A Code-First, Contract-Aware Approach Example
In the @WebService annotation, the:
serviceName = RevisedTimeServerattribute causes the service artifact to be the class namedRevisedTimeServer,
and the:
name = AnnotatedTimeServer
attribute causes the portType artifact to be the classnamed AnnotatedTimeServer.
targetNamespace ensures that this will be the namespaceURI for the service in the WSDL
-
7/26/2019 Java Web Services Training-12 13 October 2015
54/120
The @WebResult annotation of the getTimeAsString method does not impactthe WSDL
but rather the SOAP response message; in particular the subelement with thetag name
ns1:ts_out in the wrapped SOAP body:
Hi, world! at Thu Oct 23 22:24:59 CDT 2008
-
7/26/2019 Java Web Services Training-12 13 October 2015
55/120
The @WebMethod named acceptInput is annotated as
@Oneway, which requires that the method return void. Asa result, a client can send a request to the parameterizedacceptInput operation but receives no response.
Conclusion:The example shows some of the possibilities in JWSscode-first, contract-aware approach.
If the web service creator is willing to accept defaults, the
JWS annotations such as @WebService and@WebMethod are clear and simple. If fine-grained controlover the WSDL and the SOAP messages is required, suchcontrol is available with additional annotations.
UDDI
-
7/26/2019 Java Web Services Training-12 13 October 2015
56/120
UDDI
A UDDI (Universal Description Discovery and Integration)
registry is one way to publish WSDLs so that potentialclients can discover them and ultimately consume the
services that the WSDLs describe.
Limitations of the WSDL
-
7/26/2019 Java Web Services Training-12 13 October 2015
57/120
Limitations of the WSDL
Once a WSDL has been located, perhaps through a UDDI
service, critical questions remain about the servicedescribed in the WSDL. For one, the WSDL does notexplain service semantics or, in plainer terms, what theservice is about.
The W3C is pursuing initiatives in web semantics under
the rubric of WSDL-S (Semantics).
see http://www.w3.org/Submission/WSDL-S.
As of now, a WSDL typically is useful only if the client
programmer already understands what the service isabout.
SOAP Handling
-
7/26/2019 Java Web Services Training-12 13 October 2015
58/120
SOAP Handling
Need to process a Soap envelope.
SOAP now comes in two versions, 1.1 and 1.2. The goodnews is that the differences between SOAP 1.1 and SOAP1.2 have minor impact on programming web services in
general and programming JAX-WS in particular.
Structure of soap message
-
7/26/2019 Java Web Services Training-12 13 October 2015
59/120
Structure of soap message
Under either version, SOAP messages can be manipulated throughhandlers, which are programmer-written classes that contain callbacks;that is, methods invoked from the web service runtime so that anapplication has access to the underlying SOAP. At what might be
called the application level, which consists of web services and theirclients, the SOAP remains hidden. At the handler level, the SOAP isexposed so that the programmer can manipulate the incoming andoutgoing messages.
-
7/26/2019 Java Web Services Training-12 13 October 2015
60/120
At handler level:
In JAX-WS, as in most frameworks, SOAP 1.1 is thedefault and SOAP 1.2 is an option readily available.
Starting with the 1.2 version, SOAP is officially no longer
an acronym!
1.1 1.2
technically allows XMLelements to occur after theSOAP body. Very rare
though.
the SOAP body is the lastXML element in the SOAPenvelope.
binds SOAP to HTTPtransport.
also supports SOAP overSMTP.
specification is a singledocument,
specification is divided intothree documents.
SOAP Message
-
7/26/2019 Java Web Services Training-12 13 October 2015
61/120
SOAP Message
SOAP Format Sample
WSTraining
ctli123
-
7/26/2019 Java Web Services Training-12 13 October 2015
62/120
Although a SOAP message is intended for an ultimate
receiver, the SOAP messaging architecture allows forSOAP intermediaries, which are nonterminal recipients or
nodes along the route from the sender to the ultimate
receiver. An intermediary may inspect and even
manipulate an incoming SOAP message before sendingthe message on its way toward the ultimate receiver.
Sender Intermediary 1 Intermediary 2 Receiver
-
7/26/2019 Java Web Services Training-12 13 October 2015
63/120
Body is required.
Header is optional.
An intermediary should inspect and process only theelements in the SOAP header rather than anything in the
SOAP body, which carries whatever cargo the senderintends for the ultimate receiver alone. The header, bycontrast, is meant to carry whatever meta-information isappropriate for either the ultimate receiver or
intermediaries.
Example?
-
7/26/2019 Java Web Services Training-12 13 October 2015
64/120
Digital Signature as a voucher.
include a timestamp that indicates when the information inthe messages body becomes obsolete.
-
7/26/2019 Java Web Services Training-12 13 October 2015
65/120
ca12fd33-16e1-4a95-b17e-3ef6744babdc
45
-
7/26/2019 Java Web Services Training-12 13 October 2015
66/120
The header block with the uuid tag has an attribute, SOAP-
ENV:actor, whose value ends with next. The next actor, inthis scheme, is the next recipient on the path from the
message sender to the ultimate receiver; hence, eachintermediary (and the ultimate receiver) acts in a next role.
A next actor is expected to inspect header blocks in someapplication-appropriate way. If a node cannot process theheader block, then the node should throw a fault. In SOAP1.2, this expectation can be made explicit by setting the
mustUnderstand attribute of a header block to true, whichmeans that a node must throw a fault if the node cannotprocess the header block.
-
7/26/2019 Java Web Services Training-12 13 October 2015
67/120
By default, JWS generates a SOAP request message
without a header.
Programming in the JWS Handler Framework
-
7/26/2019 Java Web Services Training-12 13 October 2015
68/120
g g
JWS provides a handler framework that allows application
code to inspect and manipulate outgoing and incomingSOAP messages. A handler can be injected into theframework in two steps:
1. Create Handler class.2. Place it in handler chain.
Once injected into the handler framework, a programmer-
written handler acts as a message interceptor that hasaccess to every incoming and outgoing message.
chain of responsibility pattern
Handlers and SOAP Message
-
7/26/2019 Java Web Services Training-12 13 October 2015
69/120
g
SOAP Handler
Custom handlers implement SOAPHandlerCan access both SOAP Headers and Body
Logical Handler
Custom handlers implement LogicalHandler
Can access SOAP Body only.
Handler Examples
-
7/26/2019 Java Web Services Training-12 13 October 2015
70/120
p
Client Side
Server Side
Programmatically.
Configuration file.
Annotations.
Intro.rpc.*
Configuration File
-
7/26/2019 Java Web Services Training-12 13 October 2015
71/120
g
intro.rpc.TimeLogicalHandler
intro.rpc.TimeSoapHandler
Programmatically
-
7/26/2019 Java Web Services Training-12 13 October 2015
72/120
g y
In the client
service.setHandlerResolver(newClientHandlerResolver());
Handler class -
import javax.xml.ws.handler.Handler;
import javax.xml.ws.handler.HandlerResolver;import javax.xml.ws.handler.PortInfo;
class ClientHandlerResolver implements HandlerResolver {
public List getHandlerChain(PortInfo port_info) {
List hchain = new ArrayList();
hchain.add(new UUIDHandler());
hchain.add(new TestHandler()); // for illustration only
}
}
handleFault Method
-
7/26/2019 Java Web Services Training-12 13 October 2015
73/120
division.*
SOAP 1.2 service
-
7/26/2019 Java Web Services Training-12 13 October 2015
74/120
Convert to SOAP 1.2 webservice - SIB
@BindingType(value =http://java.sun.com/xml/ns/jaxws/2003/05/soap/bindings/HTTP/")
MustUnderstand attribute on the header elementWsimport -extension ..
The MessageContext and Transport Headers
http://java.sun.com/xml/ns/jaxws/2003/05/soap/bindings/HTTP/http://java.sun.com/xml/ns/jaxws/2003/05/soap/bindings/HTTP/http://java.sun.com/xml/ns/jaxws/2003/05/soap/bindings/HTTP/http://java.sun.com/xml/ns/jaxws/2003/05/soap/bindings/HTTP/ -
7/26/2019 Java Web Services Training-12 13 October 2015
75/120
The focus is on the MessageContext, which is normally
accessed in handlers.
Seen in an architectural light, a context is what gives anobject (a servlet, an EJB, a web service) access to its
underlying container (servlet container, EJB container, webservice container). Containers, in turn, provide the under-the-hood support for the object. Seen in a programming
light, a context is a Map, that is, akey/value collection in which the keys are strings and thevalues are arbitrary objects.
Echo.mctx.*
Web Services and Binary Data
-
7/26/2019 Java Web Services Training-12 13 October 2015
76/120
images, movies, and the like
Type conversions come to the forefront in the issue of howbinary data such as images, movies, and the like can bearguments passed to or values returned from web service
operations. SOAP-based web services are not limited totext, but their use of binary data raises important efficiencyissues.
Two general approaches.
First Approach
-
7/26/2019 Java Web Services Training-12 13 October 2015
77/120
The binary data can be encoded using a scheme such as
base64 and then transmitted as the payload of the SOAPbody. The downside is that base64 and similar encodingschemes result in payloads that are at least a third largerin size than the original, unencoded binary data. In short,byte encoding such as base64 results in data bloat.
Second Approach
-
7/26/2019 Java Web Services Training-12 13 October 2015
78/120
The binary data can be transmitted as one or more
attachments to a SOAP message. A SOAP message alsomay have attachments, which can carry data of any MIMEtype, including multimedia types such as audio/x-wav,video/mpeg, and image/jpeg. JAX-B provides the required
mappings between MIME and Java types: the MIME typesimage/* map to Image, and the remaining multimedia typesmap to DataHandler.
The downside is that the receiver then must deal with theraw bytes, for example, by converting them back intomultimedia types such as images and sounds.
Three Options for SOAP Attachments
-
7/26/2019 Java Web Services Training-12 13 October 2015
79/120
SwA (SOAP with Attachments) - the original SOAPspecification for attachments;It is hard to use SwA with a document-style service, which is now the norm.Frameworks such as DotNet do not support SwA
DIME (Direct Internet Message Encapsulation), a
lightweight but by now old-fashioned encoding scheme forattachments;JWS has a DIME extension whose main purpose is to interoperate with Microsoft clients.
MTOM (Message Transmission Optimization Mechanism),which is based onXOP (XML-Binary OptimizedPackaging).MTOM has the W3C stamp of approval and enjoys widespread support; hence, MTOMis the efficient, modern, interoperable way to transmit binary data in SOAP-based webservices.
First Approach Example
-
7/26/2019 Java Web Services Training-12 13 October 2015
80/120
1. Edit the XSD document. In particular, make the two additions shown in bold:
The attribute expectedContentTypes is set to the MIME type image/jpeg so that the
wsimport utility can generate versions of the operations getImage and getImages
that return the Java types Image and List, respectively.
ch03.image.*
-
7/26/2019 Java Web Services Training-12 13 October 2015
81/120
2. In the SkiImageService, the @WebService annotation
should be changed to:@WebService(serviceName = "SkiImageService",
wsdlLocation = "ch03/image/ski.wsdl")
-
7/26/2019 Java Web Services Training-12 13 October 2015
82/120
The WSDL should then be changed to reflect the new
location of XSD document:
-
7/26/2019 Java Web Services Training-12 13 October 2015
83/120
Wsimport
wsimport -keep -p skiC2 ch03/image/ski.wsdl
MTOMChange 1
-
7/26/2019 Java Web Services Training-12 13 October 2015
84/120
The MIME subtype name application/octet-stream captures the optimization thatrecommends MTOMthe image bytes will be streamed unencoded to the service client.
The bloat of base64 or comparable encoding is thereby avoided.In the XSD, the expectedContentTypes attribute occurs twice. The changes are in bold:
MTOMChange 2
-
7/26/2019 Java Web Services Training-12 13 October 2015
85/120
For emphasis, the SkiImageService is annotated to show
that MTOM may come intoplay:
import javax.xml.ws.soap.SOAPBinding;
@WebService(serviceName = "SkiImageService")
// This binding value is enabled by default but put here foremphasis.
@BindingType(value =
SOAPBinding.SOAP11HTTP_MTOM_BINDING)
@HandlerChain(file = "handler-chain.xml") // for messagetracking
public class SkiImageService {//**The binding value is the default, hence optional, but it is included for emphasis.
MTOMchange 3
-
7/26/2019 Java Web Services Training-12 13 October 2015
86/120
The next change is important. The revised publisher, with the work now divided among several methods for clarity:
package ch03.image;
import javax.xml.ws.Endpoint;
import javax.xml.ws.soap.SOAPBinding;
public class SkiImagePublisher {
private Endpoint endpoint;
public static void main(String[ ] args) {
SkiImagePublisher me = new SkiImagePublisher();
me.create_endpoint();
me.configure_endpoint();
me.publish();}
private void create_endpoint() {
endpoint = Endpoint.create(new SkiImageService());
}
private void configure_endpoint() {
SOAPBinding binding = (SOAPBinding) endpoint.getBinding();
binding.setMTOMEnabled(true);}
private void publish() {
int port = 9999;
String url = "http://localhost:" + port + "/ski";
endpoint.publish(url);
System.out.println(url);
}
}
-
7/26/2019 Java Web Services Training-12 13 October 2015
87/120
The service operations now return a DataHandler or a List
of these. This change is reflected in the JAX-B artifactscreated with the wsimport utility.
It is now up to the client to reconstruct the appropriate
objects from the optimized byte stream sent from theservice. The tradeoff is clear: MTOM optimizes thetransmission by avoiding data bloat, but the messagereceiver is forced to deal with raw bytes.
JAS
-
7/26/2019 Java Web Services Training-12 13 October 2015
88/120
Web container
Message-oriented middlewareEnterprise Java Bean (EJB) container
JNDI service provider
Security provider
Relational Database Management System
Client container
-
7/26/2019 Java Web Services Training-12 13 October 2015
89/120
Web container
A web container deploys servlets and web services. A traditional web
application in Java is a mix of static HTML pages, servlets, higher-level servletgenerators such as JSP (Java Server Pages) and JSF (Java Server Faces)scripts, backend Java-Beans for JSP and JSF scripts, and utility classes.Tomcat is the reference implementation (RI) for a web container. Tomcat, likeother web containers, can be embedded in an application server. Webcomponents are deployed in the web container as WAR files, which typicallycontain the standard configuration document web.xml and may containvendor-specific configuration documents as well (e.g., sun-jaxws.xml). To hostweb services, a web container relies on a servlet interceptor (in the case ofTomcat, a WSServlet instance) that mediates between the client and the webservice SIB.
Client container
The client container consists of the software libraries that a client requires tointeract with deployed components such as message topics or EJBs and touse services such as JNDI and security.
Deploy WebServices on Tomcat
-
7/26/2019 Java Web Services Training-12 13 October 2015
90/120
1.Create a web service (of course).
2.Create a sun-jaxws.xml, defines web serviceimplementation class.
3.Create a standard web.xml, definesWSServletContextListener, WSServlet and structure of a
web project.4.Build tool to generate WAR file.
5.Copy JAX-WS dependencies to ${Tomcat}/lib folder.
6.Copy WAR to ${Tomcat}/webapps folder.
7.Start It.
-
7/26/2019 Java Web Services Training-12 13 October 2015
91/120
WSServlet instance is linked to the JWS runtime. Tomcat
provides the WSServlet instance.
WSServletContextListener instance that will parse asecond, Sun-specific configuration file named sun-
jaxws.xml, which provides the web services endpoint byconnecting the WSServlet instance to the servicesimplementation class.
-
7/26/2019 Java Web Services Training-12 13 October 2015
92/120
5. JAX-WS Dependencies
By default, Tomcat does not comes with any JAX-WS dependencies, So, youhave to include it manually.
1. Go here http://jax-ws.java.net/.
2. Download JAX-WS RI distribution.
3. Unzip it and copy following JAX-WS dependencies to Tomcat library folder{$TOMCAT}/lib.
jaxb-impl.jar
jaxws-api.jar
jaxws-rt.jar
gmbal-api-only.jar
management-api.jar
stax-ex.jar
streambuffer.jar
policy.jar
Overview of Web Services Security
-
7/26/2019 Java Web Services Training-12 13 October 2015
93/120
Wire-level security
Security begins at the transport or wire levelUser authentication and authorization
Web services provide clients with access to resources.
WS-Security
WS-Security, or WSS for short, is a collection ofprotocols.
Wire-level security
-
7/26/2019 Java Web Services Training-12 13 October 2015
94/120
HTTP/HTTPS
HyperText Transport Protocol over Secure SocketLayer
Netscape did the original work called it SSL (SecureSockets Layer).
TheIETF (International Engineering Task Force) hastaken over SSL and renamed it to TLS (Transport
Layer Security)
HTTPS Basic Service Peer authentication
Confidentiality
Integrity
Wire-level securitytypes of encryptions
-
7/26/2019 Java Web Services Training-12 13 October 2015
95/120
Symmetric and Asymmetric Symmetric
Also called Single Key Encryption
Simple
Less time
key distribution problem.
Asymmetric Public Key Encryption
Complex
Takes 1000 times more time than symmetric
No key distribution problem.
Wire-level security
-
7/26/2019 Java Web Services Training-12 13 October 2015
96/120
Public key encryption and decryption Solves the key distribution problem
The public key approach solves the confidentiality problem for Aliceand Bob.
A hash value is also called a message digest, which is a fixed-length digest of arbitrarily many input bits.
Or A message digest is a crytographic hash function containing a string of digits created by a one-way hashing formula.
HTTPS Basic Service
-
7/26/2019 Java Web Services Training-12 13 October 2015
97/120
Peer authenticationDigital Certificates
Confidentiality - EncryptionIntegrityDigest
IntegrityDigest
-
7/26/2019 Java Web Services Training-12 13 October 2015
98/120
The message sent over HTTPS includes a digest, which
the receiver recomputes. If the sent digest differs from thedigest that the receiver computes, then the message wasaltered during transmission, either by accident or design. Ifthe sent digest itself is altered during transmission, thislikewise counts as integrity failure.
Peer authenticationDigital Certificates
-
7/26/2019 Java Web Services Training-12 13 October 2015
99/120
A typical web applicationuser needs to pay1. User browser challenges the vendors web server
One or more digital certificate is returned back
2. Browser checks the web servers digital certificates against the browserstruststore
Vouching signature from VeriSign a certificate authority (CA)
3. The server has the option of challenging the client. The web servertypically does not challenge the browser.
Tomcats configuration file, server.xml
HTTPS Basic Serviceauthentication/confidentiality
-
7/26/2019 Java Web Services Training-12 13 October 2015
100/120
Process of generating a secret key:
4. Client generates of a pre-master secret string and sends to server
Pre-master key is 48 bit
Encrypts pre-master key using the public key received in the digitalcertificate.
5. Server decrypts the pre-master key using its own public key.
6. Client and the server agree upon which cipher suite, or set of
cryptographic algorithms, should be used. A cipher suite includes a key-pair algorithm and a hash algorithm.
7. Master key is distributed as per the decided cipher suite.
8. At any point, either the client or the server may insist on starting the entireprocess
9. A secret key is used to encrypt and decrypt traffic for several reasons. First, symmetric encryption has relatively high performance.
Second, if the server does not challenge the client, then the server doesnot have the clients public key to encrypt messages to the client.
HTTPS Basic ServiceGoogleClient
G l Cli t j
-
7/26/2019 Java Web Services Training-12 13 October 2015
101/120
GoogleClient.javaHere is the output from a sample run:
Status code: 200
- Cipher suite: SSL_RSA_WITH_RC4_128_MD5 Cert. type: X.509
Hash code: 23073427
Algorithm: RSA
Format: X.509
Cert. type: X.509
Hash code: 32560810
Algorithm: RSA Format: X.509
Cert. type: X.509
Hash code: 8222443
Algorithm: RSA
Format: X.509
RSA - public key cryptography algorithm
RC4_128 - stream cipher algorithm
MD5 - Message Digest algorithm 5
Clients default truststore: JAVA_HOME/jre/lib/security/cacerts
Container-Managed Security for Web Services
-
7/26/2019 Java Web Services Training-12 13 October 2015
102/120
Securing the @WebService Under Tomcat
Web ServiceWeb component
-
7/26/2019 Java Web Services Training-12 13 October 2015
103/120
Cd WSSTempConvert\bin\WEB-INF\classes
wsgen.exe -cp . com.tc.secure.TempConvertSecureImpl
Cd ..\..
jar cvf tempc.war WEB-INF
Copy the war file into ${Tomcat}\webapps
Start the tomcatwsimport -keep -p tcClient https://localhost:8443/tempc/tc?wsdl
Create client application
Tomcat con nector fo r SSL/TLS is enabled: conf/server.xml,
uncomment and restart the tomcat:
Generating Keystore using keytool
http://localhost:8080/tempc/tc?wsdlhttp://localhost:8080/tempc/tc?wsdl -
7/26/2019 Java Web Services Training-12 13 October 2015
104/120
C:\Users\ssathee\workspace\WSSTempConvertClient>keytool -genkey -alias tomcatws -keyalg RSA
Enter keystore password: changeit
Re-enter new password: changeit
What is your first and last name?
[Unknown]: Sandeep S
What is the name of your organizational unit?
[Unknown]: CTLI
What is the name of your organization?
[Unknown]: CTL
What is the name of your City or Locality?[Unknown]: Bangalore
What is the name of your State or Province?
[Unknown]: Karnataka
What is the two-letter country code for this unit?
[Unknown]: IN
Is CN=Sandeep S, OU=CTLI, O=CTL, L=Bangalore, ST=Karnataka, C=IN correct?[no]: yes
Enter key password for
(RETURN if same as keystore password):
C:\Users\ssathee> dir .keystore
Location of .keystore file
-
7/26/2019 Java Web Services Training-12 13 October 2015
105/120
By default location of .keystore file is user home directory and tomcat also looks for it in this directory.
Say C:/users/ssathee
Otherwise server.xml can also be updated to point to the .keystore file location as follows:
Restart the tomcat.
Try this URL: https://localhost:8443
To execute client for a secure service
-
7/26/2019 Java Web Services Training-12 13 October 2015
106/120
1. There is no need to re-generate the client stubs again by running wsimport command for httpswsdl. You can stilluse the client stub generated for httpwsdl.
2. Minor change in the client code. At runtime, you need to run pointing to https. That can be achieved with below
code (changes are highlighted with bold)package client;
import java.util.Map;import javax.xml.ws.BindingProvider;
public class HelloWorldClient {
private static final String endpoint = "https://localhost:8443/HelloWorld-20141031/hello";
public static void main(String[] args) {HelloWorldImplService service = new HelloWorldImplService();HelloWorld port = service.getHelloWorldImplPort();
Map req_ctx = ((BindingProvider) port).getRequestContext();
req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpoint);
System.out.println(port.getHelloWorldAsString());}}
To execute client
https://mail.centurylink.com/OWA/redir.aspx?C=3rk7WPfv0k21Egbuk3KPROgC2JRBcdIInsN16V1BITxaQtpB_eYEtUOg9WQL_Uy9RqJScSOozyA.&URL=https://localhost:8443/HelloWorld-20141031/hellohttps://mail.centurylink.com/OWA/redir.aspx?C=3rk7WPfv0k21Egbuk3KPROgC2JRBcdIInsN16V1BITxaQtpB_eYEtUOg9WQL_Uy9RqJScSOozyA.&URL=https://localhost:8443/HelloWorld-20141031/hellohttps://mail.centurylink.com/OWA/redir.aspx?C=3rk7WPfv0k21Egbuk3KPROgC2JRBcdIInsN16V1BITxaQtpB_eYEtUOg9WQL_Uy9RqJScSOozyA.&URL=https://localhost:8443/HelloWorld-20141031/hellohttps://mail.centurylink.com/OWA/redir.aspx?C=3rk7WPfv0k21Egbuk3KPROgC2JRBcdIInsN16V1BITxaQtpB_eYEtUOg9WQL_Uy9RqJScSOozyA.&URL=https://localhost:8443/HelloWorld-20141031/hello -
7/26/2019 Java Web Services Training-12 13 October 2015
107/120
3. Run the modified client class with the VM arguments (ineclipse, right click -> run configurations): -
No need to regenerate keystore newly. You need to usethe already generated keystore.
-Djavax.net.ssl.trustStore=C:/Users/ssathee/.keystore -
Djavax.net.ssl.trustStorePassword=changeit -Djavax.net.ssl.keyStore=C:/Users/ssathee/.keystore -
Djavax.net.ssl.keyStorePassword=changeit
The command is sufficiently complicated that an Ant orequivalent script might be used in production.
Application-Managed Authentication
-
7/26/2019 Java Web Services Training-12 13 October 2015
108/120
com.tc.secure.application*
Container-Managed Authentication and Authorization
-
7/26/2019 Java Web Services Training-12 13 October 2015
109/120
A realm is a collection of resources, including web pagesand web services, with a designated authentication and
authorization facilitylike Unix group with respect toaccess rights.
Tomcat provides five standard plugins, with Realm in thenames, to manage communications between the containerand authentication/authorization store. Here are the fiveplugins with a short description of each:
JDBCRealm, DataSourceRealm, JNDIRealm,MemoryRealm, JAASRealm
Configuring Container-Managed Security Under Tomcat
-
7/26/2019 Java Web Services Training-12 13 October 2015
110/120
declarativerather thanprogrammatic.
Web.xml changes.
Web service implementation
Generate client.
Conf/Tomcat-users.xml
com.tc.auth*tcauthClient*
Web.xml changes
-
7/26/2019 Java Web Services Training-12 13 October 2015
111/120
The Only Secure Role
bigshot
Users-Roles Security
/tcauth
bigshot
CONFIDENTIAL
BASIC
Generate client
-
7/26/2019 Java Web Services Training-12 13 October 2015
112/120
There is one tricky aspect to the client: the use of thewsimport utility to generate the artifacts in the tcauthClientpackage. The problem is that the web services WSDL is
also secured and therefore requires authentication foraccess. There are workarounds, of course. One option isto generate the WSDL locally by using the wsgen utility onthe SIB. Another option is to get the WSDL from anonsecure version of the service. The locally saved WSDLand its XSD are then fed into wsimport to generate theartifacts.
Conf/Tomcat-users.xml
-
7/26/2019 Java Web Services Training-12 13 October 2015
113/120
-
7/26/2019 Java Web Services Training-12 13 October 2015
114/120
BASIC
FORMCLIENT-CERT
DIGEST
Using a Digested Password Instead of a Password
-
7/26/2019 Java Web Services Training-12 13 October 2015
115/120
Tomcat also supports the DIGEST method ofauthentication. A careful user will be understandablyconcerned about having a copy of a password on a remotehost, in this case the machine that hosts the secured webservice. If the remote host is compromised, so is the userspassword. A digest of the password avoids this problem so
long as the digest is generated with a one-way hashfunction; that is, a function that is easy to compute but hardto invert. For example, given the digest of a password andthe algorithm used to compute the digest (for instance,
MD5 or SHA-1), it is still a computationally intractable taskto derive the original password from the digest producedby a one-way hash function used in MD5 or SHA-1.
-
7/26/2019 Java Web Services Training-12 13 October 2015
116/120
Web.xml
Digest utility;Conf/tomcat-users.xmlreplace the password
Client changetcauthDigest*
The revised client needs to be executed with the JAR files
bin/tomcat-juli.jar andlib/catalina.jar on the classpath. The compiler needs only
the catalina.jar file on the classpath.
Digest utility
-
7/26/2019 Java Web Services Training-12 13 October 2015
117/120
Tomcat provides a digest utility, in TOMCAT_HOME/bin,that can be used to generate message digests using thestandard algorithms such as MD5 and SHA.
Here is the command to digest Freds password rockbed:
digest.bat -a SHA rockbed
WSSecurity - WSS
-
7/26/2019 Java Web Services Training-12 13 October 2015
118/120
WS-Security is a family of specifications designed to augment wire level security by providing aunified, transport-neutral, end-to-end framework for higher levels of security such as authenticationand authorization.
-
7/26/2019 Java Web Services Training-12 13 October 2015
119/120
WS-Security is often associated with federated security inthe broad sense, which has the goal of cleanly separatingweb service logic from the high-level security concerns, inparticular authentication/authorization, that challenge webservice deployment. This separation of concerns is meantto ease collaboration across computer systems and trust
realms.
-
7/26/2019 Java Web Services Training-12 13 October 2015
120/120
THANK YOU