advanced soa and web services

54
Advanced SOA Sreekanth Narayanan Code samples in Java

Upload: sreekanth-narayanan

Post on 15-Jan-2015

2.588 views

Category:

Technology


2 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Advanced soa and web services

Advanced SOASreekanth Narayanan

Code samples in Java

Page 2: Advanced soa and web services

What are we covering ?

• Message Handlers/Design/Uses• Web Service Interoperability Issues• WS-I basic profile• JAX-WS Asynchronous Client API

Page 3: Advanced soa and web services

Handlers

• Handlers are components which act as interceptors and can be plugged in to Web Service (Dealing with JAX-WS predominantly, but other runtimes also support handlers) runtime environment to do additional processing on the incoming and outgoing messages. There are 2 broad classifications of handlers

Page 4: Advanced soa and web services

Handlers ...Types• Protocol Handlers• Logical Handlers

• Handlers are invoked with a message context, which provides methods that the handler uses to access and modify inbound or outbound messages

Page 5: Advanced soa and web services

Handlers ...

JAX-WS RUNTIMEJAX-WS RUNTIME

NetworkLogical Handlers

SOAP Handlers

SOAP Handlers

Logical Handlers

Client Server

Page 6: Advanced soa and web services

Protocol Handlers• They deal with a specific Protocol like SOAP • They can work on the header and the body of a SOAP

message • Extensively used in applications where there is a

need for processing the information which is sent on the SOAP header.

• A Typical example is cases where we need to send information which cannot be sent as a payload

• Very useful in performance logging for services and throttling

Page 7: Advanced soa and web services

SOAP Protocol Handler Sample public class ServiceSoapMessageHandler implements SOAPHandler<SOAPMessageContext> {

// OR extend from ... public boolean handleMessage(SOAPMessageContext smc) { logToLog4J(smc); return true; } public boolean handleFault(MessageContext smc) { logToLog4J(smc); return true; } public void close(MessageContext messageContext) {

//Cleanup any ressources } }

Page 8: Advanced soa and web services

Logical Handlers• Protocol agnostic• They work on the Payload and not on the

Protocol specified parts of the message • Can be transported across protocols• Cannot alter the SOAP Header/Body

Page 9: Advanced soa and web services

Logical handler example public class LogicalMesaageValidationHandler implements LogicalHandler<LogicalMessageContext> { ... public boolean handleMessage (LogicalMessageContext context) { return processMessage(context); } public boolean handleFault (LogicalMessageContext context) { return processMessage(context); } public void close(MessageContext context) { // Clean up Resources } }

Page 10: Advanced soa and web services

Register your handlers ! // Annotate your WS implementation class with the handler chain name

@HandlerChain(file="Servicehandler.xml",name="ServiceSoapMessageHandler")

// Use Servicehandler.xml to declare the Handler class for the chain.

<?xml version="1.0" encoding="UTF-8"?><jwshc:handler-config xmlns:jwshc="http://www.bea.com/xml/ns/jws" xmlns="http://java.sun.com/xml/ns/j2ee"> <jwshc:handler-chain> <jwshc:handler-chain-name>

ServiceSoapMessageHandler </jwshc:handler-chain-name> <jwshc:handler> <handler-name>ServiceSoapMessageHandler</handler-name> <handler-class>com.company.product.soap.ServiceSoapMessageHandler</handler-class> </jwshc:handler> </jwshc:handler-chain></jwshc:handler-config>

Page 11: Advanced soa and web services

Uses of handlers• Handlers need to be registered with the Web Service Runtime to be

invoked

• Service Run time acts like the container by invoking the relevant hooks

Handlers can be used for performance monitoring and logging of Web Services. A SOAP handler can track the entry time and exit time for the Web Service by logging the time at both entry and exit

• Handlers can be used for throttling of Web Services. The handler can determine the number of calls which could be processed and disallow calls beyond a certain number. It can also check for the IP address from which the call emanates and see if the same client is making too many calls.

Page 12: Advanced soa and web services

Interoperability of Web Services• Interoperability is a key seller for web

services• .NET and J2EE interoperability is an example• The unknowns and pitfalls

Page 13: Advanced soa and web services

Key Interoperability issues Data Type Mismatches Platform related issues SOAP and WSDL related issues

Page 14: Advanced soa and web services

Interoperability – Data Type Issues• Non existence of direct native type maping.

Some schema types such as xsd:unsignedshort, xsd:unsignedint and xsd:unsignedlong do not always have a direct native type mappings on all languages. For example, in Java, unsigned types are not defined.

Page 15: Advanced soa and web services

Interoperability – Data Type Issues• Difference in precisions.

Different programming languages and platforms might support different precisions for XML schema defined floating point and decimal numbers such as xsd:decimal, xsd:double or xsd:float – and this might create issues with sensitive numbers like in financial transactions.

Page 16: Advanced soa and web services

Interoperability – Data Type Issues• Null values in SOAP messages.

Difference in how schema data types are mapped to native platform data types can cause issue in handling null values. For example, let’s say, a Java based Web service returns a date/time using java.util.Date or java.util.Calendar and a .NET consumer consumes the service. If the service returns a null, the .NET consumer fails, because in .NET System. DateTime is considered a value type (i.e., they reside in the stack) and value types cannot be a null. This is unlike Java where the two are classed as reference types (stored in the heap) and therefore can be null.

Page 17: Advanced soa and web services

Interoperability – Data Type Issues• Processing byte arrays.

SOAP allows exchanging data in the form of byte arrays (e.g., base64 encoded and placed on the XML document). Implementations may return inconsistent values due to a difference in native data types or other problems.

Please note that this method was used to transport binary data on SOAP for a long time, but has been found to be affective performance of the HTTP transport very badly. The MTOM (Message Transmission Optimization Mechanism) is the new recommended approach for the Binary data transported on SOAP as it no longer base 64 encodes the Binary data which is sent on HTTP and saves about 30% of the message size.

Page 18: Advanced soa and web services

Interoperability-Platform related issues• Different interpretations of namespace declarations.

.NET considers the domain name as well as the branch while making the packages for the generated code, But Java uses the name space based on only the domain name.

The problem comes when you have subfolders in your namespace and you repeat your classnames in the different namespaces – Java will try to place them all under same package as they all came from the same domain.

Page 19: Advanced soa and web services

Interoperability-Platform related • Difference in platform generated proxies.

Service proxies/stubs generated using one implementation does not typically work with other implementations. Moreover, code written against proxies generated using one version of the implementation may not work with another version of the implementation. For example, Code written against Axis 1.1 generated proxy may not work when the proxy is regenerated using Axis 1.2

Page 20: Advanced soa and web services

Interoperability-SOAP and WSDLUsage of mustUnderstand attribute. • SOAP 1.1 defines a mustUnderstand attribute that can be specified for a

SOAP header. • As per the W3C definition, The SOAP mustUnderstand global attribute

can be used to indicate whether a header entry is mandatory or optional for the recipient to process. The recipient of a header entry is defined by the SOAP actor attribute. The value of the mustUnderstand attribute is either "1" or "0". The absence of the SOAP mustUnderstand attribute is semantically equivalent to its presence with the value "0". The recipient is required to understand and make use of the information supplied by the header.

• If the actor does not understand the header, it must fault. Exception in thread "main" javax.xml.rpc.soap.SOAPFaultException: SOAP must understand error at com.sun.xml.rpc.client.StreamingSender._raiseFault(StreamingSender.java:528)

Page 21: Advanced soa and web services

Interoperability-SOAP and WSDLProblems• Some toolkits have allowed the values "false" and "true". • This incopatibility has been fixed in SOAP 1.2 where the spec states the

following : If relaying the message, a SOAP intermediary MAY substitute "true" for the value "1", or "false" for "0". In addition, a SOAP intermediary MAY omit a SOAP mustUnderstand attribute information item if its value is "false“ – But you still need to be careful about what SOAP version your WS runtime supports

• Supported only after SOAP 1.1 • Some SOAP runtimes do not support this attribute

Page 22: Advanced soa and web services

Interoperability-SOAP and WSDLUsage of SOAPAction Headers• When SOAP is used over HTTP there is a need to define a

header called “SOAPAction” (SOAP 1.1 – replaced by “action” in SOAP 1.2)

• The SOAPAction HTTP request header field can be used to indicate the intent of the SOAP HTTP request. The value is a URI identifying the intent.

• SOAP places no restrictions on the format or specificity of the URI or that it is resolvable.

• An HTTP client MUST use this header field when issuing a SOAP HTTP Request.

Page 23: Advanced soa and web services

Interoperability-SOAP and WSDLProblems• Some SOAP implementations require that the values be quoted.

However, some implementations do not quote their SOAPAction HTTP header values

• Also, if a receiver requires null-value SOAPAction, some HTTP client APIs have difficulty setting a null HTTP header value

• Some implementations support both SOAPAction values of "" and (null), while others do not (the soap spec does differentiate between the two of these)

• Some SOAP implementations such as Apache SOAP do not support dispatching using the SOAPAction header.

• Most versions of Axis use the HTTP Header name as “HTTP_SOAPAction” and not as SOAPAction. This creates interoperability problems –

• A very interesting authentication issue related to the SOAP Action header using AXIS 1.1 can be seen here.

Page 24: Advanced soa and web services

Interoperability-SOAP and WSDLWSDL Binding Styles• Style has 2 values: Document & RPC• A SOAP binding can also have an encoded use or a

literal useWe get 5 combinations with these • RPC/Encoded • RPC/Literal • Document/Encoded – Never Used• Document/Literal • Document/Literal wrapped

Page 25: Advanced soa and web services

Style – what that means• "literal" means "what you see is what you get"- this is just

plain XML data. "literal" implies that you should need nothing more other than the WSDL to establish communication with the web service endpoint. "literal" is also the only messaging mode that is endorsed by the WS-I Basic Profile

Page 26: Advanced soa and web services

Style – what that means• "encoded" means that there is an additional set of rules outside of

WSDL that imbue the XML data with some meaning. These rules specify how "something" is encoded/serialized to XML and then later decoded/de-serialized from XML back to "something". This set of rules (encoding) is identified by the encodingStyle attribute. If you do not know the encoding you cannot communicate with the web service endpoint. The encoding can be any set of rules however most of the time you will see encodingStyle="http://schemas.xmlsoap.org/soap/encoding" which refers to the dreaded SOAP Encoding. That encoding was originally designed to help in the serialization and de-serialization of data structures used in most programming languages even of entire object graphs (something not supported under XML Schema). However it was ambiguous enough so that two separate vendor implementations of the encoding may not work together. For obvious reasons "encoded" is not endorsed by the WS-I Basic Profile

Page 27: Advanced soa and web services

Use – what that means• In the "Document” mode of messaging, a SOAP Body element contains

an XML document fragment, a well-formed XML element that contains arbitrary application data (text and other elements)

• In the “Document” Style the message parts appear directly under the <soap:body> element. There are no SOAP formatting rules for what the <soap:body> contains. The server application is responsible for mapping the server objects (parameters, method calls, and so forth) and the values of the XML documents. (Through XSDs)

• “Document” also means that the content of <soap:Body> is specified by XML Schema defined in the <wsdl:type> section. It does not need to follow specific SOAP conventions. In short, the SOAP message is sent as one "document" in the <soap:Body> element without additional formatting rules having to be considered.

Page 28: Advanced soa and web services

Use – what that means • The “RPC” mode of messaging enables SOAP messages to model calls

to procedures or method calls with parameters and return values. • The RPC style specifies that the <soap:body> contains an element with

the name of the Web method being invoked. This element in turn contains an entry for each parameter and the return value of this method.

Page 29: Advanced soa and web services

RPC/EncodedRPC/Encoded Example• WSDL looks like the following<message name="Request">

<part name="x" type="xsd:int"/> <part name="y" type="xsd:float"/>

</message>

<message name="empty"/>

<portType name=“port"> <operation name=“method">

<input message="Request"/> <output message="empty"/>

</operation> </portType>

<binding .../>

Page 30: Advanced soa and web services

RPC/EncodedRPC/Encoded Example• The instance message looks like the following<soap:envelope>

<soap:body> <method>

<x xsi:type="xsd:int">5</x> <y xsi:type="xsd:float">5.0</y>

</method> </soap:body>

</soap:envelope>

Page 31: Advanced soa and web services

RPC/EncodedAdvantages• Simple WSDL• The operation is there in the message, so the receiver has an easy

time dispatching this message to the implementation of the operation.

Disadvantages• You cannot easily validate this message since only the

<x ...="">5</x> and <y ...="">5.0</y> lines contain things defined in a schema; the rest of the soap:body content comes from WSDL definitions. There is no schema based validation possible.

• The type encoding information (such as xsi:type="xsd:int") is usually just overhead, which degrades throughput performance.

• Not WS-I compliant

Page 32: Advanced soa and web services

RPC/LiteralRPC/Literal Example• WSDL looks like the following

<message name="Request"> <part name="x" type="xsd:int"/> <part name="y" type="xsd:float"/>

</message>

<message name="empty"/>

<portType name=“port"> <operation name=“method">

<input message="Request"/> <output message="empty"/>

</operation> </portType>

<binding .../>

Page 33: Advanced soa and web services

RPC/LiteralRPC/Literal Example• The instance message looks like the following

<soap:envelope> <soap:body>

<method> <x>5</x> <y>5.0</y>

</method> </soap:body>

</soap:envelope>

Page 34: Advanced soa and web services

RPC/LiteralAdvantages• Simple WSDL• The operation name still appears in the message. Routing is still

very easy• The type encoding info is eliminated. Eliminates the overhead of

passing types explicitly• RPC literal is WS-I compliant.

Disadvantages• You still cannot easily validate this message since only the

<x ...="">5</x> and <y ...="">5.0</y> lines contain things defined in a schema; the rest of the soap:body content comes from WSDL definitions.

Page 35: Advanced soa and web services

Document/LiteralDocument/Literal Example• WSDL looks like the following<types>

<schema> <element name="xElement" type="xsd:int"/> <element name="yElement" type="xsd:float"/>

</schema> </types>

<message name="Request"> <part name="x" element="xElement"/> <part name="y" element="yElement"/>

</message>

<message name="empty”> </message>

<portType name=“port"> <operation name="method">

<input message="Request"/> <output message="empty"/>

</operation> </portType>

Page 36: Advanced soa and web services

Document/LiteralDocument/Literal Example• The instance message looks like the following<soap:envelope>

<soap:body> <x>5</x> <y>5.0</y>

</soap:body> </soap:envelope>

Page 37: Advanced soa and web services

Document/LiteralAdvantages• You can finally validate this message with any XML validator. Everything

within soap:body is defined in a schema. • There is no type encoding information. Eliminates the overhead, lighter

message• Document/literal is WS-I compliant Disadvantages• The operation name in the SOAP message is lost. Without the name,

dispatching can be difficult, and sometimes impossible. (The only option is to pass the method name on the SOAP header as SOAPAction and the WS runtime will route the request on to the correct code)

• WS-I only allows one child of soap:body in a SOAP message, but this example has two children. But this is more of not a very serious compliance issue.

• The WSDL is more complicated.

Page 38: Advanced soa and web services

Document/Literal WrappedDocument/Literal Wrapped Example• WSDL looks like the following

<types> <schema>

<element name="method"> <complexType> <sequence>

<element name="x" type="xsd:int"></element> <element name="y" type="xsd:float"></element>

</sequence> </complexType>

</element> <element name="Response">

<complexType></complexType> </element>

</schema> </types>

<message name="Request"> <part name="parameters" element="method"/>

</message> <message name="empty">

<part name="parameters" element="Response"/> </message>

<portType name= "port"> <operation name="method">

<input message="Request"/> <output message="empty"/>

</operation> </portType>

Page 39: Advanced soa and web services

Document/Literal WrappedDocument/Literal Wrapped Example• The instance message looks like the following<soap:envelope>

<soap:body> <method>

<x>5</x> <y>5.0</y>

</method> </soap:body>

</soap:envelope>

Page 40: Advanced soa and web services

Document/Literal WrappedAdvantages• Everything that appears in soap:body is defined by the schema, so you

can easily validate this message. • The method name appears in the SOAP message. • There is no type encoding information and overhead is removed• Document literal is WS-I compliant, and the wrapped pattern meets the

WS-I restriction that the SOAP message's soap:body has only one child.

Disadvantages• The WSDL is very complicated and not very human readable.• Although WSDL allows overloaded methods, if you use overloaded

methods with Document/Literal Wrapped pattern of WSDL, the problem is: This pattern requires a wrapper element to have the same name as the operation, and there is no way to differentiate overloaded operations.

Page 41: Advanced soa and web services

Interoperability - conclusionsComparison between style/use

RPC-Encoded Document-Literal

Interoperability Is less interoperable due to incompatibility in SOAP encoding across platforms

Is more interoperable and recommendedby WS-I

Performance May yield worse performance dueto processing overhead required

to encode payloads

No Encoding overhead

Modifiability In theory yields better modifiabilitybecause service interfaces are

closer to programming languageinterfaces with operations and parameters.

This similarity also enablesthe use of automatic object to-

WSDL translation.

Is usually harder to implement becausethe XML schema definitions

and the code to process and transformthe XML documents are usually

not created automatically

In practice, any change to the syntaxof an operation requires

changes in the service users, resultingin increased coupling.

Yields less coupling. There is moreflexibility to change the business

document without affecting all serviceusers.

Page 42: Advanced soa and web services

WS-I Basic Profile• WS-I basic profile specifications can be found

here : http://ws-i.org/profiles/BasicProfile-2.0-WGD.html

• It specifies the ground rules of how you can make your web services interoperable across platforms

• Each element in the WSDL and SOAP and the restrictions on each of them is defined and discussed.

Page 43: Advanced soa and web services

Asynchronous servicesAsynchronous Service Impelmentation with JAX-WS

• JAX-WS Provides out of the box support for Producing and consuming Aysnchronous Web Services

• When implementing asynchronous request-response in your client, rather than invoking the operation directly, you invoke an asynchronous flavor of the same operation.

• For example, rather than invoking an operation called addNumbers directly, you would invoke addNumbersAsync instead.

• The asynchronous flavor of the operation always returns void, even if the original operation returns a value.

Page 44: Advanced soa and web services

Asynchronous services – Client APIAsynchronous Service Client with JAX-WS – Implementation steps

• Create the asynchronous client. • Create an external binding declaration file to enable the creation

of the asynchronous methods. • Update your build.xml file to compile the asynchronous client. • Run the Ant target to build the AsyncClient.

• One of the greatest advantages of the Client Asyc API is that it removes the dependency on how the Server implements the Service. This virtually allows you to invoke a Synchronous service on the server in a Async mode !

Page 45: Advanced soa and web services

JAX-WS Async Client APIAsynchronous Service Impelmentation with JAX-WS –

Creating the Asynchronous client program• The way of coding the Async Client – Sample

code is attached belowpublic class AsyncClient {

private AddNumbersPortType port = null;

protected void setUp() throws Exception { AddNumbersService service = new AddNumbersService(); port = service.getAddNumbersPort(); String serverURI = System.getProperty("wls-server"); ((BindingProvider) port).getRequestContext().put( BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://" + serverURI + "/JAXWS_ASYNC/AddNumbersService"); }

//Continued ……

Page 46: Advanced soa and web services

JAX-WS Async Client API/**Asynchronous callback handler - Class*/

class AddNumbersCallbackHandler implements AsyncHandler<AddNumbersResponse> { private AddNumbersResponse output; public void handleResponse(Response<AddNumbersResponse> response) { try { output = response.get();}

catch (ExecutionException e) { e.printStackTrace();} catch (InterruptedException e) { e.printStackTrace();}

} AddNumbersResponse getResponse() { return output; } }

public void AddNumbersTestDrive() throws Exception { int number1 = 10; int number2 = 20; AddNumbersCallbackHandler callbackHandler = new AddNumbersCallbackHandler(); Future<?> resp = port.addNumbersAsync(number1, number2,callbackHandler);

// For the purposes of a test, block until the async call completes resp.get(5L, TimeUnit.MINUTES); int result = callbackHandler.getResponse().getReturn(); }}

Page 47: Advanced soa and web services

Asynchronous services – Client API• To generate asynchronous polling and callback methods in the

service endpoint interface when the WSDL is compiled, enable the jaxws:enableAsyncMapping binding declaration in the WSDL file.

• You can create an external binding declarations file that contains all binding declarations for a specific WSDL or XML Schema document. Then, pass the binding declarations file to the <binding> child element of the wsdlc, jwsc, or clientgen Ant task.

Page 48: Advanced soa and web services

JAX-WS Async Client API• The following example shows the content of the

bindings file<!-- File named jaxws-binding.xml -->

<bindingsxmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"wsdlLocation="AddNumbers.wsdl"xmlns="http://java.sun.com/xml/ns/jaxws">

<bindings node="wsdl:definitions"><package name="examples.webservices.async"/><enableAsyncMapping>true</enableAsyncMapping>

</bindings>

</bindings>

Page 49: Advanced soa and web services

JAX-WS Async Client API• The following example shows the content of the Client

Gen Task – The bindings mapping on this task will point to the binding XML file which is created

<!– build.xml -->

<taskdef name="clientgen"classname="weblogic.wsee.tools.anttasks.ClientGenTask" />

<target name="build_client">

<clientgen type="JAXWS“ wsdl="AddNumbers.wsdl“ destDir="${clientclasses.dir}"packageName="examples.webservices.async.client">

<binding file="jaxws-binding.xml" /></clientgen>

<javac srcdir="${clientclass-dir}" destdir="${clientclass-dir}“ includes="**/*.java"/>

<javac srcdir="src" destdir="${clientclass-dir}"includes="examples/webservices/hello_world/client/**/*.java"/>

</target>

....

Page 50: Advanced soa and web services

Some design tips for WS• Keep it Simple, or do the simplest thing that works

• Evaluate your technology options – Pick the latest runtime supported on your infrastructure, especially when developing new Services. This helps you to make use of Performance improvements

• Try to avoid using propreitary features of the infrastructure provider. E.g: Weblogic provides its own streaming XML parser, do not use it – use the STAX instead. This will make sure your code is portable with minimal changes

• Use Document/Literal style and use as much as possible

Page 51: Advanced soa and web services

Some design tips for WS• Send only necessary information on Exceptions back to the client

• Implement throttling for your services

• Implement RBAC for all applicable services

• Check all fields which are directly used on SQL queries for possibility of a Injection attack

• Evaluate your granularity and determine what is right for you. Move towards business services and not Objects. Do not build SOAP services with dynamic granularity

Page 52: Advanced soa and web services

Some design tips for WS• Evaluate REST as an option where there is not much of a need for

significant infrastructure support based on metadata

• Consider implementing Asynchrounous services wherever your provider takes more time to process the request

• Try to confirm to well formed XSDs for all the XML messages. Check your XML repository to see if there are existing XSDs which will fit the bill for your object structure. We do not need to create another one.

• Please make interoperability considerations – like usage of datatypes, when your service is going to be called from .NET to Java or vice versa.

Page 53: Advanced soa and web services

Some design tips for WS• If your service is a reusable component, definitely

consider publishing it on a UDDI.

• UDDIs can be internal or public.

• Discoverability will drive reusability of your service.

Page 54: Advanced soa and web services

Thank you

Q & A

Sreekanth Narayanan