Sie sind auf Seite 1von 123

XML/SCHEMA Web services interoperability in general, is the Basic Profile 1.

0 (BP), published by the Web Services Interoperability Organization (WS-I). The BP provides a set of rules that govern how applications make use of common Web service technologies so that everyone is speaking the same language. SOAP messages serve as a network envelope for exchanging XML documents and data. There is an ancillary specification called SOAP Messages with Attachments (SwA). SwA defines a message format for attaching binary data (images, sound files, documents, and so on) to SOAP messages. WSDL (Web Services Description Language) is a standard for describing the structure of the XML data exchanged between two systems using SOAP. UDDI (Universal Description, Discovery, and Integration) defines a standard set of Web service operations (methods) that are used to store and look up information about other Web service applications. In other words, UDDI defines a standard SOAP-based interface for a Web services registry. You can use a UDDI registry to find a particular type of Web service, or to find out about the Web services hosted by a specific organization. XML Namespaces (Objective 1.3) An XML namespace provides a qualified name for an XML element or attribute, the same way that a Java package provides a qualified name for a Java class. Creating XML documents based on multiple markup languages is often desirable. We can define a standard markup language for address information, the Address Markup Language, to be used whenever an XML document needs to contain address information. An instance of Address Markup is: <?xml version="1.0" encoding="UTF-8" ?> <address category="business" > <name>Amazon.com</name> <street>1516 2nd Ave</street> <city>Seattle</city> <state>WA</state> <zip>90952</zip> </address> If the purchase-order document has its own schema (defined by the Purchase Order Markup Language) and the address information has its own schema (defined by the Address Markup Language), We use namespaces. We can state that the address elements conform to Address Markup by declaring the namespace of Address Markup in the address element. We do the same thing for the purchase order elements by declaring, in the purchaseOrder element, that they conform to the Purchase Order Markup. The scope of a default namespace applies only to the element and its descendants, so the xmlns used in the address element applies only to the address, name, street, city, state, and zip elements.

The default xmlns declared in the purchaseOrder element applies to all the elements except the address elements, because the address element overrides the default namespace of the purchaseOrder element to define its own default namespace. To simplify things, XML Namespaces defines a shorthand notation for associating elements and attributes with namespaces. You can assign an XML namespace to a prefix, then use that prefix to fully qualify each element name. <?xml version="1.0" encoding="UTF-8" ?> <purchaseOrder orderDate="2003-09-22" xmlns="http://www.Monson-Haefel.com/jwsbook/PO"> <accountName>Amazon.com</accountName> <accountNumber>923</accountNumber> <address xmlns="http://www.Monson-Haefel.com/jwsbook/ADDR"> <name>AMAZON.COM</name> <street>1850 Mercer Drive</street> <city>Lexington</city> <state>KY</state> <zip>40511</zip> </address> <book> <title>J2EE Web Services</title> <quantity>300</quantity> <wholesale-price>29.99</wholesale-price> </book> <total>8997.00</total> </purchaseOrder> <?xml version="1.0" encoding="UTF-8" ?> <po:purchaseOrder orderDate="2003-09-22" xmlns:po="http://www.Monson-Haefel.com/jwsbook/PO" xmlns:addr="http://www.Monson-Haefel.com/jwsbook/ADDR"> <po:accountName>Amazon.com</po:accountName> <po:accountNumber>923</po:accountNumber> <addr:address> <addr:name>AMAZON.COM</addr:name> <addr:street>1850 Mercer Drive</addr:street> <addr:city>Lexington</addr:city> <addr:state>KY</addr:state> <addr:zip>40511</addr:zip> </addr:address> <po:book> <po:title>J2EE Web Services</po:title> <po:quantity>300</po:quantity> <po:wholesale-price>29.99</po:wholesale-price> </po:book> <po:total>8997.00</po:total> </po:purchaseOrder>

URI used for the XML namespace should be unique to that markup language, but it doesn't have to point to an actual resource or document. In XML-speak, a prefix combined with an element name is called a QName, which stands for "qualified name." A QName has two parts, the XML namespace and the local name. In addr:street, http://www.Monson-Haefel.com/jwsbook/ADDR is the namespace and street is the local name. Namespaces help avoid name collisions, where two elements from different markups share a common local name. For example, a WSDL document can use Monson-Haefel's postal address element as well as the SOAP-binding address element in the same document. Although both elements are named address, they belong to different namespaces with different QNames, so there is no name conflict. <?xml version="1.0" encoding="UTF-8" ?> <definitions name="Address-Update" targetNamespace="http://www.monson-haefel.org/jwsbook/Address-Update" xmlns:tns="http://www.monson-haefel.org/jwsbook/Address-Update" xmlns:addr="http://www.Monson-Haefel.com/jwsbook/ADDR" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/"> <message name="AddressMessage"> <part name="address" element="addr:address" /> </message> <service name="AddressUpdateService"> <documentation>Update a customers mailing address</documentation> <port name="AddressUpdate_Port" binding="tns:AddressUpdate_Binding"> <soap:address location="http://www.monson-haefel.org/jwsbook/BookPrice" /> </port> </service> </definitions> XML parsers and other tools can use XML namespaces to process, sort, and search XML elements in a document according to their QNames. XML Schema To address limitations of DTDs, the W3C (World Wide Web Consortium), which manages the fundamental XML standards, created a new way to describe markup languages called XML schema. DTD failed to address data typing. <?xml version="1.0" encoding="UTF-8"?> <!ELEMENT address (street+, city, state, zip)> <!ELEMENT street (#PCDATA) > <!ELEMENT city (#PCDATA) > <!ELEMENT state (#PCDATA) > <!ELEMENT zip (#PCDATA) > <!ATTLIST address category CDATA #REQUIRED >

XML schema facilitates type inheritance, which allows simple or complex types to be extended or restricted to create new types. In addition, XML schema supports the use of XML namespaces to create compound documents composed of multiple markup languages. Specifically it defines which elements and attributes are used in a markup language, how they are ordered and nested, and what their data types are. A schema describes the structure of an XML document in terms of complex types and simple types. Complex types describe how elements are organized and nested. Simple types are the primitive data types contained by elements and attributes. The XML schema specification defines 44 standard simple types, called built-in types. The builtin types are the standard building blocks of an XML schema document. They are members of the XML schema namespace, "http://www.w3.org/2001/XMLSchema". All built-in simple and complex types are ultimately derived from anyType, which is the ultimate base type, like the Object class in Java. The names of XML schema types are case-sensitive. When an element declares that it is of a particular type, it must specify both the namespace and the name of that type exactly as the type declares them. A complex type may contain a sequence of elements that are simple types or other complex types. The content pattern for the <complextType> element is: annotation? (simpleContent | complexContent | ((group | all | choice | sequence)? (attribute | attributeGroup)* anyAttribute?))) A complex type may also define its own attributes. <?xml version="1.0" encoding="UTF-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:mh="http://www.Monson-Haefel.com/jwsbook" targetNamespace="http://www.Monson-Haefel.com/jwsbook" > <element name="purchaseOrder" type="mh:PurchaseOrder" /> <element name="address" type="mh:USAddress" /> <complexType name="PurchaseOrder"> <sequence> <element name="accountName" type="string" /> <element name="accountNumber" type="unsignedShort" /> <element name="shipAddress" type="mh:USAddress" /> <element name="billAddress" type="mh:USAddress" /> <element name="book" type="mh:Book" /> <element name="total" type="float" /> </sequence> <attribute name="orderDate" type="date"/> </complexType> <complexType name="USAddress">

<sequence> <element name="name" type="string" /> <element name="street" type="string" /> <element name="city" type="string" /> <element name="state" type="string" /> <element name="zip" type="string" /> </sequence> </complexType> <complexType name="Book"> <sequence> <element name="title" type="string" /> <element name="quantity" type="unsignedShort" /> <element name="wholesale-price" type="float" /> </sequence> </complexType> </schema> An instance of the above schema is shown below: <?xml version="1.0" encoding="UTF-8"?> <po:purchaseOrder orderDate="2003-09-22" xmlns:po="http://www.Monson-Haefel.com/jwsbook"> <accountName>Amazon.com</accountName> <accountNumber>923</accountNumber> <shipAddress> <name>AMAZON.COM</name> <street>1850 Mercer Drive</street> <city>Lexington</city> <state>KY</state> <zip>40511</zip> </shipAddress> <billAddress> <name>Amazon.com</name> <street>1516 2nd Ave</street> <city>Seattle</city> <state>WA</state> <zip>90952</zip> </billAddress> <book> <title>J2EE Web Services</title> <quantity>300</quantity> <wholesale-price>24.99</wholesale-price> </book> <total>8997.00</total> </po:purchaseOrder> The multiplicity of an element, the number of times it occurs in an instance document, is controlled by occurrence constraints, which are declared by the maxOccurs and minOccurs attributes <element name="street" type="string" minOccurs="1" maxOccurs="2" /> The default value for both maxOccurs and minOccurs is "1",

Attribute types declare the use occurrence constraint, which may be "required", "optional", or "prohibited", indicating that the attribute must, may, or may not be used, respectively. The default is "optional". An attribute may also have a default value, to be assigned if no value is explicitly declared in the instance document. The default attribute can be used only when the use attribute is "optional" <complexType name="USAddress"> <sequence> <element name="name" type="string" /> <element name="street" type="string" /> <element name="city" type="string" /> <element name="state" type="string" /> <element name="zip" type="string" /> </sequence> <attribute name="category" type="string" default="business" use=optional /> </complexType> An attribute may also be declared fixed: A fixed value is assigned to the attribute no matter what value appears in the XML instance document. Unlike sequence, which defines the exact order of child elements, the XML schema all element allows the elements in it to appear in any order. Each element in an all group may occur once or not at all; no other multiplicity is allowed. In other words, minOccurs is always "0" and maxOccurs is always "1". name, street, and zip elements must be present in the instance document, but the city and state elements may be absent. The elements can be in any order, but none of the elements may occur more than once. <?xml version="1.0" encoding="UTF-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:mh="http://www.Monson-Haefel.com/jwsbook" targetNamespace="http://www.Monson-Haefel.com/jwsbook" > ... <complexType name="USAddress"> <all> <element name="name" type="string" /> <element name="street" type="string" /> <element name="city" type="string" minOccurs="0"/> <element name="state" type="string" minOccurs="0"/> <element name="zip" type="string" /> </all> </complexType> ... </schema> The <choice> Element

The <choice> element allows one of the elements contained in the <choice> element to be present in the containing element. <complexType name="ComputerOwner"> <sequence> <element name="name" type="string"/> <choice minOccurs="1" maxOccurs="2"> <element name="desktop" type="string"/> <element name="notebook" type="string"/> <element name="handheld" type="string"/> </choice> </sequence> </complexType> So, xml: <name>Ivan</name> <notebook>MacBook</notebook> <desktop>Big Bertha</desktop> The <simpleContent> Element The <simpleContent> element enables adding of attributes to global simple types. This element can also be used to extend or restrict attributes on other complex types with simple content. <element name="PriceAndCurrency" type="tns:PriceWithCurrency"/> <complexType name="PriceWithCurrency"> <simpleContent> <extension base="decimal"> <attribute name="currency" type="string"/> </extension> </simpleContent> </complexType> XML: <tns:PriceAndCurrency xmlns:tns="http://www.ivan.com/PriceWithCurrencySchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.ivan.com/PriceWithCurrencySchema PriceWithCurrencySchema.xsd" currency="USD"> 168.4 </tns:PriceAndCurrency> A schema may also declare global elements, which XML instance documents can refer to directly. Global elements are declared as direct children of the schema element, rather than children of a complex type. The root element of a valid XML document must have a corresponding global element declaration in the schema. A schema may define more than one global element. XML schema also supports global attributes that can be referred to anywhere in the schema, and that

provide a consistent attribute name and type across elements. An example of a standard global attribute is xml:lang, which any element can use to indicate the language used in an element's value. In a nutshell, global elements and attributes are declared as direct children of the schema element, while local elements and attributes are not; they are the children of complex types. Global elements and attributes must always be qualified, which means that in an XML instance you must prefix them to form a QName. The exception is when a global element is a member of the default namespace, in which case it does not have to be qualified with a prefixall unqualified elements are assumed to be part of the default namespace. The default namespace does not apply to global attributes; global attributes must always be prefixed. XML schema defines two attributes, elementFormDefault and attributeFormDefault, that determine whether local elements in an XML instance need to be qualified with a prefix or not. To validate an XML document against one or more schemas, you need to specify which schemas to use by identifying the schemas' locations, using the schemaLocation attribute, which is an XML schema-instance attribute. Each schema is listed in an xsi:schemaLocation attribute as a namespacelocation pair, which associates a namespace with a physical URL. xsi:schemaLocation="http://www.Monson-Haefel.com/jwsbook http://www.Monson-Haefel.com/jwsbook/po.xsd http://www.w3.org/2001/XMLSchema-instance http://www.w3.org/2001/XMLSchema.xsd"> JAX-RPC can map most derived complex types to Java beans, but not all. Most object-oriented languages do not support the full scope of inheritance defined by the XML schema specification. For this reason, you should use type inheritance in schemas with care Complex types can use two types of inheritance: extension and restriction. Both allow you to derive new complex types from existing complex types. 1. Extension broadens a derived type by adding elements or attributes not present in the base type, 2. Restriction narrows a derived type by omitting or constraining elements and attributes defined by the base type. <element name="address" type="mh:Address"/> <complexType name="Address"> <sequence> <element name="name" type="string"/> <element name="street" type="string" maxOccurs="unbounded"/> <element name="city" type="string"/> <element name="country" type="string"/> </sequence>

<attribute name="category" type="string" default="business"/> </complexType> <complexType name="USAddress"> <complexContent> <extension base="mh:Address"> <sequence> <element name="state" type="string"/> <element name="zip" type="string"/> </sequence> </extension> </complexContent> </complexType> With Restriction, you simply redefine or omit those elements and attributes that change, and list all the other elements and attributes exactly as they were in the base type. <complexType name="BriefUSAddress"> <complexContent> <restriction base="mh:USAddress"> <sequence> <element name="name" type="string"/> <element name="street" type="string"/> <element name="zip" type="string"/> </sequence> <attribute name="category" type="string" default="business"/> </restriction> </complexContent> </complexType> The derived type, BriefUSAddress, contains the name, street, and zip elements, but not the city, state, and country elements, we will first have to make these omitted elements omittable in the base type by making them optional there ie minOccurs= 0). Rules for restriction: 1. You cannot omit an element from a restriction unless the parent type declared it to be optional(minOccurs="0"). 2. In addition, the derived type's occurrence constraints cannot be less strict than those of its base type. derived types can be used polymorphically with elements of the base type. In other words, you can use a derived type in an instance document in place of the base type specified in the schema. <element name="address" type="mh:Address"/> <element name="purchaseOrder" type="mh:PurchaseOrder"/> <complexType name="PurchaseOrder"> <sequence> <element name="accountName" type="string"/> <element name="accountNumber" type="unsignedShort"/>

<element name="shipAddress" type="mh:Address"/> <element name="billAddress" type="mh:Address"/> <element name="book" type="mh:Book"/> <element name="total" type="float"/> </sequence> <attribute name="orderDate" type="date"/> </complexType> <purchaseOrder orderDate="2003-09-22" xmlns="http://www.Monson-Haefel.com/jwsbook" xmlns:mh="http://www.Monson-Haefel.com/jwsbook" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.Monson-Haefel.com/jwsbook http://www.Monson-Haefel.com/jwsbook/po2.xsd"> <accountName>Amazon.com</accountName> <accountNumber>923</accountNumber> <shipAddress xsi:type="mh:UKAddress"> <name>Amazon.co.uk</name> <street>Ridgmont Road</street> <city>Bedford</city> <country>United Kingdom</country> <postcode>MK43 0ZA</postcode> </shipAddress> <billAddress xsi:type="mh:BriefUSAddress"> <name>Amazon.com</name> <street>1516 2nd Ave</street> <zip>90952</zip> </billAddress> <book> <title>Java Web Services</title> <quantity>300</quantity> <wholesale-price>24.99</wholesale-price> </book> <total>8997.00</total> </purchaseOrder> The xsi:type attribute explicitly declares Explicitly declaring an element's type with xsi:type tells the parser to validate the element against the derived type instead of the type declared in the schema. You can declare complex types to be abstract much as you do Java classes. <complexType name="Address" abstract="true"> <sequence> <element name="name" type="string"/> <element name="street" type="string" maxOccurs="unbounded"/> <element name="city" type="string"/> <element name="country" type="string"/> </sequence> <attribute name="category" type="string" default="business"/> </complexType>

If we add abstract="true" to the earlier definition of Address, as in the above snippet, it cannot be used directly in an instance document. You can also declare complex types to be final, just as Java classes can be final, to prevent a complex type from being used as a base type for restriction or extension. The possible values for the final attribute are "restriction", "extension", and "#all". final="restriction" can be extended but not restricted final=#all type cannot used as a base type at all XML schema allows us to create new simple types that are derived from existing simple types in order to constrain further the range of possible values that a simple type may represent. The content pattern for the <simpleType> element is: annotation? (restriction | list | union) restrict the built-in float type to create a new type called Total. <simpleType name="Total"> <restriction base="float"> <minInclusive value="0"/> <maxExclusive value="100000"/> </restriction> </simpleType> Simple type facets are: maxInclusive maxExclusive minInclusive minExclusive pattern ---Regexp for value enumeration ---Set of allowed values whiteSpace ---Constrain. regular expression is used to verify that the contents of an element or attribute adhere to a predefined character pattern. <simpleType name="Total"> <restriction base="float"> <pattern value="[0-9]+\.[0-9]{2}" /> <minInclusive value="0"/> <maxExclusive value="100000" /> </restriction> </simpleType> "[0-9]+\.[0-9]{2}" specifies that there must be at least one digit before the decimal point and exactly two digits following the decimal point. The pattern facet is commonly applied to string types <simpleType name="USZipCode"> <restriction base="string"> <pattern value="[0-9]{5}(-[0-9]{4})?" />

</restriction> </simpleType> <complexType name="USAddress" final="extension"> <complexContent> <extension base="mh:Address"> <sequence> <element name="state" type="string"/> <element name="zip" type="mh:USZipCode"/> </sequence> </extension> </complexContent> The enumeration facet restricts the value of any simple type (except boolean) to a set of distinct values. <simpleType name="USState"> <restriction base="string"> <enumeration value="AK"/> <!-- Alaska --> <enumeration value="AL"/> <!-- Alabama --> <enumeration value="AR"/> <!-- Arkansas --> <!-- and so on --> </restriction> </simpleType> A list is a sequence of simple-type values separated by white space. <simpleType name="USStateList"> <list itemType="mh:USState"/> </simpleType> In an instance document, an element of the USStateList type could contain zero or more state abbreviations separated by spaces. e.g: <list-of-states>CA NY FL AR NH</list-of-states> A union is a set of valid simple types. The union type USStateOrZipUnion allows the value to be either a USStateList type or a USZipCode type. <simpleType name="USStateOrZipUnion"> <union memberTypes="mh:USStateList mh:USZipCode"/> </simpleType> e.g: <!-- valid use of union type --> <location>CA NJ AK</location> <location>94108</location> <!-- invalid use of union type --> <location>94108 CA 554011 MN</location> Anonymous types: You can combine an element declaration with a complex or simple type declaration to create an anonymous type. An anonymous type is not named and cannot be referred to outside the element that declares it. Anonymous types can be nested as well:

<element name="purchaseOrder"> <complexType> <sequence> <element name="accountName" type="string"/> <element name="accountNumber" type="unsignedShort"/> <element name="shipAddress" type="mh:Address"/> <element name="billAddress" type="mh:Address"/> <element name="book"> <complexType> <sequence> <element name="title" type="string"/> <element name="quantity" type="unsignedShort"/> <element name="wholesale-price" type="float"/> </sequence> </complexType> </element> <element name="total"> <simpleType> <restriction base='float'> <minInclusive value="0"/> <maxExclusive value="100000"/> <pattern value="[0-9]+\.[0-9]{2}"/> </restriction> </simpleType> </element> </sequence> <attribute name="orderDate" type="date"/> </complexType> </element> Anonymous types are not reusable, and you should employ them only when you know that the type won't be useful in other schemas. Importing and Including Schemas: An import allows you to combine schemas from different namespaces, <?xml version="1.0" encoding="UTF-8" ?> <schema targetNamespace="http://www.Monson-Haefel.com/jwsbook/PO" xmlns:po="http://www.Monson-Haefel.com/jwsbook/PO" xmlns:addr="http://www.Monson-Haefel.com/jwsbook/ADDR" xmlns="http://www.w3.org/2001/XMLSchema"> <import namespace="http://www.Monson-Haefel.com/jwsbook/ADDR" schemaLocation="http://www.Monson-Haefel.com/jwsbook/addr.xsd" /> . include lets you combine schemas from the same namespace.Including is useful when a schema becomes large and difficult to maintain. <?xml version="1.0" encoding="UTF-8" ?> <schema targetNamespace="http://www.Monson-Haefel.com/jwsbook/PO"

xmlns:po="http://www.Monson-Haefel.com/jwsbook/PO" xmlns:addr="http://www.Monson-Haefel.com/jwsbook/ADDR" xmlns="http://www.w3.org/2001/XMLSchema"> <include schemaLocation="http://www.Monson-Haefel.com/jwsbook/po.xsd" /> <import namespace="http://www.Monson-Haefel.com/jwsbook/ADDR" schemaLocation="http://www.Monson-Haefel.com/jwsbook/addr.xsd" /> . there are a couple of other schema languages, including DTDs, Schematron, RELAX-NG, and a few others. Of these, Schematron appears to be the best complement to XML schema, or at least to offer validation checks that XML schema cannot duplicate. Schematron is based on Xpath and XSLT and is used for defining context-dependent rules for validating XML documents.

SOAP 1.2 Web Service Standards


SOAP was originally an acronym for Simple Object Access Protocol. (Now it's just a name.) SOAP is just another XML markup language accompanied by rules that dictate its use. SOAP has a clear purpose: exchanging data over networks. In a nutshell, SOAP is a network application protocol. Web services can use One-Way messaging or Request/Response messaging. Advantages of SOAP: 1. The SOAP message format is defined by an XML schema, which exploits XML namespaces to make SOAP very extensible. 2. Another advantage of SOAP is its explicit definition of an HTTP binding, a standard method for HTTP tunneling. HTTP tunneling is the process of hiding another protocol inside HTTP messages in order to pass through a firewall unimpeded. Firewalls will usually allow HTTP traffic through port 80, but will restrict or prohibit the use of other protocols and ports. A SOAP message may have an XML declaration, which states the version of XML used and the encoding format. An XML declaration isn't mandatory. Web services are required to accept messages with or without them. Envelope may contain an optional Header element, and must contain a Body element. If you use a Header element, it must be the immediate child of the Envelope element, and precede the Body element. The Body element contains, in XML format, the actual application data being exchanged between applications. The Envelope element cannot contain any other children. <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header> <!-- Header blocks go here --> </soap:Header> <soap:Body> <!-- Application data goes here --> </soap:Body> </soap:Envelope>

The Header element contains information about the message (describe security credentials, transaction IDs, routing instructions, debugging information, payment tokens, or any other information about the message that is important in processing the data in the Body element.), e.g: <soap:Header> <mi:message-id>11d1def534ea:b1c5fa:f3bfb4dcd7:-8000</mi:message-id> <sec:Signature > <ds:Signature> <ds:SignedInfo> <ds:CanonicalizationMethod Algorithm= "http://www.w3.org/TR/2000/CR-xml-c14n-20001026"/> <ds:SignatureMethod Algorithm= "http://www.w3.org/2000/09/xmldsig#dsa-sha1"/> <ds:Reference URI="#Body"> <ds:Transforms> <ds:Transform Algorithm= "http://www.w3.org/TR/2000/CR-xml-c14n-20001026"/> </ds:Transforms> <ds:DigestMethod Algorithm= "http://www.w3.org/2000/09/xmldsig#sha1"/> <ds:DigestValue>u29dj93nnfksu937w93u8sjd9= </ds:DigestValue> </ds:Reference> </ds:SignedInfo> <ds:SignatureValue>CFFOMFCtVLrklR</ds:SignatureValue> </ds:Signature> </sec:Signature> </soap:Header> Each header block element must be identified by its own namespace. Each header block in the Header element should have its own namespace. Namespace xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" defines the namespace of the standard SOAP elementsEnvelope, Header, and Body. If a SOAP application receives a message based on some other namespace, it must generate a fault. Intermediaries in a SOAP message path must not modify the application-specific contents of the SOAP Body element, but they may, and often do, manipulate the SOAP header blocks. When processing a header block, each node reads, acts on, and removes the header block from the SOAP message before sending it along to the next receiver. Any node in a message path may also add a new header block to a SOAP message. SOAP 1.1 applications use the actor attribute to identify the nodes that should process a specific header block. SOAP also employs the mustUnderstand attribute to indicate whether a node processing the block needs to recognize the header block and know how to process it. The actor(in soap 1.1)/role(in soap 1.2) attribute You must identify the roles a node will play by declaring an actor attribute. In SOAP 1.2 this attribute has been renamed role. The actor attribute uses a URI (Uniform Resource Identifier) to identify the role that a node must perform in order to process that header block. When a

node receives a SOAP message, it examines each of the header blocks to determine which ones are targeted to roles supported by that node. A node may have many modules that operate on a message, and therefore many roles, so every node in a message path may identify itself with several different roles. A node may have many modules that operate on a message, and therefore many roles, so every node in a message path may identify itself with several different roles. There are three SOAP roles defined by the SOAP 1.2 specification: Next- Each SOAP intermediary and the ultimate SOAP receiver MUST act in this role. None-- SOAP nodes MUST NOT act in this role. Header blocks with this role will never be formally processed. ultimateReceiver-- The ultimate receiver MUST act in this role. The default value of the role attribute is http://www.w3.org/2003/05/soapenvelope/ role/ultimateReceiver. Additional roles may be specified by applications. Note: SOAP header blocks may be processed in arbitrary order. <soap:Header> <mi:message-id soap:actor/role="http://www.Monson-Haefel.com/logger" > 11d1def534ea:b1c5fa:f3bfb4dcd7:-8000 </mi:message-id> <proc:processed-by soap:actor/role=" http://schemas.xmlsoap.org/soap/actor/next"> <node> <time-in-millis>1013694680000</time-in-millis> <identity>http://www.customer.com</identity> </node> </proc:processed-by> </soap:Header> Only those nodes in the message path that identify themselves with the actor value "http://www.Monson- Haefel.com/logger" will process the message-id header block; all other nodes will ignore it. In addition to custom URIs like "http://www.Monson-Haefel.com/logger", SOAP identifies two standard roles for the actor attribute: next and ultimate receiver. The next role indicates that the next node in the message path must process the header. The next role has a designated URI, which must be used as the value of the actor attribute: "http://schemas.xmlsoap.org/soap/actor/next". The ultimate receiver role indicates that only the ultimate receiver of the message should process the header block. The protocol doesn't specify an explicit URI for this purpose; it's the absence of an actor attribute in the header block that signals that the role is ultimate receiver. In the above example, the next receiver in the message path, no matter what other purpose it may serve, should process the processed-by header block. If an intermediary node in the message path supports the logger role, then it should process the processed-by header block in addition to the message-id header block.

When a node processes a header block, it must remove it from the SOAP message. The node may also add new header blocks to the SOAP message. SOAP nodes frequently feign removal of a header block by simply modifying it, which is logically the same as removing it, modifying it, and then adding it back to the SOAP messagea little trick that allows a node to adhere to the SOAP specifications while propagating header blocks without losing any data. For example, the logger node may remove the message-id header block, but we don't want it to remove the processed-by header block, because we want all the nodes in the message path to add information to it. Therefore, the logger node will simply add its own data to the processed-by header block, then pass the SOAP message to the next node in the message path, as shown in the below example, after the logger node has processed the SOAP message. <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mi="http://www.Monson-Haefel.com/jwsbook/message-id" xmlns:proc="http://www.Monson-Haefel.com/jwsbook/processed-by"> <soap:Header> <proc:processed-by soap:actor="http://schemas.xmlsoap.org/soap/actor/next"> <node> <time-in-millis>1013694680000</time-in-millis> <identity>http://www.customer.com</identity> </node> <node> <time-in-millis>1013694680010</time-in-millis> <identity>http://www.Monson-Haefel.com/sales</identity> </node> </proc:processed-by> </soap:Header> <soap:Body> <!-- Application-specific data goes here --> </soap:Body> </soap:Envelope> Header blocks may indicate whether processing is mandatory or not by using the mustUnderstand attribute. The mustUnderstand attribute can have the value of either "1" or "0", to represent true and false, respectively( "true" and "false" are not allowed). If the mustUnderstand attribute is omitted, then its default value is "0" (false). When a header block has a mustUnderstand attribute equal to "1", it's called a mandatory header block. SOAP nodes must be able to process any header block that is marked as mandatory if they play the role specified by the actor attribute of the header block. If a node doesn't understand a mandatory header block, it must generate a SOAP fault (similar to a remote exception in Java) and discard the message; it must not forward the message to the next node in the message path the BP 1.0 requires this behavior. If a SOAP application uses Request/Response messaging, it's required to send a SOAP fault back to the sender; if it uses One-Way messaging, it's not. <soap:Header> <proc:processed-by

soap:actor="http://schemas.xmlsoap.org/soap/actor/next" soap:mustUnderstand="1" > <node> <time-in-millis>1013694684723</time-in-millis> <identity>http://local/SOAPClient2</identity> </node> .. If a node performs the role declared by a non-mandatory header block, and an application fails to understand the header (it doesn't recognize the XML structure or the namespace), it must remove the header block. Receivers should not reject a message simply because a header block targeted at some other node has not been processed (and removed). nodes are required to "mind their own business," WS-I Conformance Header Block An optional conformance header block that indicates that the SOAP message complies with the BP. <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" <soap:Header> <wsi:Claim conformsTo="http://ws-i.org/profiles/basic/1.0" xmlns:wsi="http://ws-i.org/schemas/conformanceClaim/" /> </soap:Header> <soap:Body sec:id="Body"> <!-- Application-specific data goes here --> </soap:Body> </soap:Envelope> A SOAP message can declare a separate Claim header for each profile it adheres to. SOAP Forwarding Intermediaries A SOAP forwarding intermediary must process a SOAP message, as described above, and additionally: Remove all processed SOAP header blocks. Remove all non-relayable header blocks that were targeted at the node but ignored during processing. Retain all relayable header blocks that were targeted at the node but ignored during processing. Relayable Header Blocks A SOAP header block may have a relay attribute that indicates whether the header block is relayable or not.
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:xml="http://www.w3.org/XML/1998/namespace"> <env:Header> <test:echoOk xmlns:test="http://example.org/ts-tests" env:role="http://www.w3.org/2003/05/soap-envelope/role/ultimateReceiver" env:mustUnderstand="1" env:relay="false" env:anyAttribute="any value"> foo

</test:echoOk> <test1:echoOk1 xmlns:test1="http://example1.org/ts-tests" env:role="http://www.w3.org/2003/05/soap-envelope/role/next" env:mustUnderstand="0" env:relay="true" env:anyAttribute="any value"> foo </test1:echoOk1>

The relay attribute should only appear on the root element of a SOAP header block. If it appears elsewhere, it may be ignored. The following rules apply to the preservation of the XML data in a SOAP message by a SOAP forwarding intermediary: 1. The entire SOAP message must be preserved, except as specified in the following rules. 2. SOAP header blocks may be removed. 3. SOAP header blocks may be added. 4. White space characters may be added to or removed from: - Children of the SOAP Envelope element. - Children of the SOAP Header element. 5. Comment elements may be added to or removed from: - Children of the SOAP Envelope element. - Children of the SOAP Header element. 6. Attribute items may be added to: - The SOAP Envelope. - The SOAP Header. 7. Namespace attributes may be added to: - The SOAP Envelope. - The SOAP Header. 8. If the role attribute of a SOAP header block is Ultimate Receiver, then it may be omitted. 9. The mustUnderstand attribute of a SOAP header block can be transformed: - The value false may be substituted with 0. - The value true may be substituted with 1. - The attribute may be omitted if its value is false. 10. The relay attribute of a SOAP header block can be transformed: - The value false may be substituted with 0. - The value true may be substituted with 1. - The attribute may be omitted if its value is false. 11. The base URI of the document information item need not be maintained. 12. The base URI of element information items in the SOAP message may be changed or removed. 13. The character encoding property of the document information item may be changed orremoved. 14. All namespace information items in elements must be preserved. 15. Additional namespace information items may be added. SOAP Active Intermediaries Active intermediaries may also process SOAP messages in ways not described by SOAP header block(s) found in the incoming SOAP message. Example of services offered by SOAP active intermediaries are: Security services, annotation services, and content manipulation services. SOAP Messaging Modes

Except in the case of fault messages, SOAP does not specify the contents of the Body element (although it does specify the general structure of RPC-type messages). The Body element may contain any XML element or it can be empty. SOAP supports four modes of messaging (RPC/Literal, Document/ Literal, RPC/Encoded, and Document/Encoded). The following encoding types may be used in SOAP messages: SOAP encoding. Literal encoding. SOAP encoding: Describes how to map non-XML based data to a format that can be transferred in SOAP messages. Is less flexible and more restricted compared to XML. Is optional and does not have to be implemented in a SOAP node. Is not allowed by the WS-I Basic Profile. The WS-I Basic Profile prohibits use of all encodings, since this has been a cause of interoperability problems. Literal means that the XML document fragment can be validated against its XML schema. Messaging modes using the literal encoding are: Document/Literal RPC/Literal The WS-I Basic Profile 1.1 defines the bindings as follows: A messaging mode is defined by its messaging style (RPC or Document) and its encoding style. The term "Literal" means that the XML document fragment can be validated against its XML schema. Document/Literal In the Document/Literal 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) that belongs to an XML schema and namespace separate from the SOAP message's. For example, a set of XML elements that describes a purchase order, embedded within a SOAP message, is considered an XML document fragment. <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mi="http://www.Monson-Haefel.com/jwsbook/message-id" xmlns:proc="http://www.Monson-Haefel.com/jwsbook/processed-by"> <soap:Header> <!-- Header blocks go here --> </soap:Header> <soap:Body> <po:purchaseOrder orderDate="2003-09-22" xmlns:po="http://www.Monson-Haefel.com/jwsbook/PO"> <po:accountName>Amazon.com</po:accountName> <po:accountNumber>923</po:accountNumber> ... <po:book> <po:title>J2EE Web Services</po:title>

<po:quantity>300</po:quantity> <po:wholesale-price>24.99</po:wholesale-price> </po:book> </po:purchaseOrder> </soap:Body> </soap:Envelope> Document/Literal Binding A "document-literal binding" is a wsdl:binding element whose child wsdl:operation elements are all document-literal operations. A "document-literal operation" is a wsdl:operation child element of wsdl:binding whose soapbind:body descendent elements specifies the use attribute with the value "literal" and, either: 1. The style attribute with the value "document" is specified on the child soapbind:operation element; or 2. The style attribute is not present on the child soapbind:operation element, and the soapbind:binding element in the enclosing wsdl:binding specifies the style attribute with the value "document"; or 3. The style attribute is not present on both the child soapbind:operation element and the soapbind:binding element in the enclosing wsdl:binding. Style can be any of below two marked yellow. <wsdl:binding name="TestWSSoapBinding" type="impl:TestWS"> <wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <wsdl:operation name="testIface"> <wsdlsoap:operation soapAction="" style="document"/> <wsdl:input name="testIfaceRequest"> <wsdlsoap:body use="literal"/> Advantages are that the interface of the service is less likely to change, even if there are changes in the parameter data structure. change is more likely to affect services that are concerned with the changed part, but is less likely to affect services processing other aspects. Drawbacks include the fact that you expose a complex data structure which may, to some extend, expose the inner workings of the service. If the inner workings change, the changes are more likely to cause ripples that affect clients of the service.

RPC/Literal
The RPC/Literal mode of messaging enables SOAP messages to model calls to procedures or method calls with parameters and return values. In RPC/Literal messaging, the contents of the Body are always formatted as a struct. An RPC request message contains the method name and the input parameters of the call. An RPC response message contains the return value and any output parameters (or a fault). In many cases, RPC/Literal messaging is used to expose traditional components (servlets, stateless session beans, CORBA object, Java RMI object, DCOM etc) as Web services.
public // Get public throws } interface BookQuote extends java.rmi.Remote { the wholesale price of a book float getBookPrice(String ISBN) RemoteException, InvalidISBNException;

This JAX-RPC service endpoint can use the RPC/Literal mode of messaging. The Web service uses two

SOAP messages: a request message and a reply message. The request message is sent from an initial sender to the Web service and contains the method name, getBookPrice, and the ISBN string parameter. The reply message is sent back to the initial sender and contains the price of the book as a float value.
<?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mh="http://www.Monson-Haefel.com/jwsbook/BookQuote"> <soap:Body> <mh:getBookPrice> <isbn>0321146182</isbn> </mh:getBookPrice> </soap:Body> </soap:Envelope>

And the response is:


<?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mh="http://www.Monson-Haefel.com/jwsbook/BookQuote" > <soap:Body> <mh:getBookPriceResponse> <result>24.99</result> </mh:getBookPriceResponse> </soap:Body> </soap:Envelope>

RPC/Literal Binding An "rpc-literal binding" is a wsdl:binding element whose child wsdl:operation elements are all rpcliteral operations. An "rpc-literal operation" is a wsdl:operation child element of wsdl:binding whose soapbind:body descendant elements specify the use attribute with the value "literal", and either: 1. The style attribute with the value "rpc" is specified on the child soapbind:operation element; or 2. The style attribute is not present on the child soapbind:operation element, and the soapbind:binding element in the enclosing wsdl:binding specifies the style attribute with the value "rpc". An advantage is that the datatypes you expose can be understood by all clients. A drawback is that if there is a new version of an operation in the service that needs, for instance, additional parameters then the clients need to upgrade as the service changes.

SOAP Faults
SOAP faults are returned to the receiver's immediate sender. When that sender receives the fault message, it may take some action, such as undoing operations, and may send another fault further upstream to the next sender if there is one. Faults are caused by improper message formatting, version mismatches, trouble processing a header, and application-specific errors. When a fault message is generated, the Body of the SOAP message must contain only a single Fault element and nothing else. The Fault element itself must contain a faultcode element and a faultstring element, and optionally faultactor and detail elements.
<?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mh="http://www.Monson-Haefel.com/jwsbook/BookQuote" > <soap:Body> <soap:Fault> <faultcode>soap:Client</faultcode> <faultstring>

The ISBN value contains invalid characters </faultstring> <faultactor>http://www.xyzcorp.com</faultactor> <detail> <mh:InvalidIsbnFaultDetail> <offending-value>19318224-D</offending-value> <conformance-rules> The first nine characters must be digits. The last character may be a digit or the letter 'X'. Case is not important. </conformance-rules> </mh:InvalidIsbnFaultDetail> </detail> </soap:Fault> </soap:Body> </soap:Envelope>

SOAP Standard Fault Codes: 1. Client 2. Server 3. VersionMismatch 4. MustUnderstand Clientault Fault Code The message received by the receiver is improperly structured or contains invalid data. The incoming message is properly structured, but it uses elements and namespaces in the Body element that the receiver doesn't recognize. MustUnderstand The incoming message contains a mandatory header block that the receiver doesn't recognize. VersionMismatch The incoming message specifies an XML namespace for the SOAP Envelope and its children (Body, Fault, Header) that is not the SOAP 1.1 namespace. Server The SOAP receiver has encountered an abnormal condition that prevents it from processing an otherwise valid SOAP message The Client fault code signifies that the node that sent the SOAP message caused the error, because there is something wrong with the message or its data, it's considered the fault of the client, the sender. The receiving node generates a Client fault if the message is not well formed, or contains invalid data, or lacks information that was expected, like a specific header. The Server fault code indicates that the node that received the SOAP message malfunctioned or was otherwise unable to process the SOAP message. This fault is a reflection of an error by the receiving node (either an intermediary or the ultimate receiver) and doesn't point to any problems with the SOAP message itself. In this case the sender can assume the SOAP message to be correct, and can redeliver it after pausing some period of time to give the receiver time to recover. VersionMismatch fault when it doesn't recognize the namespace of a SOAP message's Envelope element. For example, a SOAP 1.1 node will generate a fault with a VersionMismatch code if it receives a SOAP 1.2 message, because it finds an unexpected namespace in the Envelope. Applies only to the namespace assigned to the Envelope, Header, Body, and Fault elements. If a header block is targeted at the current node (via the actor attribute) and sets the mustUnderstand attribute equal to "1", then the node is required to know how to process the header block. If the node doesn't recognize the header block, it must generate a fault with the MustUnderstand code. It is also possible to use non-standard SOAP fault codes, which belong to a separate namespace.
<?xml version="1.0" encoding="UTF-8"?> <soap:Envelope

xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/06/secext"> <soap:Body> <soap:Fault> <faultcode>wsse:InvalidSecurityToken</faultcode> <faultstring>An invalid security token was provided</faultstring> <detail/> </soap:Fault> </soap:Body> </soap:Envelope>

Optionally, the faultstring element (its a must tag to use in case of fault message) can indicate the language of the text message using a special attribute, xml:lang.
<faultstring xml:lang="es" > El ISBN tiene letras invalidas </faultstring>

default is English (xml:lang="en") The faultactor element indicates which node encountered the error and generated the fault (the faulting node). This element is required if the faulting node is an intermediary, but optional if it's the ultimate receiver. The detail element of a fault message must be included if the fault was caused by the contents of the Body element (though its legal to have the detail element empty <detail/>), but it must not be included if the error occurred while processing a header block.

SOAP Over HTTP


SOAP messages sent over HTTP are placed in the payload of an HTTP request or response. Web services that use SOAP 1.1 with HTTP always use HTTP POST and not HTTP GET messages as HTTP POST requests have a payload area for the SOAP message to be tunneled.
POST /jwsbook/BookQuote HTTP/1.1 Host: www.Monson-Haefel.com Content-Type: text/xml; charset="utf-8" Content-Length: 295 SOAPAction=""

The HTTP POST message must contain a SOAPAction header field, but the value of this header field is not specified. The SOAPAction header field can improve throughput by providing routing information outside the SOAP payload. The BP requires that the SOAPAction header field be present and that its value be a quoted string that matches the value of the soapAction attribute declared by the corresponding WSDL document. If that document declares no soapAction attribute, the SOAPAction header field can be an empty string text/xml Content-Type to be used with SOAP over HTTP. It's possible to use others (for example, SOAP with Attachments would specify multipart/related) but it's not recommended. The reply to the SOAP message is placed in an HTTP reply message that is similar in structure to the request message, but contains no SOAPAction header.
HTTP/1.1 200 OK Content-Type: text/xml; charset='utf-8' Content-Length: 311

The types of response codes used depend on the success or failure of the SOAP request and the type of messaging exchange pattern used, Request/Response or One-Way. 200-OK 202-soap msg accepted, but there is no SOAP response data. Similar to a void method that does not return anything. 400- either the HTTP request or the XML in the SOAP message was not well formed.

405-Http Method Not Allowed. Happens if used other than post. 415- Unsupported Media Type. Happens if Content-Type header is anything other than text/xml. 500- Internal Server Error. This code must be used when the response message in Request/Response MEP is a SOAP fault.

WSDL/UDDI

definitions element
The root element of all WSDL documents is the definitions element, which encapsulates the entire document and also provides a WSDL document with its name.
<definitions name="BookQuoteWS" targetNamespace="http://www.Monson-Haefel.com/jwsbook/BookQuote" xmlns:mh="http://www.Monson-Haefel.com/jwsbook/BookQuote" xmlns:soapbind="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/">

Name attribute is used to give a WSDL name (which is not used in practice) and is optional. The message, portType, and binding elements are assigned labels using their name attributes; these labels automatically take on the namespace specified by the targetNamespace attribute. Labeled message, portType, and binding elements are commonly called definitions.

types element
The types element serves as a container for defining any data types that are not described by the XML schema built-in types: complex types and custom simple types. The data types and elements defined in the types element are used by message definitions when declaring the parts (payloads) of messages. you are not allowed to use the Array type, or the arrayType attribute defined for SOAP 1.1 Encoding (SOAP 1.1 Note, Section 5), or the WSDL arrayType attribute defined by WSDL. In addition you should not label array types as "ArrayOfXXX" as suggested by the WSDL 1.1. The wayaround is, to define a complex type with a maxOccurs value greater than 0 e.g:
<types> <xsd:schema targetNamespace="http://www.Monson-Haefel.com/jwsbook/BookQuote"> <!--A simple array-like type --> <xsd:complexType name="IntArray"> <xsd:sequence> <xsd:element name="arg" type="xsd:int" maxOccurs="unbounded"/> </xsd:sequence> </xsd:complexType> </xsd:schema> </types>

import Element
The import element makes available in the present WSDL document the definitions from a specified namespace in another WSDL document.

WSDL Abstract Interface : message, portType and operation


The portType combines the operation and message definitions into an abstract interface that is analogous to a Java interface definition.

message Element
The message element describes the payload of a message used by a Web service. message element can describe the payloads of outgoing or incoming messages.

message element can describe the contents of SOAP header blocks and fault detail elements.

When RPC-style messaging is used, message elements describe the payloads of the SOAP request and reply messages. They may describe call parameters, call return values, header blocks, or faults.
<!-- message elements describe the input and output parameters --> <message name="GetBookPriceRequest"> <part name="isbn" type="xsd:string" /> </message> <message name="GetBookPriceResponse"> <part name="price" type="xsd:float" /> </message>

Message names are arbitrary and only serve to qualify a message definition. Both input and output messages in Web services can have multiple parts. SAAJ and JAX-RPC have facilities to support output messages with multiple parts. When you use document-style messaging, the message definition refers to a top-level element in the types definition. If you're using RPC-style messaging, the part elements must use the type attribute; if you're using document-style messaging, the part elements must use the element attribute.
<?xml version="1.0" encoding="UTF-8"?> <definitions name="PurchaseOrderWS" targetNamespace="http://www.Monson-Haefel.com/jwsbook/PO" xmlns:mh="http://www.Monson-Haefel.com/jwsbook/PO" xmlns:soapbind="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/"> <types> <xsd:schema targetNamespace="http://www.Monson-Haefel.com/jwsbook/PO"> <!-- Import the PurchaseOrder XML schema document --> <xsd:import namespace="http://www.Monson-Haefel.com/jwsbook/PO" schemaLocation="http://www.Monson-Haefel.com/jwsbook/po.xsd" /> </xsd:schema> </types> <!-- message elements describe the input and output parameters --> <message name="SubmitPurchaseOrderMessage"> <part name="order" element="mh:purchaseOrder" /> </message> ... </definitions>

You can use message definitions to declare faults in the same way you use them to declare input and output messages.
<definitions name="BookQuote" ...> <types> <xsd:schema targetNamespace="http://www.Monson-Haefel.com/jwsbook/PO"> <!-- Import the PurchaseOrder XML schema document --> <xsd:element name="InvalidIsbnFaultDetail" > <xsd:complexType> <xsd:sequence> <xsd:element name="offending-value" type="xsd:string"/> <xsd:element name="conformance-rules" type="xsd:string" /> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema> </types> <!-- message elements describe the input and output parameters --> <message name="GetBookPriceRequest"> <part name="isbn" type="xsd:string" /> </message> <message name="GetBookPriceResponse"> <part name="price" type="xsd:float" /> </message> <message name="InvalidArgumentFault"> <part name="error_message" element="mh:InvalidIsbnFaultDetail" />

</message> </definitions>

Fault messages used by SOAP-based Web services can have only one part. The message definitions used by faults use Document/Literal encoding style and therefore must be based on a top-level element defined in the types element or imported in a WSDL or XML schema document. Message definitions can also be used to describe SOAP header blocks and fault header blocks.

portType Element
A portType defines the abstract interface of a Web service. In WSDL the portType is implemented by the binding and service elements, which dictate the Internet protocols, encoding schemes, and an Internet address used by a Web service implementation. A portType may have one or more operation elements, each of which defines an RPC- or document-style Web service method. Each operation is composed of at most one input or output element and any number of fault elements.
public interface BookQuote { public float getBookPrice (String isbn); <message name="GetBookPriceRequest"> <part name="isbn" type="xsd:string" /> </message> <message name="GetBookPriceResponse"> <part name="price" type="xsd:float" /> </message> / <portType name="BookQuote"> <operation name="GetBookPrice"> <input name="isbn" message="mh:GetBookPriceRequest"/> <output name="price" message="mh:GetBookPriceResponse"/> </operation> </portType>

A WSDL document can have one or more portType elements, each of which describes the abstract interface to a different Web service.

The operation Element


Each operation element declared by a portType uses one or more message definitions to define its input, output, and faults.
<portType name="BookQuote"> <operation name="getBookPrice"> <input name="isbn" message="mh:GetBookPriceRequest"/> <output name="price" message="mh:GetBookPriceResponse"/> <fault name="InvalidArgumentFault" message="mh:InvalidArgumentFault"/> </operation> </portType>

To enforce proper ordering of input or output message parameters, the operation element may declare a parameterOrder attribute.
public float getBulkBookPrice (String isbn, int quantity); <message name="GetBulkBookPriceRequest"> <part name="isbn" type="xsd:string"/>

<part name="quantity" type="xsd:int"/> </message> <message name="GetBulkBookPriceResponse"> <part name="prices" type="mh:prices" /> </message> <portType name="GetBulkBookPrice" > <operation name="getBulkBookPrice" parameterOrder="isbn quantity"> <input name="request" message="mh:GetBulkBookPriceRequest"/> <output name="prices" message="mh:GetBulkBookPriceResponse"/> </operation> </portType>

When a parameterOrder attribute is used, it must include all the input parts and only the output parts that are not the return type. Any part that is omitted from the list provided by the parameterOrder attribute is assumed to be the return type of the operation. A procedure call can have only one return type, so only a single output part may be omitted from the parameterOrder attribute.

Operation Overloading
In WSDL, two operations may have the same name, provided their input or output messages differ. Unfortunately, this feature has caused enough interoperability problems that the Basic Profile prohibits operation overloading.

WSDL Message Exchange Pattern


Most WSDL-based Web services today use either Request/Response or One-Way messaging and are the ones supported by J2EE Web services. If an operation is declared with a single input element followed by a single output element, it defines a Request/Response operation. In addition to its one input and one output, a Request/Response operation may also include fault elements (0 or more), which are returned to the client in the event of an error.
<portType name="BookQuote"> <operation name="getBookPrice"> <input name="isbn" message="mh:GetBookPriceRequest"/> <output name="price" message="mh:GetBookPriceResponse"/> <fault name="InvalidArgumentFault" message="mh:InvalidArgumentFault"/> <fault name="SecurityFault" message="mh:SecurityFault"/> </operation> </portType>

If an operation is declared with a single input but no output, it defines a One-Way operation. Unlike Request/Response operations, One-Way operations may not specify fault elements and do not generate fault messages.
<portType name="SubmitPurchaseOrder_PortType"> <operation name="SubmitPurchaseOrder"> <input name="order" message="mh:SubmitPurchaseOrderMessage"/> </operation> </portType>

WSDL Implementation : binding, service and port


The binding element maps an abstract portType to a set of concrete protocols such as SOAP and HTTP, messaging styles (RPC or document), and encoding styles (Literal or SOAP Encoding). The binding elements identify which portType and operation elements are being bound, while the protocol-specific elements declare the protocol and encoding style to be associated with the portType. Each type of protocol (SOAP, MIME, and HTTP) has its own set of protocol-specific elements and its own namespace.
<portType name="BookQuote"> <operation name="getBookPrice"> <input name="isbn" message="mh:GetBookPriceRequest"/> <output name="price" message="mh:GetBookPriceResponse"/> <fault name="InvalidArgumentFault" message="mh:InvalidArgumentFault"/> <fault name="SecurityFault" message="mh:SecurityFault"/> </operation> </portType>

<?xml version="1.0" encoding="UTF-8"?> <definitions name="BookQuoteWS" targetNamespace="http://www.Monson-Haefel.com/jwsbook/BookQuote" xmlns:mh="http://www.Monson-Haefel.com/jwsbook/BookQuote" xmlns:soapbind="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/"> ... <!-- binding tells us which protocols and encoding styles are used --> <binding name="BookPrice_Binding" type="mh:BookQuote"> <soapbind:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="getBookPrice"> <soapbind:operation style="rpc" soapAction= "http://www.Monson-Haefel.com/jwsbook/BookQuote/GetBookPrice"/> <input> <soapbind:body use="literal" namespace="http://www.Monson-Haefel.com/jwsbook/BookQuote" /> </input> <output> <soapbind:body use="literal" namespace="http://www.Monson-Haefel.com/jwsbook/BookQuote" /> </output> </operation> </binding> ... </definitions>

SOAP Binding
Several SOAP 1.1-specific binding elements are used in combination with the WSDL binding elements. These include soapbind:binding, soapbind:operation, soapbind:body, soapbind:fault, soapbind:header, and soapbind:headerfault. The soapbind:binding and soapbind:body elements are required, but the other elements are optional.
<!-- binding tells us which protocols and encoding styles are used --> <binding name="BookPrice_Binding" type="mh:BookQuote"> <soapbind:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="getBookPrice"> <soapbind:operation style="rpc" soapAction= "http://www.Monson-Haefel.com/jwsbook/BookQuote/GetBookPrice"/> <input> <soapbind:body use="literal" namespace="http://www.Monson-Haefel.com/jwsbook/BookQuote" /> </input> <output> <soapbind:body use="literal" namespace="http://www.Monson-Haefel.com/jwsbook/BookQuote" /> </output> <fault name="InvalidArgumentFault"> <soapbind:fault name="InvalidArgumentFault" use="literal" /> </fault> </operation> </binding>

1. The Basic Profile requires that style attributes declared by soapbind:operation elements have the same value as the style attribute of their soapbind:binding element. 2. You aren't required to declare the WSDL soapAction attribute; it can be omitted. You can also declare the soapAction attribute's value to be empty (indicated by two quotes), which is the same as omitting it. If this attribute is omitted or empty, then the SOAPAction HTTP header field must be present and must contain an empty string. 3. When you use RPC-style messaging, the Body of the SOAP message will contain an element that

represents the operation to be performed. This element gets its name from the operation defined in the portType. The operation element will contain zero or more parameter elements, which are derived from the input message's partseach parameter element maps directly to a message part. 4. When you use document-style messaging, the XML document fragment will be the direct child of the Body element of the SOAP message. The operation is not identified. Attributes of the soapbind:body element change depending on whether you use RPC- or documentstyle messaging. The soapbind:body element has four kinds of attributes: use, namespace, part, and encodingStyle. Attributes of the soapbind:body element change depending on whether you use RPC- or documentstyle messaging. The soapbind:body element has four kinds of attributes: use, namespace, part, and encodingStyle. 1. The use attribute is required to be "literal"and that value is assumed if the soapbind:body element fails to declare the use attribute. 2. The encodingStyle attribute is never used at all, because WS-I-conformant Web services are based on the W3C XML schema, which is implied by the use="literal" declaration. Other encoding styles, like SOAP 1.1 Encoding, are not used. 3. The part attribute specifies which part elements in the message definition are being used. The part attribute is necessary only if you are using a subset of the part elements declared by a message. 4. In "rpc"-style messages, the namespace attribute must be specified with a valid URI.BP The URI can be the same as the targetNamespace of the WSDL document. 5. In contrast, document-style messages must not specify the namespace attribute in the soapbind:body element. The namespace of the XML document fragment is derived from its XML schema.

In addition to the soapbind:body element, a binding operation may also declare fault elements. 1. The WSDL fault and soapbind:fault elements include a mandatory name attribute, which refers to a specific fault message declared in the associated port Type.
2. An operation may have zero or more fault elements, each with its own soapbind:fault element. Each soapbind:fault element may declare a use attribute. If it does, the value must be "literal". If it doesn't, the value is "literal" by default.

WSDL explicitly identifies a SOAP header block by using the soapbind:header element in the binding's input element, its output element, or both.
<types> <xsd:schema targetNamespace= "http://www.Monson-Haefel.com/jwsbook/BookQuote" xmlns="http://www.w3.org/2001/XMLSchema"> <xsd:element name="message-id" type="string" /> </xsd:schema> </types> <!-- message elements describe the input and output parameters --> <message name="Headers"> <part name="message-id" element="mh:message-id" /> </message> <binding name="BookPrice_Binding" type="mh:BookQuote"> <soapbind:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="getBookPrice"> <soapbind:operation style="rpc" soapAction= "http://www.Monson-Haefel.com/jwsbook/BookQuote/GetBookPrice"/>

<input> <soapbind:header message="mh:Headers" part="message-id" use="literal"> <soapbind:headerfault message="mh:HeaderFault" use="literal" /> </soapbind:header> <soapbind:body use="literal" namespace="http://www.Monson-Haefel.com/jwsbook/BookQuote" /> </input> <output> <soapbind:body use="literal" namespace="http://www.Monson-Haefel.com/jwsbook/BookQuote" /> </output> </operation> </binding>

WSDL service and port Elements


The service element contains one or more port elements, each of which represents a different Web service. It's even possible for two or more port elements to assign different URLs to the same binding, which might be useful for load balancing or failover.
<service name="BookPriceService"> <port name="BookPrice_Port" binding="mh:BookPrice_Binding"> <soapbind:address location= "http://www.Monson-Haefel.com/jwsbook/BookQuote" /> </port> <port name="BookPrice_Failover_Port" binding="mh:BookPrice_Binding"> <soapbind:address location= "http://www.monson-haefel.org/jwsbook/BookPrice" /> </port> <port name="SubmitPurchaseOrder_Port" binding="mh:SubmitPurchaseOrder_Binding"> <soapbind:address location= "https://www.monson-haefel.org/jwsbook/po" /> </port> </service>

1. The soapbind:address element is pretty straightforward; it simply assigns an Internet address to a SOAP binding via its location attribute (its only attribute). Although WSDL allows any type of address (HTTP, FTP, SMTP, and so on), the Basic Profile allows only those URLs that use the HTTP or HTTPS schema. 2. Two or more port elements within the same WSDL document must not specify exactly the same URL value for the location attribute of the soapbind:address.

EJB Lifecycle Callback Methods A method in the bean class may be declared as a lifecycle callback method by annotating the method with the following annotations: javax.annotation.PostConstruct:Methods annotated with @PostConstruct are invoked by the container on newly constructed bean instances after all dependency injection has completed and before the first business method is invoked on the enterprise bean. javax.annotation.PreDestroy:Methods annotated with @PreDestroy are invoked after any method annotated @Remove has completed and before the container removes the enterprise bean instance. javax.ejb.PostActivate:Methods annotated with @PostActivate are invoked by the container after the container moves the bean from secondary storage to active status. javax.ejb.PrePassivate:Methods annotated with @PrePassivate are invoked by the container before it passivates the enterprise bean, meaning that the container temporarily

removes the bean from the environment and saves it to secondary storage. The signature of a business method must conform to these rules. The method name must not begin with ejb, to avoid conflicts with callback methods defined by the EJB architecture. For example, you cannot call a business method ejbCreate or ejbActivate. The access control modifier must be public. If the bean allows remote access through a remote business interface, the arguments and return types must be legal types for the Java RemoteMethod Invocation (RMI) API. If the bean is a web service endpoint, the arguments and return types for the methods annotated @WebMethod must be legal types for JAX-WS. The modifier must not be static or final. The @Remove Method Business methods annotated with javax.ejb.Remove in the stateful session bean class can be invoked by enterprise bean clients to remove the bean instance. The container will remove the enterprise bean after a @Remove method completes, either normally or abnormally. In CartBean, the remove method is a @Remove method: @Remove public void remove() { contents = null; } Singleton Session Beans A singleton session bean is instantiated once per application and exists for the lifecycle of the application. Singleton session beans are designed for circumstances in which a single enterprise bean instance is shared across and concurrently accessed by clients. Initializing Singleton Session Beans The EJB container is responsible for determining when to initialize a singleton session bean instance unless the singleton session bean implementation class is annotated with the javax.ejb.Startup annotation. In this case, sometimes called eager initialization, the EJB container must initialize the singleton session bean upon application startup. @Startup @Singleton public class StatusBean { private String status Sometimes multiple singleton session beans are used to initialize data for an application and therefore must be initialized in a specific order. In these cases, use the javax.ejb.DependsOn annotation to declare the startup dependencies of the singleton session bean. The @DependsOn annotations value attribute is one or more strings that specify the name of the target singleton session bean. The following singleton session bean, PrimaryBean, should be started up first: @Singleton public class PrimaryBean { ... } SecondaryBean depends on PrimaryBean: @Singleton @DependsOn("PrimaryBean")

public class SecondaryBean { ... } @Singleton @DependsOn({"PrimaryBean", "SecondaryBean"}) public class TertiaryBean { ... } Managing Concurrent Access in a Singleton Session Bean When creating a singleton session bean, concurrent access to the singletons business methods can be controlled in two ways: container-managed concurrency and bean-managed concurrency. The javax.ejb.ConcurrencyManagement annotation is used to specify container-managed or bean-managed concurrency for the singleton. With @ConcurrencyManagement, a type attribute must be set to either javax.ejb.ConcurrencyManagementType.CONTAINER or javax.ejb.ConcurrencyManagementType.BEAN. If no @ConcurrencyManagement annotation is present on the singleton implementation class, the EJB container default of container-managed concurrency is used. container-managed concurrency The javax.ejb.Lock annotation and a javax.ejb.LockType type are used to specify the access level of the singletons business methods or @Timeout methods. The LockType enumerated types are READ and WRITE. @Lock(LockType.READ) method can be accessed by many clients at the same time If a method is of locking type WRITE, client access to all the singletons methods is blocked until the current client finishes its method call or an access timeout occurs. When an access timeout occurs, the EJB container throws a javax.ejb.ConcurrentAccessTimeoutException. The javax.ejb.AccessTimeout annotation is used to specify the number of milliseconds before an access timeout occurs. If added at the class level of a singleton, @AccessTimeout specifies the access timeout value for all methods in the singleton unless a method explicitly overrides the default with its own @AccessTimeout annotation. The @AccessTimeout annotation can be applied to both @Lock(LockType.READ) and @Lock(LockType.WRITE) methods. @ConcurrencyManagement(ConcurrencyManagementType.CONTAINER) @Singleton @AccessTimeout(value=120000) Or, @AccessTimeout(value=60, timeUnit=SECONDS)// TimeUnit constants: NANOSECONDS, MICROSECONDS, MILLISECONDS, or SECONDS. public class StatusSingletonBean { private String status; @Lock(LockType.WRITE) public void setStatus(String new Status) { status = newStatus; }

@Lock(LockType.WRITE) @AccessTimeout(value=360000) public void doTediousOperation { ... } } If there is no @Lock annotation on the class or business method, default of @Lock(WRITE) is applied to the business method. Bean-Managed Concurrency Singletons that use bean-managed concurrency allow full concurrent access to all the business and timeout methods in the singleton. Developers who create singletons with bean-managed concurrency are allowed to use the Java programming language synchronization primitives, such as synchronization and volatile, to prevent errors during concurrent access. Handling Errors in a Singleton Session Bean If a singleton session bean encounters an error when initialized by the EJB container, that singleton instance will be destroyed. Add a @ConcurrencyManagement annotation with the type set to ConcurrencyManagementType.BEAN at the class level of the singleton to specify bean-managed Concurrency. @ConcurrencyManagement(ConcurrencyManagementType.BEAN) @Singleton public class AnotherSingletonBean { ... } Securing Enterprise Beans Enterprise bean methods can be secured in either of the following ways: Declarative security (preferred): Programmatic security: For an enterprise bean, code embedded in a business method that is used to access a callers identity programmatically and that uses this information to make security decisions. In general, security management should be enforced by the container in a manner that is transparent to the enterprise beans business methods. A security view consists of a set of security roles, a semantic grouping of permissions that a given type of users of an application must have to successfully access the application. Method permissions can be specified on the class, the business methods of the class, or both. Method permissions can be specified on a method of the bean class to override the method permissions value specified on the entire bean class. @DeclareRoles: Specifies all the roles that the application will use, including roles not specifically named in a @RolesAllowed annotation. The set of security roles the application uses is the total of the security roles defined in the @DeclareRoles and @RolesAllowed annotations. The @DeclareRoles annotation is specified on a bean class

@DeclareRoles({"Administrator", "Manager", "Employee"}) @RolesAllowed("list-of-roles"): Specifies the security roles permitted to access methods in an application. This annotation can be specified on a class or on one or more methods. When specified at the class level, the annotation applies to all methods in the class. When specified on a method, the annotation applies to that method only and overrides any values specified at the class level. @DenyAll-- Specifies that no security roles are permitted to execute the specified method or methods. @PermitAll-- Specifies that all security roles are permitted to execute the specified method or methods. This annotation can be specified on a class or on one or more methods. @DeclareRoles({"Administrator", "Manager", "Employee"}) public class Calculator { @RolesAllowed("Administrator") public void setNewRate(int rate) { ... }} Specifying an Authentication Mechanism and Secure Connection When method permissions are specified, basic user name/password authentication will be invoked by the GlassFish Server. To use a different type of authentication or to require a secure connection using SSL, specify this information in an application deployment descriptor.

Securing an Enterprise Bean Programmatically Programmatic security, code that is embedded in a business method, is used to access a callers identity programmatically and uses this information to make security decisions within the method itself. The javax.ejb.EJBContext interface provides two methods that allow the bean provider to access security information about the enterprise beans caller. getCallerPrincipal, which allows the enterprise bean methods to obtain the current caller principals name. @Stateless public class EmployeeServiceBean implements EmployeeService { @Resource SessionContext ctx; @PersistenceContext EntityManager em; public void changePhoneNumber(...) { ... // obtain the caller principal. callerPrincipal = ctx.getCallerPrincipal(); // obtain the caller principals name. callerKey = callerPrincipal.getName();

// use callerKey as primary key to find EmployeeRecord EmployeeRecord myEmployeeRecord = em.find(EmployeeRecord.class, callerKey); // update phone number myEmployeeRecord.setPhoneNumber(...); ... } isCallerInRole, which the enterprise bean code can use to allow the bean provider/application developer to code the security checks that cannot be easily defined using method permissions. @Resource SessionContext ctx; public void updateEmployeeInfo(EmplInfo info) { oldInfo = ... read from database; // The salary field can be changed only by callers // who have the security role "payroll" if (info.salary != oldInfo.salary && !ctx.isCallerInRole("payroll")) { throw new SecurityException(...); } ... To propagate an identity to the target enterprise bean form one bean to another, configure a run-as identity for the bean, The run-as identity applies to the enterprise bean as a whole, including all the methods of the enterprise beans business interface, local and remote interfaces, component interface, and web service endpoint interfaces, the message listener methods of a message-driven bean, the timeout method of an enterprise bean, and all internal methods of the bean that might be called in turn. You can configure an enterprise beans run-as, or propagated, security identity by using the @RunAs annotation. When an enterprise bean is designed so that either the original caller identity or a designated identity is used to call a target bean, the target bean will receive the propagated identity only. The presence of the @RolesAllowed annotation also implicitly declares that authentication will be required for a user to access these methods. If no authentication method is specified in the deployment descriptor, the type of authentication will be user name/password authentication. How to setup security: http://www.jairrillo.com/blog/2009/08/16/jee-security-how-to-setup-authentication-onglassfish-and-netbeans/ http://weblogs.java.net/blog/tchangu/archive/2006/06/glassfish_role.html Create a web service client for a RESTful web service

Use the java.net.* APIs to access a JAX-RS resource 1. Create a URL. 2. Retrieve the URLConnection object. 3. Set output capability on the URLConnection. 4. Open a connection to the resource. 5. from the connection. 6. Write to the output stream. 7. Close the output stream. java.net.Authenticator to access a secure JAX-RS resource Applications use this class by overriding getPasswordAuthentication() in a sub-class. This method will typically use the various getXXX() accessor methods to get information about the entity requesting authentication. An instance of this concrete sub-class is then registered with the system by calling setDefault(Authenticator). When authentication is required, the system will invoke one of the requestPasswordAuthentication() methods which in turn will call the getPasswordAuthentication() method of the registered object.
public static void main(String[] args) throws IOException { // TODO Auto-generated method stub StringBuilder sb=new StringBuilder(); String line=new String(); URL url=new URL("http://localhost:8888/RSWEB/rest/calculator/add?x=5&y=2"); ///java.net.Authenticator to access a secure JAX-RS resource./// String proxy = "localhost:8888"; String port = "8888"; String username = "ravi"; String password = "ravi"; Authenticator.setDefault(new SimpleAuthenticator(username,password));--register subclass Properties systemProperties = System.getProperties(); systemProperties.setProperty("http.proxyHost",proxy); systemProperties.setProperty("http.proxyPort",port); HttpURLConnection conn=(HttpURLConnection)url.openConnection(); conn.setConnectTimeout(30000); conn.setUseCaches(true); conn.setDoOutput(true); ///GET/// conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/xml"); conn.connect(); InputStream is=conn.getInputStream(); InputStreamReader rd=new InputStreamReader(is); BufferedReader br=new BufferedReader(rd); while((line=br.readLine())!=null){ sb.append(line);

} System.out.println(sb.toString()); sb=new StringBuilder(); conn.disconnect(); ////POST//// url=new URL("http://localhost:8888/RS-WEB/rest/customer"); conn=(HttpURLConnection)url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); String input="{\"@id\":\"1111\",\"firstname\":\"hello\"}"; OutputStream os= conn.getOutputStream(); os.write(input.getBytes()); os.close(); conn.connect(); br=new BufferedReader(new InputStreamReader(conn.getInputStream())); while((line=br.readLine())!=null){ sb.append(line); } System.out.println(sb.toString()); conn.disconnect(); } import java.net.Authenticator; import java.net.PasswordAuthentication; public class SimpleAuthenticator extends Authenticator{ private String username, password; public SimpleAuthenticator(String username,String password) { this.username = username; this.password = password; } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username,password.toCharArray()); } }

Use Ajax to access a JAX-RS resource

XMLHttpRequest Object is used to make AJAX calls.

Browser Type detection: if (window.XMLHttpRequest) { // Mozilla, Safari http_request = new XMLHttpRequest(); if (http_request.overrideMimeType) { // set type accordingly to anticipated content type http_request.overrideMimeType('text/xml'); } } else if (window.ActiveXObject) { // IE try { http_request = new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) { try { http_request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } } if(method=='GET') { http_request.open(method, url+parameters, true); http_request.setRequestHeader("Content-type", "text/xml"); http_request.setRequestHeader("Content-length", parameters.length); http_request.setRequestHeader("Connection", "close"); http_request.send(null); } if(method=='POST') { http_request.open(method, url, true); http_request.setRequestHeader("Content-type", "text/xml"); http_request.setRequestHeader("Content-length", parameters.length); http_request.setRequestHeader("Connection", "close"); http_request.send(parameters); } if(method=='PUT') { http_request.open(method, url, true); http_request.setRequestHeader("Content-type", "text/xml"); http_request.setRequestHeader("Content-length", parameters.length); http_request.setRequestHeader("Connection", "close"); http_request.send(parameters); } if(method=='DELETE'){ http_request.open(method, url+parameters, true); http_request.setRequestHeader("Content-type", "text/xml"); http_request.setRequestHeader("Content-length", parameters.length); http_request.setRequestHeader("Connection", "close"); http_request.send(null); } Read Response: if (http_request.readyState == 4) { if (http_request.status == 200 || http_request.status==201) { alert('Response received from server:\n'+http_request.responseText); result = http_request.responseText; // Turn < and > into &lt; and &gt; (case matters) result = result.replace(/\<([^!])/g, '&lt;$1'); result = result.replace(/([^-])\>/g, '$1&gt;'); document.getElementById('serverresponse').innerHTML = result; } else { alert('There was a problem with the request.' +http_request.responseText +' '+http_req document.getElementById('serverresponse').innerHTML = http_request.respons

} } Getting Form data to make AJAX call: function postTheForm() { var postStr = document.myform.xmldata.value ; alert('Sending XML to server:\n' + postStr); makeAJAXRequest('POST', document.myform.endpointURL.value , postStr); } function getTheForm() { var getStr = encodeURI(document.myform.xmldata.value) ; alert('Sending XML to server:\n' + getStr); makeAJAXRequest('GET', document.myform.endpointURL.value , getStr); } function putTheForm() { var putStr = document.myform.xmldata.value ; alert('Sending XML to server:\n' + putStr); makeAJAXRequest('PUT', document.myform.endpointURL.value , putStr); } function deleteTheForm() { var delStr = encodeURI(document.myform.xmldata.value); alert('Sending XML to server:\n' + delStr); makeAJAXRequest('DELETE',document.myform.endpointURL.value , delStr); } Jersey client API to access a JAX-RS resource: The Jersey client API can be utilized to interoperate with any RESTful Web service, implemented using one of many frameworks, and is not restricted to services implemented using JAX-RS. The Jersey Client API supports a pluggable architecture to enable the use of different underlying HTTP client implementations. Two such implementations are supported and leveraged: the Http(s)URLConnection classes supplied with the JDK; and the Apache HTTP client. Apache HTTP client API or java.net.HttpURLConnection supplied with the JDK place too much focus on the Client-Server constraint for the exchanges of request and responses rather than a resource, identified by a URI, and the use of a fixed set of HTTP methods. A resource in the Jersey client API is an instance of the Java class WebResource, and encapsulates a URI. The fixed set of HTTP methods are methods on WebResource or if using the builder pattern are the last methods to be called when invoking an HTTP method on a resource. The Jersey Client API reuses many aspects of the JAX-RS and the Jersey implementation such as: 1. URI building using UriBuilder and UriTemplate to safely build URIs; 2. Support for Java types of representations such as byte[], String, InputStream, File, DataSource and JAXB beans in addition to Jersey specific features such as JSON support and MIME Multipart support. 3. Using the builder pattern to make it easier to construct requests. create an instance of a Client

Client c = Client.create(); automatic redirection for appropriate responses: c.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true); which is same as : c.setFollowRedirects(true); OR, ClientConfig cc = new DefaultClientConfig(); cc.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true); Client c = Client.create(cc);
Obtain a WebResource instance, which will inherit the configuration declared on the client instance.
WebResource r = c.resource("http://localhost:8080/xyz");

The creation of Web resources, the building of requests and receiving of responses are guaranteed to be thread safe. Thus a Client instance and WebResource instances may be shared between multiple threads.

Requests to a Web resource are built using the builder pattern (RequestBuilder) where the terminating method corresponds to an HTTP method (UniformInterface). GET: String response = r.accept( MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE). header("X-FOO", "BAR"). get(String.class); POST: String request = "content"; String response = r.accept( MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE). header("X-FOO", "BAR"). type(MediaType.TEXT_PLAIN_TYPE). post(String.class, request); where the String "content" will be serialized as the request entity. or alternatively the request entity and type may be declared using the entity method as follows: String response = r.accept( MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE). header("X-FOO", "BAR"). entity(request, MediaType.TEXT_PLAIN_TYPE). post(String.class);
If the response has a entity (or representation) then the Java type of the instance required is declared in the terminating HTTP method. In the above examples a response

entity is expected and an instance of String is requested. The response entity will be deserialized to a String instance. If response meta-data is required then the Java type ClientResponse can be declared from which the response status, headers and entity may be obtained.
ClientResponse response = r.get(ClientResponse.class); EntityTag e = response.getEntityTag(); String entity = response.getEntity(String.class);

If the ClientResponse type is not utilized and the response status is greater than or equal to 300 then the runtime exception UniformInterfaceException is thrown. This exception may be caught and the ClientResponse obtained as follows: try { String entity = r.get(String.class); } catch (UniformInterfaceException ue) { ClientResponse response = ue.getResponse(); } A new WebResource can be created from an existing WebResource by building from the latter's URI. WebResource r = c.resource("http://localhost:8080/xyz"); MultivaluedMap<String, String> params = MultivaluedMapImpl(); params.add("foo", "x"); params.add("bar", "y"); String response = r.path("abc"). queryParams(params). get(String.class); This results in a GET request to the URI "http://localhost:8080/xyz/abc?foo=x&bar=y". To process a response entity (or representation) as a stream of bytes use InputStream as follows: InputStream in = r.get(InputStream.class); // Read from the stream ... in.close(); To POST a file use File as follows: File f = ... String response = r.post(String.class, f); Adding support for new representations Classes or implementations of the provider-based interfaces(namely MessageBodyReader and MessageBodyWriter) need to be registered with a ClientConfig and passed to the Client for creation. ClientConfig cc = new DefaultClientConfig(); cc.getClasses().add(MyReader.class);--My Reader implements MessageBodyReader Client c = Client.create(cc); The following registers an instance or singleton of MyReader: ClientConfig cc = new DefaultClientConfig();

MyReader reader = ... cc.getSingletons().add(reader); Client c = Client.create(cc); e.g:


@GET @Path("add") @Produces({"application/xml","application/json"}) @RolesAllowed("Administrator") public Response add(@QueryParam("x") int x, @QueryParam("y") int y){ JAXBClass cla= new JAXBClass(); cla.setSum(x+y); return Response.ok(cla).build(); }

public static void main(String[] args) { ClientConfig cc=new DefaultClientConfig(); MultivaluedMap<String, String> params=new MultivaluedMapImpl(); params.add("x", "5"); params.add("y", "2"); Client c=Client.create(cc); WebResource r=c.resource("http://localhost:8888/RSWEB/rest/calculator"); ClientResponse resp= r.path("/add").queryParams(params).accept(MediaType. APPLICATION_JSON).get(ClientRespo nse.class); System.out.println(resp.getStatus()); System.out.println(resp.getEntity(String.class)); // JAXBClass jaxc= r.path("/add").queryParams(params).accept(MediaType.APPLICATION_XML).get(JAXBClass.cl ass); // System.out.println(jaxc.getSum()); // String responseString=r.path("/add").queryParams(params).accept(MediaType.APPLICATION_XML).g et(String.class); // System.out.println(responseString); }

JAX-WS A typical client invocation of a web service consists of the following steps: 1. The web service client invokes a Java method in the web service proxy interface, supplying parameters. 2. JAX-WS generates the appropriate SOAP message for the invoked method. 3. JAX-WS maps the parameters of the method call to XML using JAXB and inserts them into the SOAP message. 4. JAX-WS sends the SOAP message over HTTP to the web service server. 5. At the server side, JAX-WS interprets the SOAP message, mapping it to appropriate Java method in the web service implementation. 6. JAX-WS maps the parameters XML data to Java parameters. 7. JAX-WS invokes the Java method in the web service implementation. 8. The web service implementation method processes the request and returns some data. 9. JAX-WS generates the appropriate SOAP response message. 10. JAX-WS maps the resulting data of the Java web service implementation method to XML using JAXB and inserts it into the SOAP message. 11. JAX-WS returns the HTTP response to the client. 12. On the client side, JAX-WS maps the XML data to Java return data. 13. The call to the method in the web service proxy interface returns, supplying the return data. JAX-WS supports both message-oriented web services as well as RPC-oriented web services. JAX-WS enables development of both web services and web service clients in the platform independent Java language. JAX-WS 2.0 allows for direct sending of XML over HTTP, thus supporting RESTful web services. JAX-WS uses technologies defined by the World Wide Web Consortium (W3C), such as HTTP, SOAP and WSDL, which are standard technologies applicable regardless of the programming language or platform used for web services and web service clients. JAX-WS supports the WS-I Basic Profile version 1.1, which clarifies SOAP and WSDL specifications and establish a set of best practices that promotes interoperability. JAX-WS supplies a layered programming model consisting of two layers: - The upper layer, which is the only layer most applications will use, uses annotations extensively which makes it easy to use. - The lower layer is more traditional, API-based, and more suitable for special cases. A JAX-WS web service can be implemented either using an EJB endpoint or using a servlet. Both EJB based endpoints and POJO based endpoints will be wrapped by a servlet. Both servlet endpoints and EJB endpoints can have an object implementing the WebServiceContext interface injected using the @Resource annotation. MessageContext getMessageContext() Retrieves the message context of the request being served. The basic message context is of the type Map<String, Object>. Principal getUserPrincipal() Retrieves the user's principal identifying the sender of the request, or null if there is none. boolean isUserInRole(String role) Determines if an authenticated user is in the role having the supplied role name.

servlet-based endpoints additionally can access a servlet context (type: javax.servlet.ServletContext). EJB Endpoints An EJB endpoint is a regular Enterprise Java Bean version 3 and as such provide: Transactions Security - More fine grained security, where permissions can be specified for individual methods. Interceptors Access to timer services Dependency injection Thread management Only one thread at a time is allowed to execute in an EJB endpoint instance. Integrated Stack (I-Stack) which consists of JAX-WS, JAXB, StAX, SAAJ. JAX-WS - Java API for XML Web Services - API for creating web services. JAXB - Java Architecture for XML Binding - Marshaling of Java objects to XML representation and unmarshaling of XML representations to Java objects. StAX - Streaming API for XML - Reading and writing of XML documents. SAAJ- SOAP with Attachments API for Java - Facilitates production and consumption of SOAP messages with attachments. Fast Infoset - A binary encoding of XML that can improve performance

JAX-WS Development Approaches Java first - Also called bottom-up. Interoperability problems may occur with services/clients defined in other languages. WSDL first - Also called top-down or contract first. Better interoperability between different web service technologies (.NET, Java etc). Less sensitive to changes. More control. Meet in the middle - Overly complex. The prerequisites for the Meet in the Middle approach are an existing WSDL document and an existing implementation of the service. This approach may be used when a web service with a fixed interface (the WSDL document) is to be created using existing implementation of business logic. Generate the service endpoint interface (SEI) and additional artifacts from the WSDL file. Create a service implementation class that implements the SEI and delegates the performing of business functionality to the existing implementation. Package the archive (WAR or JAR) containing the web service. Deploy the archive in the appropriate container.

Annotations:

Additional Features AddressingFeature MTOMFeature

RespectBindingFeature AddressingFeature Can be used with the SOAP 1.1/HTTP or SOAP 1.2/HTTP binding only Enabling this feature on the server will result in the <wsaw:UsingAddressing> element being added to the <wsdl:Binding> for the endpoint and in the runtime being capable of responding to WSAddressing headers. Enabling this feature on the client will cause the JAX-WS runtime to include WS-Addressing headers in SOAP messages. MTOMFeature The MTOM feature is used to enable or disable transport optimization of SOAP messages as well as setting the threshold used to determine when binary data should be encoded. RespectBindingFeature This feature clarifies the use of the <wsdl:binding> in a JAX-WS runtime. This feature is only useful with web services that have an associated WSDL. Enabling this feature requires that a JAX-WS implementation inspect the <wsdl:binding> for an endpoint at runtime to make sure that all <wsdl:extensions> that have the required attribute set to true are understood and are being used. Architecture:

JAX-WS Tools SPI


The JAX-WS Tools SPI provides a means to implement custom behaviour of the wsgen and wsimport tools. It consists of two classes; the abstract WSToolsObjectFactory and the concrete class WSToolsObjectFactoryImpl. both located in the com.sun.tools.ws.spi package. The WSToolsObjectFactory defines the properties of a factory used to produce JAX-WS tools related objects and contains the following methods: public static WSToolsObjectFactory newInstance() - Obtain an instance of the factory. abstract public boolean wsgen(OutputStream logStream, Container container, String[] args) - Invokes wsgen on an endpoint implementation, and generates the necessary artifacts like wrapper, exception bean classes etc. public boolean wsgen(OutputStream logStream, String[] args) - Invokes wsgen on an endpoint implementation, and generates the necessary artifacts like wrapper, exception bean classes etc. abstract public boolean wsimport(OutputStream logStream, Container container, String[] args) -Invokes wsimport on a WSDL URL argument, and generates the necessary portable artifacts like Service Endpoint Interface, Service, Bean classes etc. public boolean wsimport(OutputStream logStream, String[] args) - Invokes wsimport on a WSDL URL argument, and generates the necessary portable artifacts like Service Endpoint Interface, Service, Bean classes etc.

The WSToolsObjectFactoryImpl class inherits from the WSToolsObjectFactory class and provides implementations of the abstract methods for the default behaviour of the tools. JAX-WS Provider SPI The Provider SPI allows an application to customize the JAX-WS implementation by defining the properties of the factory that creates endpoints, creates service delegate objects and publishes endpoints. Any customization is totally transparent and requires no changes in the application code.

The Service class delegates work to the ServiceDelegate class. All methods in the javax.xml.ws.Service class, except for two create-methods that create instances of the Service class, are also present in the javax.xml.ws.spi.ServiceDelegate.
Subclasses of the abstract javax.xml.ws.spi.Provider class are responsible for creating the following types of objects specific to the JAX-WS implementation in question: javax.xml.ws.Endpoint javax.xml.ws.ServiceDelegate javax.xml.ws.wsaddressing.W3CEndpointReference The abstract javax.xml.ws.spi.Provider class contains the following methods: Method Signature Description abstract Endpoint createAndPublishEndpoint(String address, Object implementor) Creates and publishes an endpoint with the supplied address and protocol to use, both specified by one URI)that uses the supplied implementation object.

abstract Endpoint createEndpoint(String bindingUri, Object implementor) Creates an endpoint that uses the binding (e.g. SOAP/HTTP) specified by the supplied binding URI and that uses the supplied implementation object. abstract ServiceDelegate createServiceDelegate(URL wsdlLocation, QName serviceName, Class serviceClass) - Creates a service delegate object using the supplied location of the WSDL document describing the service, the supplied qualified name of the service and the supplied class which must be an instance of javax.xml.ws.ServiceDelegate or a subclass thereof. abstract W3CEndpointReference createW3CEndpointReference(String address, .QName serviceName, QName portName, List<org.w3c.dom.Element> metadata, String wsdlDocumentLocation, List<org.w3c.dom.Element> referenceParameters) Creates a W3CEndpointReference with the supplied properties. abstract <T> T getPort(EndpointReference endpointReference, Class<T> serviceEndpointInterface, WebServiceFeature... features) - Creates a proxy that supports the supplied service endpoint interface and which invokes the supplied endpoint reference. The proxy will be configured using the supplied web service features. static Provider provider()- Creates a new Provider object. Documentation of this method provides description on how to plug in a custom provider implementation. protected Provider() - Creates a new instance of the Provider class.

JAX-WS ServiceDelegate SPI The abstract javax.xml.ws.spi.ServiceDelegate class contains the following methods:

There are certain requirements on JAX-WS endpoint class: It must be annotated by either the @WebService or the @WebServiceProvider annotation. It must not be declared final or be abstract. Must have a default public constructor or no constructor. It must not define the finalize method. It may use the @PostConstruct and @PreDestroy annotations on lifecycle callback methods. It may specify a service endpoint interface using the endpointInterface element in the @WebService annotation, but is not required to do this. If none specified, then one will be implicitly defined. Web service methods must be public and must not be final or static. Web service methods must be annotated with the @WebMethod annotation, except in the case when all the elements of the @WebMethod annotation have the default values. Web service methods must have JAXB compatible parameters and return types.
@WebService(name="jaxwsPort", serviceName="jaxwsService", targetNamespace="http://myjaxws/tns", portName="jaxwsPort", wsdlLocation="jaxwsService.wsdl") @SOAPBinding(parameterStyle=ParameterStyle. WRAPPED, use=Use.LITERAL,style=Style.DOCUMENT) public class JAXWS_Test implements CalculatorIface{ @Resource private WebServiceContext wsc;

@PostConstruct @WebMethod(exclude=true) public void init(){ System.out.println("init called!"); } @WebMethod(operationName="add", action="urn:add") @RequestWrapper(className="jaxws.jaxb.RequestPayload", localName="reqpayload", targetNamespace="http://myjaxws/tns") @ResponseWrapper(className="jaxws.jaxb.ResponsePayload", localName="resppayload", targetNamespace="http://myjaxws/tns") public int add(int x, int y) throws NumberFormatException{ return x+y; }

Wsgen command to crete artifacts from a service class. wsgen -classpath build/classes/ -wsdl -r WebContent/WEB-INF/wsdl -s src -d build/classes/ jaxwsService.JAXWS_Test This will generate schema, wsdl, RequestPayload and responsePayload

A web service can also be written to process entire protocol messages, usually SOAP, or message payloads. Such a web service class will implement the javax.xml.ws.Provider<T> interface and be annotated with the @WebServiceProvider annotation. Create xsd for payloads Create wsdl Generate jaxb classes using dali tool form xml Write class with @WebservicePriovider annotation Implement provider<T> Write logic in invoke method. The JAX-WS specification mandates support for the following providers: Provider<Source> - In message payload mode. The Source interface is implemented by the classes:DOMSource, JAXBSource, SAXSource, StAXSource, StreamSource Provider<SOAPMessage> -In message mode. Provider<javax.activation.DataSource> Note that, when creating the JAXBContext instance, it is possible to supply a colon-separated list of package names to be included in the context. Thus, it is possible to marshal or unmarshal data related to many different XML schemas. The following additional constrains are placed by the JAX-WS 2.1 specification on a provider class: Provider classes must implement a default constructor or no constructor. A provider class must be bound to a specific type. That is, it may implement Provider<Source>, Provider<SOAPMessage but implementing Provider<T> is not allowed. A provider class must be annotated with the @WebServiceProvider annotation.

MessageProvider.wsdl

MessageProvider.xsd

Result.java

package-info.java

ObjectFactory.java

Params.java

MessageProvider.java

JAX-WS Client Communications Models A JAX-WS client can use the following invocation models: Synchronous request-response Asynchronous request-response One-way In order to be able to choose the mode in which to invoke a web service, an object implementing the javax.xml.ws.Dispatch<T> interface must be obtained from an instance of the javax.xml.ws.Service The Dispatch interface contains the following methods: T invoke(T message) Invoke a service operation synchronously sending the supplied message, or message payload. Returns the response message, or message payload. Response<T> invokeAsync(T message) Invokes a service operation asynchronously sending the supplied message, or message payload. Returns an object that can be polled for the result of the invocaion. Future<?> invokeAsync(T message, AsyncHandler<T> handler) Invokes a service operation asynchronously sending the supplied message, or message payload. The supplied handler will be called when a response to the operation is available. Returns an object that can be used to check the status of the operation invocation. void invokeOneWay(T message) Invokes a service operation using the one-way interaction mode. The invocation is logically non-blocking, but will, when HTTP is used as the underlying protocol, block until a HTTP response is received. When requesting a Dispatch object, the client can also choose whether to work with entire messages, SOAP messages when SOAP is used, or message payloads only, which when SOAP is used is the contents of the SOAP body. Note that when using a Dispatch object to invoke a service operation, we must create either the entire (SOAP) message or, as in the above example, the message payload. Both the message and the message payload are usually in XML format. Sync and async eg.
public static void main(String[] args) throws MalformedURLException, JAXBException, InterruptedException, ExecutionException { // TODO Auto-generated method stub ///create service QName serviceQName=new QName("http://MessageProvider", "MessageProviderService"); Service service=Service.create(new URL("http://localhost:9090/JAX-WSWEB/MessageProviderService?wsdl"), serviceQName); ///create dispatch

QName portName=new QName("http://MessageProvider", "MessageProviderPort"); JAXBContext jc=JAXBContext.newInstance("jaxws.jaxb.messageprovider"); Dispatch<Object> dispatch=service.createDispatch(portName, jc, Service.Mode.PAYLOAD); ///create request payload ObjectFactory of = new ObjectFactory(); Params in=new Params(); in.setParam1(6); in.setParam2(1); JAXBElement<Params> params= of.createInParam(in); ///call service Result result = (Result)dispatch.invoke(params); System.out.println("Synchronous call ;" + result.getOut()); ////Async Invoke Response<Object> response=dispatch.invokeAsync(params); while(!response.isDone()){ System.out.println("async call is still running"); } result=(Result)response.get(); System.out.println("Async Result :" + result.getOut()); ////async call with async handler AsyncHandler<Object> handler = new AsyncHandler<Object>() { @Override public void handleResponse(Response<Object> res) { try { System.out.println("handler async call result : "+((Result)res.get()).getOut()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; java.util.concurrent.Future<?> fh=dispatch.invokeAsync(params, handler); while(!fh.isDone()){ System.out.println("Handler Async call stil running!"); } }

Command to generate static client from given wsdl by using wsimport tool: wsimport -d build/classes -s src -p jaxws.jaxb.messageprovider.staticClient -b WebContent/WEBINF/wsdl/MessageProvider.wsdl http://localhost:9090/JAX-WSWEB/MessageProviderService?wsdl crete an instance of service class, get the port and call the method.

e.g:
MessageProviderService mps = new MessageProviderService(); MessageProviderPort port=mps.getMessageProviderPort(); jaxws.jaxb.messageprovider.staticClient.Params param= new jaxws.jaxb.messageprovider.staticClient.Params(); param.setParam1(10); param.setParam2(3); Result r= port.subtract(param); System.out.println("proxy call result : "+r.getOut());

Asynchronous Invocation with Proxies JAX-WS 2.1 does not specify any annotations by which a method in a web service can be marked as being asynchronous, instead the enableAsyncMapping binding declaration must be used. Such a declaration is usually placed in a separate file that refers to the WSDL: you need to crete a separate binding file. CustomBindingForasyncProxyClientService.xml <bindings xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" wsdlLocation="http://localhost:9090/JAX-WS-WEB/MessageProviderService?wsdl" xmlns="http://java.sun.com/xml/ns/jaxws"> <bindings node="//wsdl:portType[@name='MessageProviderPort']"> <bindings node="wsdl:operation[@name='subtract']"> <enableAsyncMapping>true</enableAsyncMapping> </bindings> </bindings> </bindings> Command to crete client with new binding. wsimport -d build/classes -s src -p jaxws.jaxb.messageprovider.AsyncstaticClient -b WebContent/WEB-INF/wsdl/CustomBindingForasyncProxyClientService.xml http://localhost:9090/JAX-WS-WEB/MessageProviderService?wsdl The newly crete port class will have normal subtract, Response<> asyncSubtract and Future<?> asyncSubtract methods. One-Way Service You need to annotate service method with @OneWay, no response wrapper, only requestwrapper annotation on method. e.g:
@WebService(name="onewayPort", portName="onewayPort", serviceName="onewaySrvice", targetNamespace="http://onewayNamespace", wsdlLocation="onewaySrvice.wsdl") @SOAPBinding(parameterStyle=ParameterStyle. WRAPPED, style=Style.DOCUMENT, use=Use.LITERAL) public class OneWayService { @WebMethod(action="urn:greet", operationName="greet") @Oneway @RequestWrapper(className="jaxws.jaxb.oneway.greetPayload", localName="greetMsg", targetNamespace="http://onewayNamespace", partName="greetMsgPart") public void greet(String greetMsg){ System.out.println("Hello "+greetMsg+ "!");

} } Client call: QName serviceName=new QName("http://onewayNamespace","onewaySrvice"); QName portName=new QName("http://onewayNamespace", "onewayPort"); Service service=Service.create(new URL("http://localhost:8888/JAX-WSWEB/onewaySrvice?wsdl"), serviceName); JAXBContext jc=JAXBContext.newInstance("jaxws.jaxb.oneway"); Dispatch dispatch=service.createDispatch(portName, jc, Mode. PAYLOAD); jaxws.jaxb.oneway.ObjectFactory of=new ObjectFactory(); GreetMsg req=of.createGreetMsg(); req.setArg0("Ravi Kumar"); JAXBElement<GreetMsg> reqPayload=of.createGreetMsg(req); dispatch.invokeOneWay(reqPayload); }

Handlers in JAX-WS
Handlers are message interceptors that can be easily plugged in to the JAX-WS runtime to do additional processing of the inbound and outbound messages. JAX-WS defines two types of handlers, logical handlers and protocol handlers. Protocol handlers are specific to a protocol and may access or change the protocol specific aspects of a message. Logical handlers are protocolagnostic and cannot change any protocol-specific parts (like headers) of a message. Logical handlers act only on the payload of the message. With outgoing messages, handlers are invoked before a message is sent to the wire. With incoming messages, handlers are invoked before the receiving application receives the message. The same handler implementation is used for both incoming and outgoing messages. JAX-WS provides two levels of handlers: Logical handlers deal with the payload level of the message. Logical handlers can be used for building non-functional behavior, such as logging and caching, that is common across protocols. Protocol handlers deal with protocol information, such as SOAP headers. SOAP handlers should extend javax.xml.ws.handler.soap.SOAPHandler Logical handlers extend javax.xml.ws.handler.LogicalHandler and provide access to message context and message payload. If you are using SOAP over HTTP, the content of the SOAP body forms the payload. If you are using XML over HTTP, the XML content of the primary part of the message becomes the payload. Logical handlers are invoked with LogicalMessageContext. LogicalMessageContext.getMessage() returns a LogicalMessage. LogicalHandler Methods: close(MessageContext ctx) boolean handleFault(LogicalMessageContext ctx) boolean handleMessage(LogicalMessageContext ctx) Returning true from the handleMessage method tells the JAX-WS run time that processing should move to the next handler in the chain. Boolean outbound = ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); This property give you the direction of the message Message: LogicalMessage message = ctx.getMessage(); Get the payload as XML javax.xml.transform.Source payload = message.getPayload(); Get the payload as JAXB objects Object jaxbPayload = message.getPayload(jaxbContext); In the case of SOAP, the payload is the contents of the SOAP:Body, either in XML form (javax.xml.transform.Source) or in JAXB form (java.lang.Object).
Protocol handlers

manipulate SOAP headers implement SOAPHandler<SOAPMessageContext> SOAP handler skeleton has the familiar methods of close, handleFault, handleMessage getHeaders method is a new method on SOAPMessageContext compared to logical handler. The JAX-WS run time calls this method to determine whether the handler can process SOAP headers that must be understood (as indicated by the SOAP mustUnderstand attribute).

String javax.xml.soap.SOAPConstants.URI_SOAP_ACTOR_NEXT = "http://schemas.xmlsoap.org/soap/actor/next" The URI identifying the next application processing a SOAP request as the intended actor for a SOAP 1.1 header entry (see section 4.2.2 of the SOAP 1.1 specification). This value can be passed to SOAPHeader.examineMustUnderstandHeaderElements(String), SOAPHeader.examineHeaderElements(String) and SOAPHeader.extractHeaderElements(String) Iterator javax.xml.soap.SOAPHeader.extractHeaderElements(String actor) Returns an Iterator over all the SOAPHeaderElement objects in this SOAPHeader object that have the specified actor and detaches them from this SOAPHeader object. This method allows an actor to process the parts of the SOAPHeader object that apply to it and to remove them before passing the message on to the next actor. Configure SOAP and logical handlers on the Server side. Annotate server and client calss with @Handler annotation or Configure Handler chain in webservices.xml <port-component> . <handler-chains> <handler-chain> <handler> <handler-name>myhandler</handler-name> <handler-class>ImprovedHelloHandler</handler-class> </handler> </handler-chain> </port-component> Configure SOAP and logical handlers on the client side. Use deployment descriptors(webservices.xml)

Or, Use programmatic API. Service.setHandlerResolver(HandlerResolver handlerResolver); e.g: HelloMessengerService service = new HelloMessengerService(); service.setHandlerResolver(new HandlerResolver() { public List getHandlerChain(PortInfo inf) { return Collections.singletonList(new HelloMessengerProtocolHandler()); } });

WS-Addressing with a SOAP web service


The WS-Addressing specification introduces two primary concepts: Endpoint references Endpoint references provide a standard mechanism to encapsulate information about specific endpoints. Endpoint references can be propagated to other parties and then used to target the Web service endpoint that they represent. Message addressing properties Message addressing properties (MAPs) are a set of well-defined WS-Addressing properties that can be represented as elements in SOAP headers and provide a standard way of conveying information, such as the endpoint to which to a direct message replies, or information about the relationship that the message has with other messages. For JAX-WS applications, you can enable WS-Addressing support in several ways, such as configuring policy sets or using annotations in code. Enable WS-Addressing from either the server or the client. For web service clients, WS-Addressing support is disabled by default. For web service providers, WS-Addressing support is enabled by default. Therefore, you do not have to enable this support. However, you can use the enabling mechanisms to modify other WS-Addressing behavior for the service, such as whether WS-Addressing information is required and what is included in the generated WSDL document The following additional features are related to the JAX-WS enhancements: Java representations of WS-Addressing endpoint references are available. You can create Java endpoint reference instances for the application endpoint, or other endpoints in the same application, at run time. You do not have to specify the URI of the endpoint reference. You can create Java endpoint reference instances for endpoints in other applications by specifying the URI of the endpoint reference. On services, you can use annotations to specify whether WS-Addressing support is enabled and whether it is required. On clients, you can use features to specify whether WS-Addressing support is enabled and whether it is required. You can configure client proxy or dispatch objects by using endpoint references. Java support for endpoint references that represent web services Resource (WS-Resource) instances is available. You can associate reference parameters with an endpoint reference at the time of its creation to correlate it with a particular resource instance. In targeted web services, you can extract the reference parameters of an incoming message so that the web service can route the message to the appropriate WS-Resource instance. @Addressing annotation This annotation represents the use of WS-Addressing with either the SOAP 1.1/HTTP or SOAP 1.2/HTTP binding. Using this annotation with any other binding is undefined.

Can be used in conjunction with the WebService, WebServiceProvider, and WebServiceRef annotations. When used with a javax.jws.WebService annotation, this annotation MUST only be used on the service endpoint implementation class. When used with a WebServiceRef annotation, this annotation MUST only be used when a proxy instance is created. The required property can be used to specify if WS-Addressing headers MUST be present on incoming messages. By default the required property is false.

@WebMethod(operationName = "add") @Action( input="http://addnumbers.org/input", output="http://addnumbers.org/output") public int add(@WebParam(name = "i") int i, @WebParam(name = "j") int j) { return i + j; } Chnages in generated wsdl due to above annotation: <portType name="CalculatorWS"> <operation name="add"> <input wsaw:Action="http://addnumbers.org/input" message="tns:add"/> <output wsaw:Action="http://addnumbers.org/output" message="tns:addResponse"/> </operation> </portType> ... <binding name="CalculatorWSPortBinding" type="tns:CalculatorWS"> <wsaw:UsingAddressing/> ... </binding> In the binding, the WSDL now indicates that it is set up for WS-Addressing so that clients are free to use Addressing if they would like to, via the <wsaw:UsingAddressing/> element. This element also has a required attribute that indicates if you want the service to force clients to use addressing. By default, it is set to false. But you could just write <wsaw:UsingAddressing required="true"/> to force clients to use. Can use @Addressing(required=true) to generate above from java class. To make sure that your endpoint and its client are portable, the endpoint must use the @Action annotation to indicate their WS-Addressing actions, and it should use the @FaultAction annotation for creating WS-Addressing-compliant SOAP faults.

Use wsam:Addressing policy in WSDL


Possible Policy assertion for @Addressing
@WebService() @Addressing public class CalculatorWS <wsam:Addressing wsp:Optional="true"> <wsp:Policy/>

</wsam:Addressing> @Addressing(required=true) <wsam:Addressing> <wsp:Policy/> </wsam:Addressing>

@Addressing(responses=Responses.NON_ANONYMOUS)
<wsam:Addressing wsp:Optional="true"> <wsp:Policy> <wsam:NonAnonymousResponses/> </wsp:Policy> </wsam:Addressing>

Use Addressing in the deployment descriptors


You can optionally use the webservices.xml deployment descriptor to augment or override application metadata specified in annotations.

Use AddressingFeature with javax.xml.ws.Endpoint API.


JAX-WS 2.1 introduces three standard features for creating proxy instances, AddressingFeature, MTOMFeature and RespectBindingFeature as well as the base WebServiceFeature class.

Enabling this feature on the server will result in the runtime being capable of consuming and responding to WS-Addressing headers. Enabling this feature on the client will cause the JAX-WS runtime to include WS-Addressing headers in SOAP messages as specified by WS-Addressing. The AddressingFeature's required property can be configured to control whether all incoming messages MUST contain Addressing headers. The AddressingFeature's responses property can be configured to control whether the endpoint requires the use of anonymous, non-anonymous and all responses. This feature is automatically enabled if the WSDL indicates the use of addressing. Can be set to flase manually.

The following describes the effects of Addressing feature with respect to be enabled or disabled: ENABLED In this Mode, WS-Addressing will be enabled. At runtime, WS-Addressing headers MUST be consumed by the receiver and produced by the sender even if the WSDL declares otherwise. The mustUnderstand="0" attribute MUST be used on the WS-Addressing headers. DISABLED In this Mode, WS-Addressing will be disabled even if an associated WSDL specifies otherwise. At runtime, WS-Addressing headers MUST NOT be used. Constructor : AddressingFeature() AddressingFeature(boolean enabled)

AddressingFeature(boolean enabled, boolean required)

Endpoints can be created using the following static methods on Endpoint: create(Object implementor) If the implementor specifies a binding using the javax.xml.ws.BindingType annotation it MUST be used else a default binding of SOAP 1.1 / HTTP binding MUST be used. create(Object implementor, WebServiceFeature ... features) features override the corresponding features that are specified in WSDL, if present. create(String bindingID, Object implementor) create(String bindingID, Object implementor, WebServiceFeature ... features) publish(String address, Object implementor) Creates and publishes an Endpoint for the given implementor. The binding is chosen by default based on the URL scheme of the provided address (which must be a URL). If a suitable binding if found, the endpoint is created then published as if the Endpoint.publish(String address) method had been called. The created Endpoint is then returned as the value of the method. publish(String address, Object implementor, WebServiceFeature ... features) An implementor object MUST be either an instance of a class annotated with the @WebService annotation or an instance of a class annotated with the @WebServiceProvider annotation @Action and @FaultAction on the service methods @Action applied to the methods of a SEI. used to specify the input, output, fault WS-Addressing Action values associated with the annotated method @FaultAction used within the @Action annotation to specify the WS-Addressing Action of a service specific exception. e.g; @Action( input = "http://example.com/input3", output = "http://example.com/output3", fault = { @FaultAction(className = AddNumbersException.class, value = "http://example.com/fault3") }) public int addNumbers3(int number1, int number2) throws AddNumbersException { wsdl: <operation name="addNumbers3"> <input wsaw:Action="http://example.com/input3" message="tns:addNumbers3"/> <output wsaw:Action="http://example.com/output3" message="tns:addNumbers3Response"/> <fault message="tns:AddNumbersException" name="AddNumbersException" wsaw:Action="http://example.com/ </operation> WebServiceContext.getEndpointReference() getEndpointReference(List<Element> referenceParameters) If the binding is SOAP 1.1/HTTP or SOAP 1.2/HTTP, then a javax.xml.ws.wsaddressing.W3CEndpointReference MUST be returned.

getEndpointReference(Class<T> clazz, List<Element> referenceParameters) Creates and returns and javax.xml.ws.EndpointReference of type clazz for a published Endpoint instance. W3CEndpointReference class is a concrete implementation of the javax.xml.ws.EndpointReference class Use Addressing on the client. Create an instance of javax.xml.ws.AddressingFeature, using true as a constructor parameter. Then pass this feature instance to the port accessor method on the service stub. new MyImplService().getMyImplPort( new javax.xml.ws.AddressingFeature(true) ); The JAX-WS 2.1 specification indicates that clients must explicitly enable addressing in order to use addressing in a web service that declares support for it. For each invocation, the client must also explicitly set BindingProvider.SOAPACTION_URI_PROPERTY. BindingProvider.getEndpointReference() The BindingProvider interface represents a component that provides a protocol binding for use by clients, it is implemented by proxies and is extended by the Dispatch interface. Also has Map<String,Object> (RequestContext), Map<String,Object> (ResponseContext) getPort(EndpointReference) methods Proxy instances are not guaranteed to be thread safe. An instance of a proxy MUST implement javax.xml.ws.BindingProvider. A proxy is created using the getPort methods of a Service instance T getPort(Class<T> sei) T getPort(QName port, Class<T> sei) T getPort(Class<T> sei, WebServiceFeature... features) T getPort(QName port, Class<T> sei, WebServiceFeature... features) T getPort(EndpointReference epr, Class<T> sei, WebServiceFeature... features) The epr MUST NOT be used as the value of any addressing header such as wsa:ReplyTo. if the proxy is created using javax.xml.ws.soap.AddressingFeature web service feature, the feature's addressing requirements MUST take precedence over WSDL's addressing requirements. @WebServiceRef static AddNumbersService ser vice; private WebServiceFeature[] enabledRequiredwsf = { new AddressingFeature(true, true) }; AddNumbers port; private AddNumbers getPort() { port = service.getPort(AddNumbers.class, enabledRequiredwsf); return port; }

MTOM and MIME in a SOAP web service


JAX-WS supports the use of SOAP Message Transmission Optimized Mechanism (MTOM) for sending binary attachment data. By enabling MTOM, you can send and receive binary data optimally without incurring the cost of data encoding needed to embed the binary data in an XML document. JAX-WS applications can send binary data as base64 or hexBinary encoded data contained within the XML document. MTOM optimization is not enabled by default. JAX-WS applications require separate configuration of both the client and the server artifacts to enable MTOM support. you can enable MTOM on a JavaBean endpoint only and not on endpoints that implement the javax.xml.ws.Provider interface. The XML schema or WSDL file includes a xsd:base64Binary or xsd:hexBinary element definition for the binary data. You can also include the xmime:expectedContentTypes attribute on the element to affect the mapping by JAXB. To enable MTOM on an endpoint, use the @MTOM (javax.xml.ws.soap.MTOM) annotation on the endpoint. Parameters: enabled - indicates if MTOM is enabled for the JAX-WS endpoint threshold - specifies the minimum size for messages that are sent using MTOM. When the message size is less than this specified integer, the message is inlined in the XML document as base64 or hexBinary data. Additionally, you can use the @BindingType (javax.xml.ws.BindingType) annotation on a server endpoint implementation class to specify that the endpoint supports one of the MTOM binding types so that the response messages are MTOM-enabled. SOAP11HTTP_MTOM_BINDING and SOAP12HTTP_MTOM_BINDING can be used for the value of the @BindingType annotation. // for SOAP version 1.1 @BindingType(value = SOAPBinding.SOAP11HTTP_MTOM_BINDING) // for SOAP version 1.2 @BindingType(value = SOAPBinding.SOAP12HTTP_MTOM_BINDING) MTOM Policy in wsdl <wsdl:definitions targetNamespace="example.com" xmlns:tns="example.com" xmlns:wsdl=http://schemas.xmlsoap.org/wsdl/ xmlns:wsp=http://schemas.xmlsoap.org/ws/2004/09/policy xmlns:wsoma=http://schemas.xmlsoap.org/ws/2004/09/policy/optimizedmimeserialization xmlns:wsu="http://docs.oasis open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0 <wsp:Policy wsu:Id="MyPolicy" > wsoma:OptimizedMimeSerialization />

<!-- omitted assertions --> </wsp:Policy> <!-- omitted elements --> <wsdl:binding name="MyBinding" type="tns:MyPortType" > <wsp:PolicyReference URI="#MyPolicy" wsdl:required="true" /> <!-- omitted elements --> </wsdl:binding> </wsdl:definitions> MTOM uses a wire format of a SOAP message by selectively encoding portions of the message, whilst still presenting an XML Infoset to the SOAP application. Use MTOM in the deployment descriptors You can enable MTOM on server by using the enable-mtom attribute in the sun-jaxws.xml configuration file. This allows the MTOM setting to be changed at deployment time: <endpoints xmlns='http://java.sun.com/xml/ns/jax-ws/ri/runtime' version='2.0'> <endpoint name="Mtom" implementation="mtom.server.HelloImpl" url-pattern="/hello" enable-mtom Use MTOM on the client The class javax.xml.ws.soap.MTOMFeature extends WebServiceFeature. Port=service.getPort(new MTOMFeature()); Sending any additional attachments using MessageContext properties. Mime attachments specified by the javax.xml.ws.binding.attachments.inbound and javax.xml.ws.binding.attachments.outbound properties defined in the MessageContext (MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS, MessageContext.INBOUND_MESSAGE_ATTACHMENTS). javax.xml.ws.binding.attachments.inbound Type - Map<String,DataHandler> A map of attachments to an inbound message. The key is a unique identifier for the attachment. The value is a DataHandler for the attachment data. javax.xml.ws.binding.attachments.outbound Type - Map<String,DataHandler> A map of attachments to an outbound message. Use of javax.xml.ws.binding.attachments.outbound property in Dispatch: When using Dispatch in SOAP / HTTP binding in payload mode, attachments specified using the javax.xml.ws.binding.attachments.outbound property will be included as mime attachments in the message. When using Dispatch in SOAP / HTTP binding in message mode, the javax.xml.ws.binding.attachments.outbound property will be ignored as the message type already provides a way to specify attachments. For example: // Create Dispatch for the payload

Dispatch<String> dispatch = svc.createDispatch(portName, String.class, Service.Mode.PAYLOAD); // Get the request context Map<String, Object> requestContext = dispatch.getRequestContext(); // Get the attachments (non-payload) that should also be sent. Map<String, DataHandler> attachmentMap = new HashMap(); attachmentMap.put("myCID", myDataHandler); // Attach the attachments to the request context requestContext.put("javax.xml.ws.binding.attachments.outbound", attachmentMap); The following method of trying to disable MTOM on the client side does not work and should not be used: SOAPBinding theSOAPBinding = (SOAPBinding)((BindingProvider)thePort).getBinding(); theSOAPBinding.setMTOMEnabled(false);

WS-Policy Expressing policies that refer to domain-specific capabilities, requirements, and general characteristics of entities in a Web services-based system. Several different kinds of policy assertions exist, some examples are: Web Services Security Policy. Web Services Reliable Messaging Policy. Web Services Atomic Transaction Policy. Web Services Business Activity Framework. Devices Profile for Web Services. The basic constructs in the WS-Policy language are: Policy - A collection of policy alternatives. Policy Alternative- A collection of policy assertions. Policy Assertion Policy Expression - The XML info set representation of a policy.

GreenPolicy OrangePolicy alternative BluePolicy Assertion

Policy Assertions Policy assertions describe either required behavior or capabilities of entities such as web service endpoints, web service messages, resources, operations etc. Policy Alternatives A policy alternative is a collection of zero or more policy assertions. The collection is unordered and may contain duplicates. Policy A policy is a collection of zero or more policy alternatives. The collection is unordered. Policy Expression A policy expression is an XML representation of a policy. It contains the following four elements and two attributes: <wsp:Policy> Root element of a policy specification. Can also be used as a policy assertion combining operation, in which case it is equivalent to the <wsp:All> element. <wsp:All> Combining multiple policy assertions so that all assertions are required. <wsp:ExactlyOne> Combining multiple policy assertions so that exactly one is required. <wsp:PolicyReference> Enables re-use of policy declarations by including them in new policy declarations. wsp:Optional Specifies whether the policy assertion is optional or not. Default is false. wsp:Ignorable Specifies whether the policy assertion can be ignored or not. Default is false. The schema outline of the normal form of a policy expression: <wsp:Policy > <wsp:ExactlyOne> ( <wsp:All> ( <Assertion > </Assertion> )* </wsp:All> )* </wsp:ExactlyOne> </wsp:Policy> The schema outline of the compact form of a policy expression: <Assertion ( wsp:Optional="xs:boolean" )? > </Assertion> When Boolean is true: <wsp:ExactlyOne> <wsp:All> <Assertion > </Assertion> </wsp:All> <wsp:All /> </wsp:ExactlyOne> When Boolean is false: <wsp:ExactlyOne> <wsp:All> <Assertion > </Assertion> </wsp:All> </wsp:ExactlyOne> Policy expressions can be attached to <binding> elements in WSDL documents, either by inserting the policy declaration or by referencing it. e.g: <wsdl:binding name="MyBinding" type="tns:MyInterface" > <wsp:Policy> <wsam:Addressing></wsam:Addressing>

</wsp:Policy> </wsdl:binding> <wsdl:binding name="InquiryBinding" type="tns:InquiryInterface" > <wsp:PolicyReference URI="#common" /> <wsdl:operation name="MakeInquiry"></wsdl:operation> </wsdl:binding> Compact form: <wsp:Policy xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702" xmlns:wsp="http://www.w3.org/ns/ws-policy" > <sp:IncludeTimestamp wsp:Optional="true" /> </wsp:Policy> Is equivalent to the following normal form as : <wsp:Policy xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702" xmlns:wsp="http://www.w3.org/ns/ws-policy" > <wsp:ExactlyOne> <wsp:All> <sp:IncludeTimestamp /> </wsp:All> <wsp:All /> </wsp:ExactlyOne> </wsp:Policy>
<All> <mtom:OptimizedMimeSerialization wsp:Optional="true"/> <wsam:Addressing></wsam:Addressing> <log:Logging wsp:Ignorable="true" /> <ExactlyOne> <sp:TransportBinding></sp:TransportBinding> <sp:AsymmetricBinding></sp:AsymmetricBinding> </ExactlyOne> </All>

SAAJ APIs Ref: http://java.boot.by/wsd-guide/ch05s04.html Belong to the javax.xml.soap package namespace Core SAAJ API exposes classes that closely mimic the actual SOAP messages structure.

Many of the classes in SAAJ extend or implement behavior from classes in the org.w3c.dom package namespace. An example of this is the SOAPPart object that implements the org.w3c.dom.Document interface. Accessing Elements of a Message: First way SOAPPart soapPart = message.getSOAPPart(); SOAPEnvelope envelope = soapPart.getEnvelope(); SOAPHeader header = envelope.getHeader(); SOAPBody body = envelope.getBody(); Second way SOAPHeader header = message.getSOAPHeader(); SOAPBody body = message.getSOAPBody(); Adding Content to the Body Create one or more SOAPBodyElement objects to hold the content. You can also add subelements to the SOAPBodyElement objects by using the addChildElement method. For each element or child element, you add content by using the addTextNode method.

When you create any new element, you also need to create an associated javax.xml.namespace.QName object so that it is uniquely identified. SOAPBody body = message.getSOAPBody(); QName bodyName = new QName("http://wombat.ztrade.com", "GetLastTradePrice", "m"); SOAPBodyElement bodyElement = body.addBodyElement(bodyName); The QName object for the new SOAPElement object symbol is initialized with only a local name because child elements inherit the prefix and URI from the parent element: QName name = new QName("symbol"); SOAPElement symbol = bodyElement.addChildElement(name); symbol.addTextNode("SUNW"); Formed XML: <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Body> <m:GetLastTradePrice xmlns:m="http://wombat.ztrade.com"> <symbol>SUNW</symbol> </m:GetLastTradePrice> </SOAP-ENV:Body> </SOAP-ENV:Envelope> Getting the Content of a Message To get the content, which was added with the method SOAPElement.addTextNode, you call the method Node.getValue. getValue returns the value of the immediate child of the element that calls the method. To access bodyElement, you call the getChildElements method on soapBody. Passing bodyName to getChildElements returns a java.util.Iterator object that contains all the child elements identified by the Name object bodyName. SOAPBody soapBody = response.getSOAPBody(); QName bodyName = new QName("http://wombat.ztrade.com", "GetLastTradePrice", "m"); java.util.Iterator iterator = soapBody.getChildElements(bodyName); SOAPBodyElement bodyElement = (SOAPBodyElement)iterator.next(); String lastPrice = bodyElement.getValue(); Adding Content to the Header SOAPHeader header = message.getSOAPHeader(); QName headerName = new QName("http://ws-i.org/schemas/conformanceClaim/", "Claim", "wsi"); SOAPHeaderElement headerElement = header.addHeaderElement(headerName); headerElement.addAttribute(new QName("conformsTo"), "http://wsi.org/profiles/basic/1.1/"); <SOAP-ENV:Header> <wsi:Claim

xmlns:wsi="http://ws-i.org/schemas/conformanceClaim/" conformsTo="http://ws-i.org/profiles/basic/1.1/"/> </SOAP-ENV:Header> Add content to headerElement headerElement.addTextNode("order"); Set Actor and mustUnderstand to header: SOAPHeaderElement orderHeader = header.addHeaderElement(order); orderHeader.setActor("http://gizmos.com/orders"); orderHeader.setMustUnderstand(true); Retrieving SOAPHeaderElements // Note that an Actor is identified by an URL Iterator headerElements = header.examineHeaderElements("http://gizmos.com/orders"); extractHeaderElements, not only returns an iterator over all of the SOAPHeaderElement objects with the specified actor attribute but also detaches them from the SOAPHeader object. Iterator headerElements=soapHeader.getChildElements(); Iterator headerElements=soapHeader.getChildElements(QName); Iterator headerElements=soapHeader.getChildElements(name);

Creating an AttachmentPart Object and Adding Content The SOAPMessage class has three methods for creating an AttachmentPart object: Method1 AttachmentPart attachment = soapMessage.createAttachmentPart(); Add content to attachment by using the AttachmentPart method setContent (Object obj, String ContentType) The Java Object in the first parameter can be a String, a stream, a javax.xml.transform.Source object, or a javax.activation.DataHandler object. Method 2 String stringContent = "10 Upbeat Street, Pleasant Grove, CA 95439"; attachment.setContent(stringContent, "text/plain"); By default, content type is text/xml,. Each AttachmentPart object has one or more MIME headers associated with it. When you specify a type to the setContent method, that type is used for the header Content-Type.\ Content-Type is the only header that is required SAAJ provides get and set methods for the headers Content-Type, Content-Id, and Content-Location. attachment.setContentId("update_address");

message.addAttachmentPart(attachment); The other two SOAPMessage.createAttachment methods create an AttachmentPart object complete with content. Method 3 URL url = new URL("http://java.boot.by/img.jpg"); DataHandler dataHandler = new DataHandler(url); AttachmentPart attachment = message.createAttachmentPart(dataHandler); attachment.setContentId("attached_image"); message.addAttachmentPart(attachment); unlike the other methods for setting content, this one does not take a String for Content-Type. This method takes care of setting the Content-Type header because of datahandler object. Accessing an AttachmentPart Object java.util.Iterator SOAPMessage.getAttachments() java.util.Iterator iterator = message.getAttachments(); while (iterator.hasNext()) { AttachmentPart attachment = (AttachmentPart)iterator.next(); String id = attachment.getContentId(); String type = attachment.getContentType(); } When getAttachments is given a MimeHeaders object, which is a list of MIME headers, getAttachments returns an iterator over the AttachmentPart objects that have a header that matches one of the headers in the list. javax.xml.soap.MessageFactory is a factory for creating SOAP 1.1-based messages public abstract class MessageFactory { public static MessageFactory newInstance() throws SOAPException { ... } public abstract SOAPMessage createMessage() throws SOAPException; ... javax.xml.soap.SOAPMessage is a Java technology abstraction for a SOAP 1.1 message. Contains EXACTLY ONE SOAPPart and ZERO OR MORE AttachmentParts. public abstract class SOAPMessage { public abstract SOAPPart getSOAPPart(); public abstract Iterator getAttachments(); public abstract Iterator getAttachments(MimeHeaders headers); ...

javax.xml.soap.SOAPPart is the first part of a multi-part message when there are attachments. public abstract class SOAPPart implements org.w3c.dom.Document { public abstract SOAPEnvelope getEnvelope() throws SOAPException; ... Getting a SOAPConnection object SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance(); SOAPConnection connection = soapConnectionFactory.createConnection(); This kind of connection is called a point-to-point connection because it goes from one endpoint to another endpoint. Messages sent using the SAAJ API are called request-response messages. They are sent over a SOAPConnection object with the method call, which sends a message (a request) and then blocks until it receives the reply (a response). Sending a message // Create an endpint point which is either URL or String type java.net.URL endpoint = new URL("http://wombat.ztrade.com/quotes"); // Send a SOAPMessage (request) and then wait for SOAPMessage (response) SOAPMessage response = connection.call(message, endpoint); Getting the content of a message SOAPBody soapBody = response.getSOAPBody(); java.util.Iterator iterator = soapBody.getChildElements(bodyName); SOAPBodyElement bodyElement = (SOAPBodyElement)iterator.next(); String lastPrice = bodyElement.getValue(); System.out.print("The last price for SUNW is "); System.out.println(lastPrice); Creating SOAP FAULT SOAPFault with no Detail object: SOAPFault fault = body.addFault(); fault.setFaultCode("Server"); fault.setFaultActor("http://gizmos.com/orders"); fault.setFaultString("Server not responding"); SOAPFault with Detail object: // Create SOAPFault object SOAPFault fault = body.addFault(); // Set fault code and fault string fault.setFaultCode("Client"); fault.setFaultString("Message does not have necessary info");

// Detail object contains one DetailEntry's Detail detail = fault.addDetail(); Name entryName = envelope.createName("order", "PO", "http://gizmos.com/orders/"); DetailEntry entry = detail.addDetailEntry(entryName); entry.addTextNode("quantity element does not have a value"); Retrieving SOAPFault: SOAPFault newFault = body.getFault(); String code = newFault.getFaultCode(); String string = newFault.getFaultString(); String actor = newFault.getFaultActor(); Retrieving Detail Object: Detail newDetail = newFault.getDetail(); // Get the list of DetailEntry's if ( newDetail != null) { Iterator it = newDetail.getDetailEntries(); while ( it.hasNext() ) { DetailEntry entry = (DetailEntry)it.next(); String value = entry.getValue(); System.out.println(" Detail entry = " + value); }

Complete e.g:
public static void main(String[] args) throws SOAPException, IOException, URISyntaxException { // TODO Auto-generated method stub MessageFactory factory = MessageFactory.newInstance(); SOAPMessage msg = factory.createMessage(); System.out.println("Brand new blank soap msg created is : "); msg.writeTo(System.out); // 2 way to get body SOAPBody soapBody = msg.getSOAPBody(); SOAPBody body = msg.getSOAPPart().getEnvelope().getBody(); QName bodyElementName = new QName("http://SAAJNamespace", "BodyElement", "SAAJ"); SOAPBodyElement bodyElement = body.addBodyElement(bodyElementName); QName elementName = new QName("ChildElement"); SOAPElement element = bodyElement.addChildElement(elementName); element.addTextNode("ChildElementyValue"); // Adding Header // 3 ways to get/crete header SOAPHeader header = msg.getSOAPHeader(); SOAPHeader soapHeader = (SOAPHeader) msg.getSOAPPart().getEnvelope() .getHeader(); if (soapHeader == null)

header = (SOAPHeader) msg.getSOAPPart().getEnvelope().addHeader(); SOAPHeaderElement headerElement = soapHeader .addHeaderElement(new QName("http://headerNamespace", "HeaderElement")); headerElement.setTextContent("HeaderElementValue"); // /Adding SOAP Attachment // 3 ways to create attachment AttachmentPart attachmentPart = msg.createAttachmentPart(); URL dataHandlerURL = new URL( "http://localhost:9090/JAX-WS-WEB/mypic.jpg"); DataHandler dataHandler = new DataHandler(dataHandlerURL); AttachmentPart attachmentPart1 = msg.createAttachmentPart(dataHandler); AttachmentPart attachmentPart2 = msg.createAttachmentPart( ImageIO.read(new File("/mypic.jpg")), "image/jpeg"); attachmentPart1.setContentId("pic"); msg.addAttachmentPart(attachmentPart1); msg.saveChanges(); // read soap Iterator childelements = msg.getSOAPBody().getChildElements( bodyElementName); while (childelements.hasNext()) { System.out.println("chilelement is : " + ((Node) childelements.next()).getValue()); } Iterator headerElements = soapHeader.getChildElements(); while (headerElements.hasNext()) { System.out.println("headerElement is : " + ((Node) headerElements.next()).getValue()); } SOAPConnectionFactory cf = SOAPConnectionFactory.newInstance(); SOAPConnection connection = cf.createConnection(); SOAPMessage responseMessage = connection.call(msg, new URL( "http://localhost:9090/JAX-WS-WEB/testsaaj")); http: // java.boot.by/wsd-guide/ch05s04.html System.out.println("new SOAP:"); msg.writeTo(System.out); connection.close(); }

SAX API SAX processing involves the following steps: 1. Create an event handler. 2. Create the SAX parser. 3. Assign the event handler to the parser. 4. Parse the document, sending each event to the handler. Create SaxParserFactory Instance SaxParser XmlReader Set Validation Options Set Content Handlercreate a content handler by implementing DefaultHandler. Default Handler includes implementations of both the ContentHandler methods and the ErrorHandler methods. Get Input Source Parse the input source Set Error Handler Write logic to print i9n startElement and endelement methods of content Handler Get the actual data using public void characters(char[] ch, int start, int length)in contentHandler
Note two important things here: o Range: The characters() event includes more than just a string of characters. It also

includes start and length information. In actuality, the ch character array includes the entire document. The application must not attempt to read characters outside the range the event feeds to the characters() event. o Frequency: Nothing in the SAX specification requires a processor to return characters in any particular way, so it's possible for a single chunk of text to be returned in several pieces. Always make sure that the endElement() event has occurred before assuming you have all the content of an element. Also, processors may use ignorableWhitespace() to return whitespace within an element. This is always the case for a validating parser.

The parser actually passes several pieces of information for each element: The qualified name, or qName. This is actually a combination of namespace information, if any, and the actual name of the element. The qName also includes the colon (:) if there is one - for example, revised:question. The namespace URI. An actual namespace is a URI of some sort and not the alias that gets added to an element or attribute name. For example, http://www.example.com as opposed to simply revised:. The local name. This is the actual name of the element, such as question. If the document doesn't provide namespace information, the parser may not be able to determine which part of the qName is the localName. Any attributes. The attributes for an element are actually passed as a collection of objects.

Resolving Entities. org.xml.sax.EntityResolver interface The EntityResolver API lets you convert a public ID (URN) into a system ID (URL). Your application may need to do that, for example, to convert something like href="urn:/someName" into "http://someURL". EntityResolver interface contains just a single method, resolveEntity(...). If you register an EntityResolver with an XMLReader, then every time that XMLReader needs to load an external parsed entity, it will pass the entity's public ID and system ID to resolveEntity(...) first. public class UseLocal implements EntityResolver { public InputSource resolveEntity(String publicId, String systemId) throws FileNotFoundException { if (systemId.equals("http://server.com/DTD/quiz.dtd")) { // use local version return new InputSource(new FileInputStream("local/DTD/quiz.dtd")); } else { // use the default behaviour return null; } } }

DOM

A DOM Document is a collection of nodes, or pieces of information, organized in a hierarchy.Analyzing the structure normally requires the entire document to be loaded and the hierarchy to be built before any work is done. Because it is based on a hierarchy of information, the DOM is said to be tree-based, or object-based.For exceptionally large documents, parsing and loading the entire document can be slow and resource-intensive. DOM provides an API that allows a developer to add, edit, move, or remove nodes The basic node types Elements Attributes Text Documentparent for all nodes in the document Parsing a file into a document Create the DocumentBuilderFactory. This object creates the DocumentBuilder. Create the DocumentBuilder. The DocumentBuilder does the actual parsing to create thDocument object. Parse the file to create the Document object. File docFile = new File("orders.xml"); Document doc = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); doc = db.parse(docFile); } catch (Exception e) { System.out.print("Problem parsing the file: "+e.getMessage()); } Root Element: Element root = doc.getDocumentElement(); System.out.println("The root element is " + root.getNodeName()); Child Elements: NodeList children = root.getChildNodes(); System.out.println("There are "+children.getLength()+" nodes in this document."); The parent-child and sibling relationships offer an alternative means for iterating through all of the children of a node for (Node child = root.getFirstChild(); child != null; child = child.getNextSibling()) { System.out.println(child.getNodeName() + " = " + child.getNodeValue()); } A Node object carries member constants that represent each type of node, such as ELEMENT_NODE or ATTRIBUTE_NODE. If the nodeType matches ELEMENT_NODE, it is an element. NamedNodeMap that contains all of the attributes for the element

if (start.getNodeType() == start.ELEMENT_NODE) { NamedNodeMap startAttr = start.getAttributes(); for (int i = 0; i < startAttr.getLength(); i++) { Node attr = startAttr.item(i); System.out.println(" Attribute: "+ attr.getNodeName() +" = "+attr.getNodeValue()); } }

TrAX (Transformation API for XML) TrAX is an API for transforming XML documents using XSLT style sheets. TrAX is part of the JAXP API, which combines a number of Java APIs. TrAX relies upon a SAX2- and DOM-level-2-compliant XML parser/XSLT engine.

// 1. create the XML content input source: // can be a DOM node, SAX stream, or any Java input stream/reader String xmlInputFile = "myXMLinput.xml"; Source xmlSource = new StreamSource(new FileInputStream(xmlInputFile)); // 2. create the XSLT Stylesheet input source // can be a DOM node, SAX stream, or a java input stream/reader String xsltInputFile = "myXsltStylesheet.xsl"; Source xsltSource = new StreamSource(new FileInputStream(xsltInputFile)); // 3. create the result target of the transformation // can be a DOM node, SAX stream, or a java out stream/reader String xmlOutputFile = "result.html"; Result transResult = new StreamResult(new FileOutputStream(xmlOutputFile)); // 4. create the transformerfactory and transformer instance TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(xsltSource); // 5. execute transformation and fill result target object t.transform(xmlSource, transResult); A single Transformer instance can be reused, but it is not thread-safe. Source The Source interface is a generic container for existing XML documents that will be used in a transformation. Result The Result interface is a generic container for an XML document that will be produced by a transformation. Templates Templates is a thread-safe interface that represents a compiled stylesheet. It can quickly create new Transformer objects without having to reread and reparse the original stylesheet. Templates instances may be reused to increase performance, and they are thread-safe. TransformerFactory TransformerFactory is an abstract factory that creates new Transformer and Templates objects. Transformer Transformer is the abstract class that represents a compiled stylesheet. It transforms Source objects into Result objects. A single Transformer can transform multiple input documents in sequence but not in parallel. Act as a per-thread execution context for transformations,
JAXB The JAXB API, defined in the javax.xml.bind package, is a set of interfaces through which client applications communicate with code generated from a schema. JAXBContext, the client' s entry point

javax.xml.bind.Unmarshaller - governs the process of deserializing XML data into Java content
trees, optionally validating the XML data as it is unmarshalled.

public interface Unmarshaller { public public public public public public Object Object Object Object Object Object unmarshal(File f) throws JAXBException; unmarshal(InputStream is) throws JAXBException; unmarshal(URL url) throws JAXBException; unmarshal(InputSource source) throws JAXBException; unmarshal(Node node) throws JAXBException; unmarshal(Source source) throws JAXBException;

public UnmarshallerHandler getUnmarshallerHandler(); public void setValidating(boolean validating) throws JAXBException; public boolean isValidating() throws JAXBException; public void setEventHandler(ValidationEventHandler handler) throws JAXBException; public ValidationEventHandler getEventHandler() throws JAXBException; public void setProperty(String name, Object value) throws PropertyException; public Object getProperty(String name) throws PropertyException; }

javax.xml.bind.Marshaller - governs the process of serializing Java content trees back


into XML data.

public interface Marshaller { public static final String JAXB_ENCODING = "jaxb.encoding"; public static final String JAXB_FORMATTED_OUTPUT = "jaxb.formatted.output"; public static final String JAXB_SCHEMA_LOCATION = "jaxb.schemaLocation"; public static final String JAXB_NO_NAMESPACE_SCHEMA_LOCATION = "jaxb.noNamespaceSchemaLocation"; public void marshal(Object public void marshal(Object public void marshal(Object public void marshal(Object JAXBException; public void marshal(Object obj, obj, obj, obj, Result result) throws JAXBException; OutputStream os) throws JAXBException; Writer writer) throws JAXBException; ContentHandler handler) throws

obj, Node node) throws JAXBException;

public org.w3c.dom.Node getNode(Object contentTree) throws JAXBException; public void setProperty(String name, Object value) throws PropertyException; public Object getProperty(String name) throws PropertyException;

public void setEventHandler(ValidationEventHandler handler) throws JAXBException; public ValidationEventHandler getEventHandler() throws JAXBException; }

javax.xml.bind.Validator - performs the validation on an in-memory object graph. public interface Validator { public void setEventHandler(ValidationEventHandler handler) throws JAXBException; public ValidationEventHandler getEventHandler() throws JAXBException; public boolean validate(Object subrootObj) throws JAXBException; public boolean validateRoot(Object rootObj) throws JAXBException; public void setProperty(String name, Object value) throws PropertyException; public Object getProperty(String name) throws PropertyException;

JAXBContext context = JAXBContext.newInstance("org.acme.foo:org.acme.bar");

JAXB can produce XML as SAX events. That is, you can pass ContentHandler and have it receive SAX events from a JAXB object. This gives client apps plenty of chances to modify XML.

Validation There are three forms of Validation in JAXB: 1. Unmarshal-Time Validation This form of validation enables a client application to receive information about validation errors and warnings detected while unmarshalling XML data into a Java content tree and is completely orthogonal to the other types of validation. To enable or disable it use method Unmarhaller.setValidating(...). All JAXB Providers are REQUIRED to support this operation. 2. On-Demand Validation This form of validation enables a client application to receive information about validation errors and warnings detected in the Java content tree. At any point, client applications can call the Validator.validate(...) method on the Java content tree (or any sub-tree of it). All JAXB Providers are REQUIRED to support this operation. 3. Fail-Fast Validation

This form of validation enables a client application to receive immediate feedback about modifications to the Java content tree that violate type constraints on Java Properties as defined in the specification. JAXB Providers are NOT REQUIRED support this type of validation. Of the JAXB Providers that do support this type of validation, some may require you to decide at schema compile time whether or not a client application will be allowed to request fail-fast validation at runtime. The Validator class is responsible for managing On-Demand Validation. The Unmarshaller class is responsible for managing Unmarshal-Time Validation during the unmarshal operations. JAXB has the capability to validate an object graph in memory without actually writing it to XML. To receive detailed information about errors, you need to register ValidationEventHandler with the Validator

JAXBContext jaxbContext = JAXBContext.newInstance(packageName); ObjectFactory itemMaker = new ObjectFactory(); Item item = itemMaker.createItem(); Validator validator = jaxbContext.createValidator(); if(! validator.validate(item)) { System.err.println("Not valid !!!");

JAXB customizations to configure mapping. There are two ways to associate a binding declaration with a schema element: as part of the source schema (inline annotated schema). external to the source schema in an external binding declaration. Inline Annotated Schema This method of customization utilizes on the appinfo element specified by the XML Schema. A binding declaration is embedded within the appinfo element as illustrated below. Below Changes are made to the schema to make JAXB generate java.util.Vector rather than java.util.ArrayList, its default collection <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" jxb:version="1.0"> <xs:annotation> <xs:appinfo> <jxb:globalBindings collectionType="java.util.Vector" /> </xs:appinfo> </xs:annotation> <xs:element name="todolist"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" minOccurs="0" name="item" type="entry"/> </xs:sequence> </xs:complexType>

</xs:element> ... </xs:schema> The annotation tag introduces a part of the schema that is usually intended for schema processing software. The appinfo tag introduces instructions for a particular processing application Before customization: public class TodolistTypeImpl implements ... { protected com.sun.xml.bind.util.ListImpl _Item = new com.sun.xml.bind.util.ListImpl(new java.util.ArrayList()); After: public class TodolistTypeImpl implements ... { protected com.sun.xml.bind.util.ListImpl _Item = new com.sun.xml.bind.util.ListImpl(new java.util.Vector()); External Binding Declaration The external binding declaration format enables customized binding without requiring modification of the source schema. <jaxb:bindings schemaLocation = "xs:anyURI"> <jaxb:bindings node = "xs:string">* <binding declaration> <jaxb:bindings> </jaxb:bindings> schemaLocation/node declaration in a JAXB binding declarations file specifies the schema name and the root schema node <jxb:bindings schemaLocation="po.xsd" node="/xsd:schema"> A subsequent schemaLocation/node declaration, say for a simpleType element named ZipCodeType in the schema, would take the form: <jxb:bindings node="//xsd:simpleType[@name='ZipCodeType']"> Customization files containing binding declarations are passed to the JAXB Binding compiler, xjc, using the following syntax: xjc -b <file> <schema> You can have a single binding file that contains customizations for multiple schemas, or you can break the customizations into multiple bindings files: xjc schema1.xsd schema2.xsd schema3.xsd -b bindings1.xjb -b bindings2.xjb -b bindings3.xjb

There are two ways with which we can ensure security with Web Services. They are: 1. Security at Transport level 2. Security at XML level

Transport Level Security based on SSL or TLS(Transport layer security) that runs beneath HTTP: Using HTTPS provides Authentication Data Protection Cryptographic Token Integrity & Confidentiality Secure n/w protocol SSL preferred over tcp/ip Encrypt all n/w traffic over socket SSL can also use PKI infrastructure for authentication SSL can use server side/client sisde certificate Server side certificate is most common, where client authenticates server but not the server to client Client auth is provided by basic/digest auth. Base 64 encoded Basic auth located in http herader that carries soap request. Server retrieves user/pwd info and apply security mechanism.
Security at XML level

XML Encryption

Unlike SSL, with XML Encryption, you can encrypt only the data that needs to be encrypted, for example, only the credit card information in a purchase order XML document e.g:
<purchaseOrder> <name>Mikalai Zaikin</name> <address> ... </address> <EncryptedData Type='http://www.w3.org/2001/04/xmlenc#Element' xmlns='http://www.w3.org/2000/11/temp-xmlenc'> <EncryptionMethod Algorithm="urn:nist-gov:tripledes-ede-cbc"> <s0:someMethod xmlns:s0='http://somens'>ABCD</s0:someMethod> </EncryptionMethod> <KeyInfo xmlns='http://www.w3.org/2000/09/xmldsig#'> <KeyName>SharedKey</KeyName> </KeyInfo> <CipherData> <CipherValue>A23B45C564562347e23e</CipherValue> </CipherData> </EncryptedData> <prodNumber>8a32gh19908</prodNumber> <quantity>1</quantity> </purchaseOrder>

In XML Encryption, your plaintext is either an element or that element's content.After encryption, you get an XML element called EncryptedData, containing the ciphertext in Base64-encoded format. That EncryptedData element replaces your plaintext.
<foo> <bar>secret text</bar> </foo> Encrypting bar element <foo> <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns=...> <!-- some info, including the ciphertext --> </EncryptedData> </foo> Encrypting bar elements content <foo> <bar> <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Content" xmlns=...> <!-- some info, including the ciphertext --> </EncryptedData> </bar> </foo>
looking at type attribute, we can tell immediately whether the plaintext is an element of just its content.

<EncryptedData Id? Type? MimeType? Encoding?> <EncryptionMethod/>? <ds:KeyInfo>

<EncryptedKey>? <AgreementMethod>? <ds:KeyName>? <ds:RetrievalMethod>? <ds:*>? </ds:KeyInfo>? <CipherData> <CipherValue>? <CipherReference URI?>? </CipherData> <EncryptionProperties>? </EncryptedData>
CipherData, either directly contains the ciphertext in CipherValue, or, if CipherReference is
used, a reference to it EncryptionMethod lets you specify the algorithm and key size, but usually you and the other party will agree on those beforehand. KeyInfo: it gives you the flexibility to give the other party the material to decrypt your message, but you'd probably want to sent it through some out-of-band mechanism

EncryptionProperties serves as another optional element used for, optional information <?xml version='1.0'?> <PaymentInfo xmlns='http://example.org/paymentv2'> <Name>John Smith</Name> <CreditCard Limit='5,000' Currency='USD'> <Number>4019 2445 0277 5567</Number> <Issuer>Example Bank</Issuer> <Expiration>04/02</Expiration> </CreditCard> </PaymentInfo>

By encrypting the entire CreditCard element from its start to end tags
<?xml version='1.0'?> <PaymentInfo xmlns='http://example.org/paymentv2'> <Name>John Smith</Name> <EncryptedData Type='http://www.w3.org/2001/04/xmlenc#Element' xmlns='http://www.w3.org/2001/04/xmlenc#'> <CipherData> <CipherValue>A23B45C56</CipherValue> </CipherData> </EncryptedData> </PaymentInfo> By encrypting the entire CreditCard element from its start to end tags, the identity of the element itself is hidden. The CipherData element contains the encrypted serialization of the CreditCard

element Encrypting XML Element Content (Elements)


<CreditCard Limit='5,000' Currency='USD'> <Number>4019 2445 0277 5567</Number> <Issuer>Example Bank</Issuer> <Expiration>04/02</Expiration> </CreditCard>

<?xml version='1.0'?> <PaymentInfo xmlns='http://example.org/paymentv2'> <Name>John Smith</Name> <CreditCard Limit='5,000' Currency='USD'> <EncryptedData xmlns='http://www.w3.org/2001/04/xmlenc#' Type='http://www.w3.org/2001/04/xmlenc#Content'> <CipherData> <CipherValue>A23B45C56</CipherValue> </CipherData> </EncryptedData> </CreditCard>

</PaymentInfo>
Encrypting XML Element Content (Character Data)

<CreditCard Limit='5,000' Currency='USD'> <Number> <EncryptedData xmlns='http://www.w3.org/2001/04/xmlenc#' Type='http://www.w3.org/2001/04/xmlenc#Content'> <CipherData> <CipherValue>A23B45C56</CipherValue> </CipherData> </EncryptedData> </Number>

If the application scenario requires all of the information to be encrypted, the whole document is encrypted as an octet sequence. This applies to arbitrary data including XML documents
<?xml version='1.0'?> <EncryptedData xmlns='http://www.w3.org/2001/04/xmlenc#' MimeType='text/xml'> <CipherData> <CipherValue>A23B45C56</CipherValue> </CipherData> </EncryptedData>

Super-Encryption: Encrypting EncryptedData The actual data encrypted can be anything, including EncryptedData and EncryptedKey elements During super-encryption of an EncryptedData or EncryptedKey element, one must encrypt the entire element.
<pay:PaymentInfo xmlns:pay='http://example.org/paymentv2'> <EncryptedData Id='ED1' xmlns='http://www.w3.org/2001/04/xmlenc#' Type='http://www.w3.org/2001/04/xmlenc#Element'> <CipherData> <CipherValue>originalEncryptedData</CipherValue> </CipherData> </EncryptedData> </pay:PaymentInfo>
A valid super-encryption of "//xenc:EncryptedData[@Id='ED1']" would be:

<pay:PaymentInfo xmlns:pay='http://example.org/paymentv2'> <EncryptedData Id='ED2' xmlns='http://www.w3.org/2001/04/xmlenc#' Type='http://www.w3.org/2001/04/xmlenc#Element'>

<CipherData> <CipherValue>newEncryptedData</CipherValue> </CipherData> </EncryptedData> </pay:PaymentInfo>


where the CipherValue content of 'newEncryptedData' is the base64 encoding of the encrypted octet sequence resulting from encrypting the EncryptedData element with Id='ED1'.

XML Digital Signature


provides authentication, data integrity (tamper-proofing), and nonrepudiation XML Digital Signature provides a flexible means of signing and supports diverse sets of Internet transaction models. For example, you can sign individual items or multiple items of an XML document. The document you sign can be local or even a remote object, as long as those objects can be referenced through a URI Another important area that XML digital signature addresses is the canonicalization of XML documents. Canonicalization enables the generation of the identical message digest and thus identical digital signatures for XML documents that are syntactically equivalent but different in appearance due to, for example, a different number of white spaces present in the documents. A signature can be either enveloped or enveloping, which means the signature can be either embedded in a document being signed or reside outside the document. XML digital signature also allows multiple signing levels for the same content, thus allowing flexible signing semantics. For example, the same content can be semantically signed, cosigned, witnessed, and notarized by different people. XML Signatures are applied to arbitrary digital content (data objects) via an indirection. Data objects are digested, the resulting value is placed in an element (with other information) and that element is then digested and cryptographically signed. XML digital signatures are represented by the Signature element which has the following structure

<Signature ID?> <SignedInfo> <CanonicalizationMethod/> <SignatureMethod/> (<Reference URI? > (<Transforms>)? <DigestMethod> <DigestValue> </Reference>)+ </SignedInfo> <SignatureValue> (<KeyInfo>)? (<Object ID?>)* </Signature>
Signatures are related to data objects via URIs. Within an XML document, signatures are related to local data objects via fragment identifiers. Such local data can be included within an enveloping signature or can enclose an enveloped signature. Detached signatures are over external network resources or local data objects that reside within the same XML document as sibling elements;

The required SignedInfo element is the information that is actually signed. Core validation of SignedInfo consists of two mandatory processes: validation of the signature over SignedInfo and validation of each Reference digest within SignedInfo. algorithms used in calculating the SignatureValue are also included in the signed information while the SignatureValue element is outside SignedInfo.

Enveloped The signature is over the XML content that contains the signature as an element. The content provides the root XML document element. Obviously, enveloped signatures must take care not to include their own value in the calculation of the SignatureValue. Signature is enveloped within the content been signed:
<doc Id="myID"> <myElement> ... </myElement> <Signature> ... <Reference URI="#myID"/> ... </Signature> </doc>

Enveloping An enveloping signature is useful when the signing facility wants to add its own metadata (such as a timestamp) to a signature - it doesn't have to modify the source document, but can include additional data covered by the signature within the signature document it generates Signature envelopes the contents to be signed:
<Signature> ... <Reference URI="#myRefObjectID"> ... </Reference> <Object Id="myRefObjectID"> <doc> <myElement> ... </myElement> ... </doc> </Object> </Signature>

Detached A detached signature is useful when you can't modify the source; the downside is that it requires two XML documents - the source and its signature - to be carried together Signature is external to the content that is signed:
<Signature>

... <Reference URI="http://www.buy.com/books/purchaseWS"/> ... </Signature>


How to Create an XML Signature

Determine which resources are to be signed. This will take the form of identifying the resources through a Uniform Resource Identifier (URI). e.g; "http://www.abccompany.com/index.html" - would reference an HTML page on the Web on the Web "http://www.abccompany.com/xml/po.xml" - would reference an XML file on the Web "http://www.abccompany.com/xml/po.xml#sender1" - would reference a specific element in an XML file on the Web Calculate the digest of each resource.
<Reference URI="http://www.abccompany.com/news/2000/03_27_00.htm"> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /> <DigestValue>j6lwx3rvEPO0vKtMup4NbeVu8nk=</DigestValue> </Reference>
Collect the Reference elements within a SignedInfo element like

<SignedInfo Id="foobar"> <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n20010315"/> <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#dsa-sha1" /> <Reference URI="http://www.abccompany.com/news/2000/03_27_00.htm"> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /> <DigestValue>j6lwx3rvEPO0vKtMup4NbeVu8nk=</DigestValue> </Reference> </SignedInfo>

The CanonicalizationMethod element indicates the algorithm was used to canonize the SignedInfo element Signing Calculate the digest of the SignedInfo element, sign that digest and put the signature value in a SignatureValue element:
<SignatureValue>MC0CFFrVLtRlk=...</SignatureValue>

Add key information If keying information is to be included, place it in a KeyInfo element


<KeyInfo> <X509Data> <X509SubjectName>CN=Ed Simon,O=XMLSec Inc.,ST=OTTAWA,C=CA</X509SubjectName> <X509Certificate>MIID5jCCA0+gA...lVN</X509Certificate> </X509Data> </KeyInfo>

Enclose in a Signature element

Place the SignedInfo, SignatureValue, and KeyInfo elements into a Signature element.
Verifying an XML Signature: A brief description of how to verify an XML signature: Verify the signature of the SignedInfo element. To do so, recalculate the digest of the SignedInfo element (using the digest algorithm specified in the SignatureMethod element) and use the public verification key to verify that the value of the SignatureValue element is correct for the digest of the SignedInfo element. If this step passes, recalculate the digests of the references contained within the SignedInfo element and compare them to the digest values expressed in each Reference element's corresponding DigestValue element.

SAML-Security Assertions Markup Language: XML-based framework for exchanging security information. it deals with three things. Defines syntax and semantics of XML-encoded assertion messages. Defines request and response protocols between requesting and asserting parties for exchanging security information. Defines rules for using assertions with standard transport and message frameworks. The security information for exchange is expressed in the form of assertions about subjects, where a subject is an entity (either human or computer) that has an identity in some security domain. Assertions are represented as XML constructs and have a nested structure. Assertions are issued by SAML authorities, namely, authentication authorities, attribute authorities, and policy decision points. SAML defines a protocol by which clients can request assertions from SAML authorities and get a response from them. Assertions can convey information about authentication acts performed by subjects, attributes of subjects, and authorization decisions about whether subjects are allowed to access certain resources. while clients always consume assertions, SAML authorities can be both producers and consumers of assertions for response. One major design goal for SAML is Single Sign-On (SSO), the ability of a user to authenticate in one domain and use resources in other domains without re-authenticating.

XACML - Extensible Access Control Markup Language XACML is a general-purpose access control policy language. it provides a syntax (defined in XML) for managing access to resources. XACML is an OASIS standard that describes both a policy language and an access control decision request/response language (both written in XML). The policy language is used to describe general access control requirements, and has standard extension points for defining new functions, data types, combining logic, etc. The request/response language lets you form a query to ask whether or not a given action should be allowed, and interpret the result.

The response always includes an answer about whether the request should be allowed using one of four values: Permit, Deny, Indeterminate (an error occurred or some required value was missing, so a decision cannot be made) or Not Applicable (the request can't be answered by this service). How does it work: Client send request to PEP(Policy Enforcenment point) The PEP will form a request based on the requester's attributes then send this request to a Policy Decision Point (PDP), That answer is returned to the PEP, which can then allow or deny access to the requester. PEP and PDP might both be contained within a single application, or might be distributed across several servers.

Not suitable for small and mobiloe devices. XKMS (XML Key Management Specification) It consists of two parts: XKISS (XML Key Information Service Specification) and XKRSS (XML Key Registration Service Specification).

XKISS defines a protocol for resolving or validating public keys contained in signed and encrypted XML documents. XKRSS defines a protocol for public key registration, revocation, and recovery. XKMS enables an XKMS server to perform PKI operations. PKI proves important for e-commerce and Web services. However, one of the obstacles to PKI's wide adoption is that PKI operations such as public key validation, registration, recovery, and revocation are complex and require large amounts of computing resources, which prevents some applications and small devices such as cell phones from participating in PKI-based e-commerce or Web services transactions. PKI refers to a set of security services for authentication, encryption and digital certificate management under which documents are encrypted with a private key and decrypted using a publicly available key accessible to the recipient via a network. PKI differs from private key technology, like Kerberos, in which a single key that is shared by the sender and receiver is used to encrypt and decrypt a message or document. XKMS is a foundational specification for secure Web services, enabling Web services to register and manage cryptographic keys used for digital signatures and encryption. XKMS, developers can integrate authentication, digital signature, and encryption services, such as certificate processing and revocation status checking, into applications. An XKMS-compliant service supports the following operations:

Register: XKMS services can be used to register key pairs for escrow services. Generation of
the public key pair may be performed by either the client or the registration service. Once keys are registered, the XKMS-compliant service manages the revocation and recovery of registered keys, whether client- or server-generated. Additional functions are reissue, revoke, and recover.

Locate: The Locate service is used to retrieve a public key registered with an XKMS-compliant
service. The public key can in turn be used to encrypt a document or verify a signature.

Validate: The Validate service is used to ensure that a public key registered with an XKMS-

compliant service is valid, and has not expired or been revoked. The validation service can also be used to check attributes against a public key.

The Benefits of XKMS XKMS provides many benefits. The most important benefits are that XKMS is:

Easy to use: The XKMS specification allows developers to rapidly implement trust features,

incorporating cryptographic support for XML digital signatures and XML encryption using standard XML toolkits. Quick to deploy: By simplifying application development, XKMS removes the need to delay PKI deployment because of , and instead, moves the complexity of PKI to server side components. Open: The XKMS specification has been submitted to the World Wide Web Consortium (W3C) as an open standard for distribution and registration of keys. Ideal for mobile devices: XKMS allow mobile devices to access full-featured PKI through ultraminimal-footprint client device interfaces. Future-proof: Supports new and emerging PKI developments since the impact of future PKI developments is restricted to server-side components

WS-Security It supports message integrity and confidentiality by allowing communicating partners to exchange signed and encrypted messages in a Web services environment. Because it is based on XML digital signature and XML Encryption standards. WS-Security supports multiple security models, such as username/password-based and certificate-based models. It also supports multiple security technologies, including Kerberos, PKI, SAML, and so on. In addition, it supports multiple security tokens; for example, tokens that contain Kerberos tickets, X.509 certificates, or SAML assertions. Signature+security token=integrity Encryption=confidentiality Message integrity(XML Signature) Message Confidentiality(XML Encryption) Single Message Authentication(Security username Tokens) WS-Security specification provides a means to protect a message by encrypting and/or digitally signing a body, a header, an attachment, or any combination of them (or parts of them). Message integrity is provided by leveraging XML Signature in conjunction with security tokens to ensure that messages are transmitted without modifications. The Security header block provides a mechanism for attaching security-related information targeted at a specific receiver (SOAP actor). this header block MAY be present multiple times in a SOAP message. a message MAY have multiple Security header blocks if they are targeted for separate receivers. However, only one Security header block can omit the S:actor attribute and no two Security

header blocks can have the same value for S:actor. Message security information targeted for different receivers MUST appear in different Security header blocks.

<S:Envelope> <S:Header> ... <Security S:actor="..." S:mustUnderstand="..."> <!-actor attribute is optional, however no two instances of the header block may omit an actor or specify the same actor --> ... </Security> ... </S:Header> ...

</S:Envelope>
(001) <?xml version="1.0" encoding="utf-8"?> (002) <S:Envelope xmlns:S="http://www.w3.org/2001/12/soap-envelope" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/04/secext" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"> (003) <S:Header> (004) <m:path xmlns:m="http://schemas.xmlsoap.org/rp/"> (005) <m:action>http://fabrikam123.com/getQuote</m:action> (006) <m:to>http://fabrikam123.com/stocks</m:to> (007) <m:from>mailto:johnsmith@fabrikam123.com</m:from> (008) <m:id>uuid:84b9f5d0-33fb-4a81-b02b-5b760641c1d6</m:id> (009) </m:path> (010) <wsse:Security> (011) <wsse:BinarySecurityToken ValueType="wsse:X509v3" Id="X509Token" EncodingType="wsse:Base64Binary"> (012) MIIEZzCCA9CgAwIBAgIQEmtJZc0rqrKh5i... (013) </wsse:BinarySecurityToken> (014) <xenc:EncryptedKey> (015) <xenc:EncryptionMethod Algorithm= "http://www.w3.org/2001/04/xmlenc#rsa-1_5"/> (016) <ds:KeyInfo> (017) <ds:KeyName>CN=Hiroshi Maruyama, C=JP</ds:KeyName> (018) </ds:KeyInfo> (019) <xenc:CipherData> (020) <xenc:CipherValue>d2FpbmdvbGRfE0lm4byV0... (021) </xenc:CipherValue> (022) </xenc:CipherData> (023) <xenc:ReferenceList> (024) <xenc:DataReference URI="#enc1"/> (025) </xenc:ReferenceList> (026) </xenc:EncryptedKey> (027) <ds:Signature> (028) <ds:SignedInfo> (029) <ds:CanonicalizationMethod

(030) (031) (032) (033) (034) (035) (036) (037) (038) (039) (040) (041) (042) (043) (044) (045) (046) (047) (048) (049) (050) (051) (052) (053) (054) (055) (056) (057) (058) (059) (060) (061)

Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/> <ds:Reference> <ds:Transforms> <ds:Transform Algorithm="http://...#RoutingTransform"/> <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> </ds:Transforms> <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <ds:DigestValue>LyLsF094hPi4wPU... </ds:DigestValue> </ds:Reference> </ds:SignedInfo> <ds:SignatureValue> Hp1ZkmFZ/2kQLXDJbchm5gK... </ds:SignatureValue> <ds:KeyInfo> <wsse:SecurityTokenReference> <wsse:Reference URI="#X509Token"/> </wsse:SecurityTokenReference> </ds:KeyInfo> </ds:Signature> </wsse:Security> </S:Header> <S:Body> <xenc:EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" Id="enc1"> <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#3des-cbc"/> <xenc:CipherData> <xenc:CipherValue>d2FpbmdvbGRfE0lm4byV0... </xenc:CipherValue> </xenc:CipherData> </xenc:EncryptedData> </S:Body> </S:Envelope>

Liberty Project

Create an open standard for identity, authentication and authorization. Objective: lower costs, accelerate commercial opportunities, and increase customer
satisfaction

Federated standard will enable every business to: o Maintain their own customer/employee/device data. o Tie data to an individuals or businesss identity. o Share data with partners according to its business objectives, and customers
preferences.

MessageLevel Security
Message-level security applies security checks to a SOAP message after a Web services client establishes a connection with an Oracle Service Bus proxy service or business service and before the proxy service or business service processes the message. Message-level security is categorized as follows: Inbound message-level security applies to messages between clients and Oracle Service Bus proxy services. It applies security to both the request from the client and the response message back to the client. You can think of this as proxy service security.
Outbound message-level security applies to messages between Oracle Service Bus proxy services and SOAP-HTTP or SOAP-JMS business services. It applies security to both the request and the response.

You can think of this as business service security.

Metro project wsit The abstract service description is defined in a WSDL document as a PortType. A concrete Service instance is defined by the combination of a PortType, transport & encoding binding and an address as a WSDL port. Sets of ports are aggregated into a WSDL service.

StAX API
The StAX API exposes methods for iterative, event-based processing of XML documents. XML documents are treated as a filtered series of events, and infoset states can be stored in a procedural fashion. Moreover, unlike SAX, the StAX API is bidirectional, enabling both reading and writing of XML documents. The StAX API is really two distinct API sets: a cursor API and an iterator API Cursor API
StAX cursor API represents a cursor with which you can walk an XML document from beginning to end. This cursor can point to one thing at a time, and always moves forward, never backward, usually one infoset element at a time. The two main cursor interfaces are XMLStreamReader and XMLStreamWriter. XMLStreamReader includes accessor methods for document encoding, element names, attributes, namespaces, text nodes, start tags, comments, processing instructions, document boundaries, and so forth.

XMLStreamWriter provides methods that correspond to StartElement and EndElement event types. public interface XMLStreamWriter { public void writeStartElement(String localName) \ throws XMLStreamException; public void writeEndElement() \ throws XMLStreamException; public void writeCharacters(String text) \ throws XMLStreamException; // ... other methods not shown }

Iterator API The base iterator interface is called XMLEvent, and there are subinterfaces for each event type listed in Table 3-2, below. The primary parser interface for reading iterator events is XMLEventReader, and the primary interface for writing iterator events is XMLEventWriter.
XMLEventReader implements java.util.Iterator public interface XMLEventReader extends Iterator { public XMLEvent nextEvent() throws XMLStreamException; public boolean hasNext(); public XMLEvent peek() throws XMLStreamException; ... } public interface XMLEventWriter { public void flush() throws XMLStreamException; public void close() throws XMLStreamException; public void add(XMLEvent e) throws XMLStreamException; public void add(Attribute attribute) \ throws XMLStreamException; ...

Iterator Event Types


Table 3-2 XMLEvent Types Event Type Description Reports the beginning of a set of XML events, including encoding, XML version, and standalone properties. Reports the start of an element, including any attributes and namespace declarations; also provides access to the prefix, namespace URI, and local name of the start tag. Reports the end tag of an element. Namespaces that have gone out of scope can be recalled here if they have been explicitly set on their corresponding StartElement. Corresponds to XML CData sections and CharacterData entities. Note that ignorable whitespace and significant whitespace are also reported as Character events. Character entities can be reported as discrete events, which an application developer can then choose to resolve or pass through unresolved. By default, entities are resolved. Alternatively, if you do not want to report the entity as an event, replacement text can be substituted and reported as Characters.

StartDocument StartElement

EndElement

Characters

EntityReference

ProcessingInstruction Reports the target and data for an underlying processing instruction.
Comment EndDocument DTD Returns the text of a comment Reports the end of a set of XML events. Reports as java.lang.String information about the DTD, if any, associated with the stream, and provides a method for returning custom objects found in the DTD. Attributes are generally reported as part of a StartElement event. However, there are times when it is desirable to return an attribute as a standalone Attribute event; for example, when a namespace is returned as the result of an XQuery or XPath expression. As with attributes, namespaces are usually reported as part of a StartElement, but there are times when it is desirable to report a namespace as a discrete Namespace event.

Attribute

Namespace

Note that the DTD, EntityDeclaration, EntityReference, NotationDeclaration, and ProcessingInstruction events are only created if the document being processed contains a DTD.

The events are created in the order in which the corresponding XML elements are encountered in the document, including nesting of elements, opening and closing of elements, attribute order, document start and document end, and so forth. As with proper XML syntax, all container elements have corresponding start and end events; for example, every StartElement has a corresponding EndElement, even for empty elements. Attribute events are treated as secondary events, and are accessed from their corresponding StartElement event. Similar to Attribute events, Namespace events are treated as secondary, but appear twice and are accessible twice in the event stream, first from their corresponding StartElement and then from their corresponding EndElement. Character events are specified for all elements, even if those elements have no character data. Similarly, Character events can be split across events.

The StAX parser maintains a namespace stack, which holds information about all XML namespaces defined for the current element and its ancestors. The namespace stack is exposed through the javax.xml.namespace.NamespaceContext interface, and can be accessed by namespace prefix or URI.

Comparing Cursor and Iterator APIs


Before choosing between the cursor and iterator APIs, you should note a few things that you can do with the iterator API that you cannot do with cursor API:
Objects created from the XMLEvent subclasses are immutable, and can be used in arrays, lists, and maps, and can be passed through your applications even after the parser has moved on to subsequent events. You can create subtypes of XMLEvent that are either completely new information items or extensions of existing items but with additional methods. You can add and remove events from an XML event stream in much simpler ways than with the cursor API.

Similarly, keep some general recommendations in mind when making your choice:
If you are programming for a particularly memory-constrained environment, like J2ME, you can make smaller, more efficient code with the cursor API. If performance is your highest priority--for example, when creating low-level libraries or infrastructure--the cursor API is more efficient. If you want to create XML processing pipelines, use the iterator API. If you want to modify the event stream, use the iterator API. If you want to your application to be able to handle pluggable processing of the event stream, use the iterator API. In general, if you do not have a strong preference one way or the other, using the iterator API is recommended because it is more flexible and extensible, thereby "future-proofing" your applications.

XMLInputFactory inputFactory=XMLInputFactory.newInstance();
Table 3-4 XMLInputFactory Properties Property javax.xml.stream.isValidating javax.xml.stream.isCoalescing javax.xml.stream.isNamespaceAware Description Turns on implementation specific validation. (Required) Requires the processor to coalesce adjacent character data. Turns off namespace support. All implementations must support namespaces supporting non-namespace aware documents is optional.

(Required) Requires the processor to replace internal entity javax.xml.stream.isReplacingEntityReferences references with their replacement value and report them as characters or the set of events that describe the entity. javax.xml.stream.isSupportingExternalEntities javax.xml.stream.reporter javax.xml.stream.resolver javax.xml.stream.allocator (Required) Requires the processor to resolve external parsed entities. (Required) Sets and gets the implementation of the XMLReporter (Required) Sets and gets the implementation of the XMLResolver interface (Required) Sets/gets the implementation of the XMLEventAllocator interface

XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();

XMLOutputFactory supports only one property, javax.xml.stream.isRepairingNamespaces.

This property is required, and its purpose is to create default prefixes and associate them with Namespace URIs
Iterator API example:

public static void main(String[] args) throws FileNotFoundException, XMLStreamException { // TODO Auto-generated method stub XMLInputFactory inputFactory=XMLInputFactory.newInstance(); InputStream is=new FileInputStream(new File("C:/Users/Ravi/Desktop/1Z0897/MTOMTestService.xml")); //createXMLStreamReader/eventreader can accept below parameters //inputstream or reader or source or input stream & encoding or systemid & reader or system id & input stream XMLEventReader eventReader = inputFactory.createXMLEventReader(is); while(eventReader.hasNext()){ XMLEvent event=eventReader.nextEvent(); if(event.isStartElement()){ StartElement startElement=event.asStartElement(); System.out.println("start element name="+startElement.getName()); Iterator<Attribute> attr=startElement.getAttributes(); while(attr.hasNext()){ Attribute at=attr.next(); System.out.println("Attribute Name="+at.getName() + "Attribute Value="+at.getValue()); } } } XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); XMLEventWriter eventWriter = outputFactory .createXMLEventWriter(new FileOutputStream("EventWritwrTest.xml")); XMLEventFactory eventFactory = XMLEventFactory.newInstance(); XMLEvent end = eventFactory.createDTD("\n"); // Create and write Start Tag StartDocument startDocument = eventFactory.createStartDocument(); eventWriter.add(startDocument); // XMLEvent tab = eventFactory.createDTD("\t"); // Create Start node StartElement sElement = eventFactory.createStartElement("", "", "StartElement"); // eventWriter.add(tab); eventWriter.add(sElement); // Create Content Characters characters = eventFactory.createCharacters("This is my start element"); eventWriter.add(characters); // Create End node

EndElement eElement = eventFactory.createEndElement("", "", "StartElement"); // eventWriter.add(eElement); eventWriter.add(end); eventWriter.add(eventFactory.createEndDocument()); eventWriter.close(); }

Cursor API Example: XMLInputFactory inputFactory=XMLInputFactory.newInstance(); InputStream is=new FileInputStream(new File("C:/Users/Ravi/Desktop/1Z0897/MTOMTestService.xml")); XMLStreamReader streamReader=inputFactory.createXMLStreamReader(is); while(streamReader.hasNext()){ streamReader.next(); if(streamReader.getEventType() == XMLStreamReader. START_ELEMENT){ System.out.println(streamReader.getLocalName()); } if(streamReader.getEventType()== XMLStreamReader. ATTRIBUTE){ System.out.println("Attribute="+streamReader.getLocalName()); } } XMLOutputFactory factory = XMLOutputFactory.newInstance();

try { XMLStreamWriter writer = factory.createXMLStreamWriter( new FileWriter("CursorAPIforStreamWriter.xml")); writer.writeStartDocument(); writer.writeStartElement("document"); writer.writeStartElement("data"); writer.writeAttribute("name", "value"); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); } catch (XMLStreamException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }

Table 10.1. XML Parser API Feature Summary


Feature API Type StAX Pull, streaming High No Good SAX Push, streaming Medium No Good DOM In memory tree High Yes Varies TrAX XSLT Rule Medium Yes Varies

Ease of Use XPath Capability CPU and Memory Efficiency Forward Only Read XML Write XML Create, Read, Update, Delete

Yes Yes Yes No

Yes Yes No No

No Yes Yes Yes

No Yes Yes No

ivan - 8.5 policy 10.3--mtom saaj Dom

Trax Sax-api Jaxp Jax-rpc uddi 8--security metro project design StaX, Study the concept of Metro project (I got around 3 questions in Metro project) You might expect questions about SSL, Mutal Authentication, XML Encryption, Digital Signatures ..... Study well about WS-Security token profiles

A. XKMS B. XACML C. XML Digital Signature D. HTTP Basic Authentication E. annotations mapped to the JAX-WS runtime WS-Security token profiles is not supported in Metro

@WebParam name If Document.Bare and mode.out/inoutname must be specified When Document.Bareoperation name When RPC and part name not given, it is the part name When header=true, it is the local element name Otherwise idt is argn partName - wsdl:part name targetNamespace- Only used if the operation is document style or the paramater maps to a header. Default is empty namespace if document.wrapped mode -In/OUT/INOUT default is : IN if not a Holder type. INOUT if a Holder type. The OUT and INOUT modes may only be specified for parameter types that conform to the definition of Holder types public static void main(String[] args) { String x = "foo"; Holder<String> h = new Holder(x); getString(h); System.out.println(h.value); } public static void getString(Holder<String> output){ output.value = "Hello World" } header - If true, the parameter is pulled from a message header rather then the message body. Default is false.

@WebResult name if Document.Bare its operation name+Response default is return if RPC its part name partName - its wsdl:part only used if the operation is rpc style or Document.Bare default is : @WebResult.name targetNamespace- Only used if the operation is document style or the return value maps to a header. header - If true, the parameter is in the message header rather than the message body.

To configure http basic over ssl, specify confedential or integral withing transport guarantee element Page 220 of mz quiz answers Web.xml <session-timeout>minutes<session-timeout> Soa based architecturewsdl defines interface that service provides <wsi:Claim confirmsTo="http://ws-i.org/profiles/basic/1.0" xmlns="http://wsi.org/schemas/conformanceClaim/"/> This confirmance claim is used in header blocl to confirm that given message confirms to WS-I basic profile 1.0.This element can not be used with soap:mustUnderstand attribute SOAPHandlers in the order specified in configuration are executed first and later the logicalHandlers specified in the order get executed. SOAP1.1 specifies onli next actor and does not specify any value for ultimateReceiver.Omission of an actor attribute in a header element means taht only the ultimate receiver may handle that header element. SOAP Fault Codes: 4 types: VersionMismatchincorrect soap namespace used Clientnot well formed msg Serverindicates msg could not be process due to some sort of server side failure MustUnderstandA mandataory sopa header can not be processed properly by a given soap internmediary of ultimate receiver.

XML-DSIGprovide guidelines for conveying digital signatures via soap header STS(Security Token Service) A stateful business process needs to be exposed as a web service that is implemented as an EJB based endpoint. A custom mechanism that associates web service messages using correlation-id can be used for maintaining state in web services.The correlationId is used to maintain state. A correlationId unique to the client and partner link initiating the request is also sent. <webservice-description> <webservice-description-name>MyWebService</webservice-description-name> <port-component> <port-component-name>MyWebService</port-component-name> <wsdl-service xmlns:pfx="http://www.comapny.com/MyWebService/"> pfx:DocumentService</wsdl-service> <wsdl-port xmlns:pfx="http://www.company.com/MyWebService/"> pfx:DocumentServiceSOAP</wsdl-port> <enable-mtom>true</enable-mtom> <service-endpoint-interface>com.comapny.MyWebService</service-endpoint-interface> <service-impl-bean> <servlet-link>com.comapny.MyWebServiceSOAPImpl</servlet-link> </service-impl-bean> </port-component> </webservice-description> <webservices> <webservice-description> <webservice-description-name>ExampleService</webservice-description-name> <wsdl-file>META-INF/wsdl/ExampleService.wsdl</wsdl-file> </webservice-description> </webservices> Addressing: <xsd:element name="addressing" type="javaee:addressingType" minOccurs="0" maxOccurs="1"> <xsd:annotation> <xsd:documentation> This specifies the WS-Addressing requirements for a JAX-WS web service. It corresponds to javax.xml.ws.soap.Addressing annotation or its feature javax.xml.ws.soap.AddressingFeature. See the addressingType for more information. </xsd:documentation> </xsd:annotation>

</xsd:element> webservices based on servlets are session aware and webservices based on ejb's arent. webservices based on ejb's can use declarative authorization, and servlets cant. ejb's have better support for concurrent service calls (there will be ony 1 servlet to handle the service calls and there can be multiple instances of the ejb in a pool to handle the service calls) 4.3.10 HTTP Cookies The HTTP State Management Mechanism ("Cookies") allows the creation of stateful sessions between Web browsers and servers. Being designed for hypertext browsing, Cookies do not have well-defined semantics for Web services, and, because they are external to the SOAP Envelope, are not accommodated by either SOAP 1.1 or WSDL 1.1. However, there are situations where it may be necessary to use Cookies; e.g., for load balancing between servers, or for integration with legacy systems that use Cookies. For these reasons, the Profile limits the ways in which Cookies can be used, without completely disallowing them.

D conform to RFC2965. R1121 An INSTANCE SHOULD NOT require consumer support for Cookies in order to function correctly.

The Profile recommends that cookies not be required by instances for proper operation; they should be a hint, to be used for optimization, without materially affecting the execution of the Web service. However, they may be required in legacy integration and other exceptional use cases, so requiring them does not make an instance non-conformant. While Cookies thus may have meaning to the instance, they should not be used as an out-of-bound data channel between the instance and the consumer. Therefore, interpretation of Cookies is not allowed at all by the consumer - it is required to treat them as opaque (i.e., have no meaning to the consumer).

The main problem is that the SOAP envelope was designed to travel over intermediate nodes, sometimes travelling over multiple transports. What exactly are you going to do with your HTTP session ID (and session data) when the envelope arrives at the HTTP server and the server then wants to sent the envelope on to the next node over JMS? In fact the HTTP server may not know enough about what is going on to maintain a meaningful session. That is why SOAP web services are supposed to use correlation identifiers inside the SOAP envelope rather than a session ID in an

HTTP header. Ideally a web service should be stateless because storage of client state impairs scalabilty of the web service. Correlation identifiers are typically used to correlate messages that relate to the same "long running business transaction". The endpoint address for EJB-based JAX-WS Web Service can be specified in the Geronimo-specific deployment descriptor using the <web-service-address> entry as show below:

<openejb-jar xmlns="http://www.openejb.org/xml/ns/openejb-jar-2.1"> <enterprise-beans> <session> <ejb-name>MyEjb</ejb-name> <web-service-address>/MyContext/MyEjb</web-service-address> </session> </enterprise-beans> </openejb-jar> when jax-rs deployed using servlet based endpoint, ServletConfig, HttpServletRequest,HttpServletResponse,ServletContext are available using @Context reference to service implementation beab specified using <service-impl-bean> in webservices.xml is either servlet-link or ejb-link depending whether endpoint is jax-rpc or ejb service endpoint. This link associates the web service port to the actual endpoint implementation defined in either web.xml or ejb-jar.xml jax-rs supports conditional GET and PUT requests. GET can return 304not modifies since last time PUT can return 412if representation is modified since last request. By Default, JAX-RS root resources are managed in Request scope. CDI managed beans annotated with @RequestScoped or @ApplicationScoped can be converted to JAX-RS resource classes.Class should have non private with no parameter constructor. strong authentication is any form of authentication in which the verification is accomplished without transmission of password. jax-ws specification supports following session management mechanism: Session APIs definition of a session interface and methods to obtain the session interface and initiate sessions for handlers and service endpoint implementation. HTTP Based sesion. The session managenebt must support HTTP Cookie and URL rewritting. SOAP Based session. The session management mechanism must support SOAP based session information.

AJAX call to rest ws

Configuring Handler for service whose name begins with EPractizeLabs.

Context Types An instance ofProviders can be injected into a class field or method parameter using the @Context annotation. An instance of SecurityContext can be injected into a class field or method parameter using the@Context annotation. The methods of SecurityContext provide access to the current user principal, information about roles assumed by the requester, whether the request arrived over a secure channel and the authentication scheme used. An instance ofRequest can be injected into a class field or method parameter using the @Context annotation. @PUT public Response updateFoo(@Context Request request, Foo foo) { An instance of HttpHeaders can be injected into a class field or method parameter using the@Context annotation. public String listHeaderNames(@Context HttpHeaders headers) { An instance of UriInfo can be injected into a class field or method parameter using the @Context annotation. public String listQueryParamNames(@Context UriInfo info)

The instance of the application-supplied Application subclass can be injected into a class field or method parameter using the @Context annotation. Access to the Application subclass instance allows configuration information to be centralized in that class. Note that this cannot be injected into the Application subclass itself since this would create a circular dependency.

Stateful JAX-WS http://weblogs.java.net/blog/kohsuke/archive/2006/10/stateful_web_se.html

The JAX-WS RI has a vendor extension that allows developers to bring back object state to the web service world. Normally, the JAX-WS RI only creates one instance of a service class, and have it serve all incoming requests concurrently. This makes it essentially impossible to use instance fields of the service class for any meaningful purpose. Because of this, people end up coding like C, in anti-OO fashion. Either that or you end up with writing boiler-plate code to dispatch a request to the right instance of your real domain object. The stateful web service support in the JAX-WS RI resolves this problem by having the JAXWS RI maintain multiple instances of a service. By using WS-Addressing behind the scene, it provides a standard-based on-the-wire protocol and easy-to-use programming model. A stateful web service class does not need to have a default constructor. In fact, most of the time you want to define a constructor that takes some arguments, so that each instance carries certain state
@Stateful @WebService @Addressing class BankAccount { protected final int id; private int balance; Account(int id) { this.id = id; } @WebMethod public synchronized void deposit(int amount) { balance+=amount; } // either via a public static field public static StatefulWebServiceManager<BankAccount> manager; // ... or via a public static method (the method name could be anything)

public static void setManager(StatefulWebServiceManager<BankAccount> manager) { ... } }

Your class would also have StatefulWebServiceManager static field or method, where the JAX-WS RI injects an instance. You'll talk with the manager to get objects exported.

The following normal stateless service shows how you can send a "remote reference" to a BankAccount object to the client:
@WebService class Bank { // this is ordinary stateless service @WebMethod public synchronized W3CEndpointReference login(int accountId, int pin) { if(!checkPin(pin)) throw new AuthenticationFailedException("invalid pin"); BankAccount acc = new BankAccount(accountId); return BankAccount.manager.export(acc); } }

The key here is the export operation. It takes a reference of a BankAccount object, then creates an "endpoint reference" object, which is really a remote reference to this specific bank account. In this example, it then sends it back to the client. The client code can look like this:
BankAccount account1 = accountService.getPort(bankServicePort.getAccount(1), Account.class); BankAccount account2 = accountService.getPort(bankServicePort.getAccount(2), Account.class); account1.deposit(100); account2.deposit(-100);

HttpSessionScope http://weblogs.java.net/blog/kohsuke/archive/2006/10/bringing_state.html @HttpSessionScope @WebService public class Hello { int counter = 0; public int getCounter() { return counter++; } }

The @com.sun.xml.ws.developer.servlet.HttpSessionScope annotation tells the JAX-WS RI to create one instance of Hello per each HTTP session. No need to mess with WebServiceContext, nor with HttpSession manually.

@Consumes & @Produces Application classes can declare @Consumes & @Produces for supported media types.

Resource methods too Entity Provider too

Handler Element

Wsdl namespace: http://schemas.xmlsoap.org/wsdl/

Soap namespace: http://schemas.xmlsoap.org/wsdl/soap/ Notification and Solicit-Response types must not be used as they are not defined in wsdl1.1 and no bindings have been defined for them as well. Digital Signatures:

To implement both Restful and SOAP Web Services using JAX-WS, below exceptions can be used: javax.xml.ws.soap.SOAPFaultException javax.xml.ws.HTTPException. SOAPFault exception represents a SOAP 1.1 or 1.2 fault. HTTPException represents a XML/HTTP fault

WS-I Basic profile 1.0

__________________________________________________________________________________________________ Restful Services are stateless by definition. SOAP services are self documenting via wsdl. SAX is a push API whereas STAX is pull.

Pull Parsing Versus Push Parsing


Streaming pull parsing refers to a programming model in which a client application calls methods on an XML parsing library when it needs to interact with an XML infoset--that is, the client only gets (pulls) XML data when it explicitly asks for it. Streaming push parsing refers to a programming model in which an XML parser sends (pushes) XML data to the client as the parser encounters elements in an XML infoset-that is, the parser sends the data whether or not the client is ready to use it at that time. Pull parsing provides several advantages over push parsing when working with XML streams:
With pull parsing, the client controls the application thread, and can call methods on the parser when needed. By contrast, with push processing, the parser controls the application thread, and the client can only accept invocations from the parser. Pull parsing libraries can be much smaller and the client code to interact with those libraries much simpler than with push libraries, even for more complex documents. Pull clients can read multiple documents at one time with a single thread. A StAX pull parser can filter XML documents such that elements unnecessary to the client can be ignored, and it can support XML views of non-XML data.

Stax allows client to start, pause, resume the parsing process . XML Parser API Feature Summary Feature API Type Ease of Use XPath Capability CPU and Memory Efficiency Forward Only Read XML Write XML High No Good Yes Yes Yes StAX SAX Medium No Good Yes Yes No No High Yes Varies No Yes Yes Yes DOM TrAX Medium Yes Varies No Yes Yes No Pull, streaming Push, streaming In memory tree XSLT Rule

Create, Read, Update, Delete No

The NetBeans IDE offers an easy way to enable secure conversations in Metro for a web service. One of the ways it does this is by providing a set of security profiles that specify the mechanism to be used in securing conversations. The profiles are:

Username Authentication with Symmetric Keys Mutual Certificates Security Transport Security (SSL) Message Authentication over SSL SAML Authorization over SSL Endorsing Certificate SAML Sender Vouches with Certificates SAML Holder of Key STS Issued Token STS Issued Token with Service Certificate STS Issued Endorsing Token STS Issued Supporting Token

Four of these profiles secure web services with STS-issued tokens:


STS Issued Token STS Issued Token with Service Certificate STS Issued Endorsing Token STS Issued Supporting Token

WS-Trust in Metro Here is a summary of the WS-Trust support in Metro:

Supports token issuance and token validation protocols.

Supports the STS framework. Supports building an STS as an independent web service. Supports client and service authentication and security with issued tokens from an STS within the general framework of WS-Security and WS-SecurityPolicy. Provides a general framework for building an STS as a web service for issuing security tokens. Supports authentication and secure communication between a client and an STS in the same way as for a regular web service. Supports issuing SAML 1.0, SAML 1.1 and SAML2.0 tokens, by default. Supports the issuing of symmetric proof keys, public proof keys, and no proof keys. Can be extended to support the issuing of other types of tokens. Allows for plugging in additional authorization mechanisms that control the issuing of tokens according to the user's identity and the targeted service. Allows for plugging in user mappings that control the user identity/attributes carried in the SAML token issued by an STS for different services.

In Metro, you use <sp:IssuedToken> policy assertions in the service's WSDL to enable security with an STS. No run-time API is required. In essence, WS-Trust specifies the following:

A general framework for token exchanges. A model for brokering trust in web services. A Security Token Service (STS) framework. Protocols for issuing, renewing, validating, and canceling security tokens.

1. 2. 3. 4. 5. 6.

Support for Policy-Alternatives (Preliminary) Support for JAAS KeyStoreLoginModule High Availability of Nonce Cache (Support Load balancing & High Availability) High Availability of SecureConversation Sessions Support for Signing Tokens not in message via STR-Transform WS-I BSP 1.1(Basic Security profile) and RSP 1.0(Reliable secure profile) Compliance 7. Support for RSA-SHA256 and higher bit SignatureAlgorithms 8. WebServices Interoperability with other Oracle Products(SAML, X509, UserNameToken and Policy alternatives are tested)
9. Metro comes with support for both WS-RM 1.0 and WS-RM 1.1.

Configuring the HTTP Binding Component for HTTP Get Interactions


To configure the HTTP Binding Component to function for HTTP GET interactions, the WSDL file of the service to which the binding component is acting as proxy, needs to use the following HTTP binding language elements defined in the WSDL 1.1 Specification:

An <http:binding> element indicating that a WSDL binding uses HTTP GET. An <http:address> element representing the address of the port.

An <http:operation> element representing a relative address for each operation, that is relative to the <http:address> defined by the port. An <http:urlEncoded> and <http:urlReplacement> element to indicate how all of the message parts of a request are encoded and made a
<http:binding verb="POST"/> <http:operation location="Submit"> <http:address location="http://localhost/MyService/MyPort">

The full HTTP request URI is: http://localhost/MyService/MyPort/Submit <wsdl:binding name="MyBinding" type="MyPortType"> <http:binding verb="GET"/> <wsdl:operation name="MyOperation"> <wsdl:input> <http:urlEncoded/> </wsdl:input> </wsdl:operation> </wsdl:binding>

The <http:urlReplacement/> element:


Indicates that all message parts that make up the input message are encoded into the request URI using the replacement algorithm detailed in the WSDL 1.1 Specification. Must be specified as a subordinate element of a <wsdl:input/> Requires a location attribute that specifies the base URI for the operation.
<wsd:message name="MyMessage"> <wsdl:part name="partA" type="xsd:string"/> <wsdl:part name="partB" type="xsd:string"/> </wsdl:message>

wsdl:binding name="MyBinding" type="MyPortType"> <http:binding verb="GET"/> <wsdl:operation name="MyOperation/(partA)/subcategory/(partB)"> <wsdl:input> <http:urlReplacement/> </wsdl:input> </wsdl:operation> </wsdl:binding>

ServletEndPointContext.isUserinRole()--The only way a servlet based endpoint can provide role based acces mapped asynchronous methods donot throw service specific exceptions dirtectly, instead they throw java.util.concurrent.ExecutionException when Response.get is called. In JAX-RS Conversion between a java object and an entity body is the responsiblity of an entity provider

Das könnte Ihnen auch gefallen