Professional Documents
Culture Documents
Workshop
Agenda
What is XML
XML stands for eXtensible Markup Language.
XML was designed to transport and store data, as HTML was designed to display data.
XML tags are not predefined. You must define your own tags.
XML does not do anything, XML its just a framework.
XML is the most common tool for data transmissions between all sorts of applications.
<?xml version="1.0" encoding="ISO-8859-15"?>
<class_list>
<student>
<name>Robert</name>
<grade>A+</grade>
</student>
<student>
<name>Lenard</name>
<grade>A-</grade>
</student>
</class_list>
3
The next line describes the root element of the document (like saying: "this document is a note").
The next 4 lines describe 4 child elements of the root (to, from, heading, and body).
And finally the last line defines the end of the root element
<?xml version="1.0" encoding="ISO-88591?>
<note>
<to>Sam</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
<p>This is a paragraph</p>
XML tags are case sensitive, opening and closing tags must be written with the same case
<Message>This is incorrect</message>
<message>This is correct</message>
<note date="12/11/2007">
Names cannot start with the letters xml (or XML, or Xml, etc)
Names cannot contain spaces
XML Namespaces
In XML, element names are defined by the developer. This often results in a conflict when trying
to mix XML documents from different XML applications.
<table>
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
<table>
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
XML Namespaces
When using prefixes in XML, a so-called namespace for the prefix must be defined.
The namespace is defined by the xmlns attribute in the start tag of an element.
The namespace declaration has the following syntax. xmlns:prefix="URI".
Namespaces can be declared in the elements where they are used or in the XML root element.
<root xmlns:h="http://www.w3.org/TR/html4/"
xmlns:f="http://www.w3schools.com/furniture">
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
9
XML Namespaces
A Uniform Resource Identifier (URI) is a string of characters which identifies an Internet Resource.
Defining a default namespace for an element saves us from using prefixes in all the child
elements.
<table
xmlns="http://www.w3.org/TR/html4/">
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
This XML carries information about a piece of furniture:
<table xmlns="http://www.w3schools.com/furniture">
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>
10
Quiz time
Time to test the XML knowledge
11
XML Schema
An XML Schema describes the structure of an XML document.
The XML Schema language is also referred to as XML Schema Definition (XSD).
<?xml version="1.0"?>
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
12
XSD features
An XML Schema:
13
XSD Reference
This XML document has a reference to an XML Schema:
<?xml version="1.0"?>
<note
xmlns="http://www.w3schools.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3schools.com note.xsd">
<to>Sam</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
Last fragments is the schemaLocation attribute The first value is the namespace to use. The second value
is the location of the XML schema to use for that namespace:
xsi:schemaLocation="http://www.w3schools.com note.xsd
14
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3schools.com"
xmlns="http://www.w3schools.com"
elementFormDefault="qualified">
...
</xs:schema>
15
The text can be of many different types. It can be one of the types included in the XML Schema
definition (boolean, string, date, etc.), or it can be a custom type that you can define yourself.
Where xxx is the name of the element and yyy is the data type of the element.
XML Schema has a lot of built-in data types. The most common types are: (xs:string, xs:decimal,
xs:integer, xs:boolean, xs:date, xs:time)
<xs:element name="lastname" type="xs:string"/>
<xs:element name="age" type="xs:integer"/>
<xs:element name="dateborn" type="xs:date"/>
17
A fixed value is also automatically assigned to the element, and you cannot specify another value.
In the following example the fixed value is "red":
<xs:element name="color" type="xs:string" fixed="red"/>
18
XSD Attributes
All attributes are declared as simple types.
Simple elements cannot have attributes. If an element has attributes, it is considered to be of a
complex type.
Where xxx is the name of the attribute and yyy is the data type of the attribute.
XML Schema has a lot of built-in data types. The most common types are: (xs:string, xs:decimal,
xs:integer, xs:boolean, xs:date, xs:time)
Here is an example:
<xs:attribute name="lang" type="xs:string"/>
19
A fixed value is also automatically assigned to the attribute, and you cannot specify another value.
In the following example the fixed value is "EN":
<xs:attribute name="lang" type="xs:string" fixed="EN"/>
Attributes are optional by default. To specify that the attribute is required, use the "use" attribute:
<xs:attribute name="lang" type="xs:string" use="required"/>
When an XML element or attribute has a data type defined, it puts restrictions on the element's
or attribute's content.
If an XML element is of type "xs:date" and contains a string like "Hello World", the element will
not validate.
20
XSD Restrictions/Facets
With XML Schemas, you can also add your own restrictions to your XML elements and attributes.
These restrictions are called facet.
The following example defines an element called "age" with a restriction. The value of age cannot
be lower than 0 or greater than 120:
<xs:element name="age">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:minInclusive value="0"/>
<xs:maxInclusive value="120"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
21
XSD Restrictions/Facets
To limit the content of an XML element to a set of acceptable values, we would use the
enumeration constraint.
<xs:element name="car">
<xs:element name="car"
<xs:simpleType>
type="carType"/>
<xs:restriction
<xs:simpleType
base="xs:string">
name="carType">
<xs:enumeration
<xs:restriction
value="Audi"/>
base="xs:string">
<xs:enumeration
<xs:enumeration
value="Golf"/>
value="Audi"/>
<xs:enumeration
<xs:enumeration
value="BMW"/>
value="Golf"/>
</xs:restriction>
<xs:enumeration
In</xs:simpleType>
right side case the type "carType" can be used byvalue="BMW"/>
other elements because it is not a part of the
</xs:element>
</xs:restriction>
"car" element, its a new custom type that weve created.
</xs:simpleType>
22
The next example defines an element called "initials" with a restriction. The only acceptable value
is THREE of the UPPERCASE letters from a to z:
<xs:restriction base="xs:string">
<xs:pattern value="[A-Z][A-Z][A-Z]"/>
</xs:restriction>
The next example also defines an element called "initials" with a restriction. The only acceptable
value is THREE of the LOWERCASE OR UPPERCASE letters from a to z:
<xs:restriction base="xs:string">
<xs:pattern value="[a-zA-Z][a-zA-Z][a-zA-Z]"/>
</xs:restriction>
23
The next example defines an element called digits" with a restriction. The only acceptable value
is FIVE digits in a sequence, and each digit must be in a range from 0 to 9:
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9][0-9][0-9][0-9][0-9]"/>
</xs:restriction>
The example below defines an element called word" with a restriction. The acceptable value is
zero or more occurrences of lowercase letters from a to z:
<xs:restriction base="xs:string">
<xs:pattern value="([a-z])*"/>
</xs:restriction>
24
case letter:
<xs:restriction base="xs:string">
<xs:pattern value="([a-z][A-Z])+"/>
</xs:restriction>
The next example defines an element called "gender" with a restriction. The only acceptable value
is male OR female:
<xs:restriction base="xs:string">
<xs:pattern value="male|female"/>
</xs:restriction>
The next example defines an element called "password" with a restriction. There must be exactly
eight characters in a row and those characters must be lowercase or uppercase letters from a to z,
or a number from 0 to 9:
<xs:restriction base="xs:string">
<xs:pattern value="[a-zA-Z0-9]{8}"/>
</xs:restriction>
25
The whiteSpace constraint is set to "replace", which means that the XML processor WILL REPLACE
all white space characters (line feeds, tabs, spaces, and carriage returns) with spaces:
<xs:restriction base="xs:string">
<xs:whiteSpace value="replace"/>
</xs:restriction>
The whiteSpace constraint is set to "collapse", which means that the XML processor WILL
REMOVE all white space characters (line feeds, tabs, spaces, carriage returns are replaced with
spaces, leading and trailing spaces are removed, and multiple spaces are reduced to a single
space)
<xs:restriction base="xs:string">
<xs:whiteSpace value=collapse"/>
</xs:restriction>
26
This example defines an element called "password" with a restriction. The value must be exactly
eight characters:
<xs:restriction base="xs:string">
<xs:length value="8"/>
</xs:restriction>
This example defines another element called "password" with a restriction. The value must be
minimum five characters and maximum eight characters:
<xs:restriction base="xs:string">
<xs:minLength value="5"/>
<xs:maxLength value="8"/>
</xs:restriction>
There are also other constrain types for Datatypes like: fractionDigits, totalDigits, maxExclusive,
maxInclusive and so on.
27
empty elements
elements that contain only other elements
elements that contain only text
elements that contain both other elements and text
28
A complex XML element, "description", which contains both elements and text:
<description>
It happened on <date lang="norwegian">03.03.99</date> ....
</description>
29
If you use the method described above, several elements can refer to the same complex type, like this:
<xs:element name="employee"
type="personinfo"/>
<xs:element name="student"
type="personinfo"/>
<xs:element name="member"
type="personinfo"/>
30
<xs:complexType name="fullpersoninfo">
<xs:complexContent>
<xs:extension base="personinfo">
<xs:sequence>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
31
The "product" element above has no content at all. To define a type with no content, we must
define a type that allows elements in its content, but we do not actually declare any elements, like
this:
<xs:element name="product">
<xs:complexType>
<xs:complexContent>
<xs:restriction base="xs:integer">
<xs:attribute name="prodid"
type="xs:positiveInteger"/>
</xs:restriction>
</xs:complexContent>
</xs:complexType>
</xs:element>
In the example above, we define a complex type with a complex content. The complexContent
element signals that we intend to restrict or extend the content model of a complex type, and the
restriction of integer declares one attribute but does not introduce any element content.
32
Or you can give the complexType element a name, and let the "product" element have a type
attribute that refers to the name of the complexType (if you use this method, several elements
can refer to the same complex type):
<xs:element name="product" type="prodtype"/>
<xs:complexType name="prodtype">
<xs:attribute name="prodid" type="xs:positiveInteger"/>
</xs:complexType>
33
Notice the <xs:sequence> tag. It means that the elements defined ("firstname" and "lastname") must
appear in that order inside a "person" element.
Or you can give the complexType element a name, and let the "person" element have a type attribute
that refers to the name of the complexType (if you use this method, several elements can refer to the
same complex type):
34
The following example declares a complexType, "shoesize". The content is defined as an integer
value, and the "shoesize" element also contains an attribute named "country":
<xs:element name="shoesize">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:integer">
<xs:attribute name="country" type="xs:string" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
35
The following schema declares the "letter" element that contain attributes, elements, and text:
<xs:element name="letter">
<xs:complexType mixed="true">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="orderid" type="xs:positiveInteger"/>
<xs:element name="shipdate" type="xs:date"/>
</xs:sequence>
</xs:complexType>
</xs:element>
We could also give the complexType element a name, and let the "letter" element have a type
attribute that refers to the name of the complexType (if you use this method, several elements
can refer to the same complex type):
<xs:element name="letter" type="lettertype"/>
<xs:complexType name="lettertype" mixed="true">
..
..
36
XSD Indicators
We can control HOW elements are to be used in documents with indicators.
There are seven indicators:
Order indicators:
All
Choice
Sequence
Occurrence indicators:
maxOccurs
minOccurs
Group indicators:
Group name
attributeGroup name
37
When using the <all> indicator you can set the <minOccurs> indicator to 0 or 1 and the
<maxOccurs> indicator can only be set to 1 (the <minOccurs> and <maxOccurs> are described
later).
38
The <sequence> indicator specifies that the child elements must appear in a specific order:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
39
The <minOccurs> indicator specifies the minimum number of times an element can occur:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string"
maxOccurs="10" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
40
Attribute groups are defined with the attributeGroup declaration, like this:
<xs:attributeGroup name="groupname">
...
</xs:attributeGroup>
41
The following example is a fragment from an XML schema called "family.xsd". It shows a
declaration for the "person" element. By using the <any> element we can extend (after
<lastname>) the content of "person" with any element:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
<xs:any minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
The <any> and <anyAttribute> elements are used to make EXTENSIBLE documents! They allow
documents to contain additional elements that are not declared in the main XML schema.
42
The following example is a fragment from an XML schema called "family.xsd". It shows a
declaration for the "person" element. By using the <anyAttribute> element we can add any
number of attributes to the "person" element
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
<xs:anyAttribute/>
</xs:complexType>
</xs:element>
43
String data types are used for values that contains character strings.
The string data type can contain characters, line feeds, carriage returns, and tab characters.
The following is an example of a string declaration in a schema:
<xs:element name="customer" type="xs:string"/>
The normalizedString data type also contains characters, but the XML processor will remove line
feeds, carriage returns, and tab characters.
The token data type also contains characters, but the XML processor will remove line feeds,
carriage returns, tabs, leading and trailing spaces, and multiple spaces.
<xs:element name="customer" type="xs:normalizedString"/>
<xs:element name="customer" type="xs:token"/>
44
Other data types below derive from the String data type.
enumeration
length
maxLength
minLength
To specify a time zone, you can either enter a date in UTC time by adding a "Z" behind the date or
you can specify an offset from the UTC time by adding a positive or negative time behind the date
46
enumeration
maxExclusive
maxInclusive
minExclusive
minInclusive
pattern
whiteSpace
47
The decimal data type is used to specify a numeric value (maximum of 18 digits).
<xs:element name="prize" type="xs:decimal"/>
The integer data type is used to specify a numeric value without a fractional component.
<xs:element name="prize" type="xs:integer"/>
Data types below derive from the Decimal data type and can be used:
Byte
Int
Long
negativeInteger, nonNegativeInteger, nonPositiveInteger, positiveInteger
Short
unsignedLong, unsignedInt, unsignedShort, unsignedByte
Binary data types are used to express binary-formatted data: base64Binary or hexBinary.
<xs:element name="blobsrc" type="xs:hexBinary"/>
pattern
whiteSpace
49
One of the best applications for the XSD schemas is Business rules
Define the entities upon which you write business rules
Before you write business rules, you must first set up the model on which they rely. You define this model as a
business object model (BOM).
USA
50
51
Every BOM element used in a rule must have a corresponding XOM implementation, but it does not have to be a simple
one-to-one mapping. You can create more complex BOM to XOM mappings, such as combining information from multiple
XOM properties into one BOM element.
You can implement the XOM as a Java object model or as an XML schema (XSD).
JAVA:
Comment Class
Comment is a public interface that extends javax.xml.bind.Element.
Content in instantiations of this class binds to the XML schema element named comment.
The getValue() and setValue() methods are used to get and set strings representing XML comment elements in the Java
content tree.
Items Class
The class provides public interfaces for Items and ItemType.
Content in instantiations of this class binds to the XML ComplexTypes Items and its child element ItemType.
Item provides the getItem() method.
ItemType provides setter and getter methods for each child object: PartNum, Comment, USPrice, ProductName, ShipDate,
Quantity
52
PurchaseOrder Class
PurchaseOrder is a public interface that extends javax.xml.bind.Element and
PurchaseOrderType.
Content in instantiations of this class binds to the XML schema element named
purchaseOrder.
PurchaseOrderType Class
Content in instantiations of this class binds to the XML schema child element named
PurchaseOrderType.
PurchaseOrderType is a public interface that provides setter and getter methods for each child
object: Items, OrderDate, Comment, BillTo, ShipTo
USAddress Class
Content in instantiations of this class binds to the XML schema element named USAddress.
USAddress is a public interface that provides setter and getter methods for each child object:
State, Zip, Country, City, Street, Name
53
The mapping of business objects to schema objects with their according restrictions
Business rule: The maximum quantity of ordered items in a simple order should be an integer value not greater
than 100.
maps to
<xsd:element name="quantity">
<xsd:simpleType>
<xsd:restriction base="xsd:positiveInteger">
<xsd:maxExclusive value="100"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
Business rule: The stock identifier for the product should contain only alphanumeric values and have a form of 3
digits 2 upper case letters.
maps to
<xsd:simpleType name="SKU">
<xsd:restriction base="xsd:string">
<xsd:pattern value="\d{3}-[A-Z]{2}"/>
</xsd:restriction>
</xsd:simpleType>
54
55
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
<xsd:element name="comment" type="xsd:string"/>
<xsd:complexType name="PurchaseOrderType">
<xsd:sequence>
<xsd:element name="shipTo" type="USAddress"/>
<xsd:element name="billTo" type="USAddress"/>
<xsd:element ref="comment" minOccurs="0"/>
<xsd:element name="items" type="Items"/>
</xsd:sequence>
<xsd:attribute name="orderDate" type="xsd:date"/>
</xsd:complexType>
<xsd:complexType name="USAddress">
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="street" type="xsd:string"/>
<xsd:element name="city" type="xsd:string"/>
<xsd:element name="state" type="xsd:string"/>
<xsd:element name="zip" type="xsd:decimal"/>
</xsd:sequence>
<xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/>
</xsd:complexType>
56
57
58
END of PART 1
59
A Web Service is a method of communication between two electronic devices over the World Wide Web.
A Web Service is a software function provided at a network address over the web or the cloud, it is a service
that is "always on.
A Web Service is a XML-based information exchange system that use the Internet for direct application-toapplication interaction.
60
61
What is SOAP
It is a simple XML-based protocol to let applications exchange information over HTTP.
SOAP is a protocol for accessing a Web Service.
SOAP stands for Simple Object Access Protocol
SOAP is platform independent
SOAP is language independent
62
63
64
65
The xmlns:soap namespace in the example above it should always have the value of:
"http://www.w3.org/2001/12/soap-envelope". The namespace defines the Envelope as a SOAP
Envelope.
The encodingStyle attribute is used to define the data types used in the document. This attribute
may appear on any SOAP element, and applies to the element's contents and all child elements.
66
If the Header element is present, it must be the first child element of the Envelope element.
<soap:Header>
<m:Trans xmlns:m="http://www.w3schools.com/transaction/"
soap:mustUnderstand="1">234
</m:Trans>
</soap:Header>
The example above contains a header with a "Trans" element, a "mustUnderstand" attribute
with a value of 1, and a value of 234.
SOAP defines three attributes in the default namespace. These attributes are: mustUnderstand,
actor, and encodingStyle.
The attributes defined in the SOAP Header defines how a recipient should process the SOAP
message.
67
If you add mustUnderstand="1" to a child element of the Header element it indicates that the
receiver processing the Header must recognize the element. If the receiver does not recognize
the element it will fail when processing the Header.
A SOAP message may travel from a sender to a receiver by passing different endpoints along the
message path. However, not all parts of a SOAP message may be intended for the ultimate
endpoint, instead, it may be intended for one or more of the endpoints on the message path.
The SOAP actor attribute is used to address the Header element to a specific endpoint.
The encodingStyle attribute is used to define the data types used in the document. This attribute
may appear on any SOAP element, and it will apply to that element's contents and all child
elements.
69
Description
<faultcode>
<faultstring>
<faultactor>
<detail>
70
Error
Description
Client
Server
71
SOAP Example
In the example below, a GetStockPrice request is sent to a server. The request has a StockName
parameter, and a Price parameter that will be returned in the response. The namespace for the
function is defined in http://www.example.org/stock
A SOAP Request:
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body xmlns:m="http://www.example.org/stock">
<m:GetStockPrice>
<m:StockName>IBM</m:StockName>
</m:GetStockPrice>
</soap:Body>
</soap:Envelope>
72
SOAP Example
A SOAP Response:
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body xmlns:m="http://www.example.org/stock">
<m:GetStockPriceResponse>
<m:Price>34.5</m:Price>
</m:GetStockPriceResponse>
</soap:Body>
</soap:Envelope>
73
What is WSDL
WSDL stands for Web Services Description Language
WSDL is an XML based protocol for information exchange in decentralized and distributed
environments.
74
WSDL Elements
WSDL breaks down Web services into three specific, identifiable elements that can be combined
or reused once defined.
Following are the elements of WSDL document. Within these elements are further sub elements
or parts:
Definitions
Data Types
Message
Operation
Port Type
Binding
Port
Service
75
WSDL example
<definitions>
<types>
definition of types........
</types>
<message>
definition of a message....
</message>
<portType>
<operation>
definition of a operation.......
</operation>
</portType>
<binding>
definition of a binding....
</binding>
<service>
definition of a service....
</service>
</definitions>
76
WSDL example
<definitions name="HelloService"
targetNamespace="http://www.examples.com/wsdl/HelloService.wsdl"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<message name="SayHelloRequest">
<part name="firstName" type="xsd:string"/>
</message>
<message name="SayHelloResponse">
<part name="greeting" type="xsd:string"/>
</message>
<portType name="Hello_PortType">
<operation name="sayHello">
<input message="tns:SayHelloRequest"/>
<output message="tns:SayHelloResponse"/>
</operation>
</portType>
77
WSDL example
<binding name="Hello_Binding" type="tns:Hello_PortType">
<soap:binding style="rpc"
transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="sayHello">
<soap:operation soapAction="sayHello"/>
<input>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:helloservice"
use="encoded"/>
</input>
<output>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:helloservice"
use="encoded"/>
</output>
</operation>
</binding>
<service name="Hello_Service">
<documentation>WSDL File for HelloService</documentation>
<port binding="tns:Hello_Binding" name="Hello_Port">
<soap:address
location="http://www.examples.com/SayHello/">
</port>
</service>
</definitions>
78
Here is the example piece of code from last session which uses definition element.
<definitions name="HelloService"
targetNamespace="http://www.examples.com/wsdl/HelloService.
wsdl"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
................................................
</definitions>
The namespace specification does not require that the document actually exist at the given
location. The important point is that you specify a value that is unique, different from all other
namespaces that are defined
79
Each message contains zero or more <part> parameters, one for each parameter of the Web
Service's function.
Each <part> parameter associates with a concrete type defined in the <types> container
element.
<message name="SayHelloRequest">
<part name="firstName"
type="xsd:string"/>
</message>
<message name="SayHelloResponse">
<part name="greeting"
type="xsd:string"/>
</message>
81
For example, a <portType> can combine one request and one response message into a single
request/response operation. This is most commonly used in SOAP services. A portType can
define multiple operations.
<portType name="Hello_PortType">
<operation name="sayHello">
<input
message="tns:SayHelloRequest"/>
<output
message="tns:SayHelloResponse"/>
</operation>
</portType>
82
83
The bindings can be made available via multiple transports, including HTTP GET, HTTP POST, or
SOAP.
The bindings provide concrete information on what protocol is being used to transfer
portType operations
The binding element has two attributes - the name attribute and the type attribute.
<binding name="Hello_Binding" type="tns:Hello_PortType">
84
85
86
The name attribute provides a unique name among all services defined within in the enclosing
WSDL document.
87
WSDL Summary
WSDL is an XML format for describing network services as a set of endpoints operating on
messages containing either document-oriented or procedure-oriented information.
88
What is JSON
JSON stands for JavaScript Object Notation
JSON is a text format that is completely language independent but uses conventions that are
familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl,
Python, and many others.
89
JSON Structure
JSON is built on two structures:
An ordered list of values. In most languages, this is realized as an array, vector, list, or
sequence.
An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends
with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated
by , (comma).
{ "firstName":"John" , "lastName":"Doe"
},
90
JSON Structure
An array is an ordered collection of values. An array begins with [ (left bracket) and ends
with ] (right bracket). Values are separated by , (comma).
A value can be a string in double quotes, or a number, or true or false or null, or an object or
an array. These structures can be nested.
{
"employees": [
{ "firstName":"John" , "lastName":"Doe"
},
{ "firstName":"Anna" ,
"lastName":"Smith" },
{ "firstName":"Peter" ,
"lastName":"Jones" }
]
}
91
JSON vs XML
Below is a direct comparison between JSON and XML structures.
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
<employees>
<firstName>John</firstName>
<lastName>Doe</lastName>
</employees>
<employees>
<firstName>Anna</firstName>
<lastName>Smith</lastName>
</employees>
<employees>
<firstName>Peter</firstName>
<lastName>Jones</lastName>
</employees>
92
JSON vs XML
Simple corresponding conversion patterns between XML and JSON.
Patter
n
XML
JSON
Access
<tag/>
"tag": null
o.tag
<tag>text</tag>
"tag": "text"
o.tag
"tag":{"@name": "value"}
o.tag["@name"
]
<tag
name="value">text</tag>
o.tag["@name"
] o.tag["#text"]
<tag> <a>text</a>
<b>text</b> </tag>
o.tag.a o.tag.b
<tag> <a>text</a>
<a>text</a> </tag>
o.tag.a[0]
o.tag.a[1]
o.tag["#text"]
o.tag.a
93
What is REST
94
REST uses HTTP uniform interface (POST, GET, PUT, DELETE) for all four CRUD
(Create/Read/Update/Delete) operations
Host: myserver.com
Accept: application/xml
A REST Web Service can be very intuitive (easy to guess, self-documenting) when
addressing resources by exposing directory structure-like URIs
95
Output
Host: myserver.com
Content-Type:application/xml
<?xml version="1.0"?>
<employee>
<firstName>John</firstName>
<lastName>Doe</lastName>
</employee>
96
Output
Content-Type: application/xml
<?xml version="1.0"?>
<?xml version="1.0"?>
<employee>
<employee>
<firstName>Bob</firstName>
<firstName>Bob</firstName>
</employee>
<lastName>Doe</lastName>
</employee>
<?xml version="1.0"?>
<employee>
<firstName>John</firstName>
<lastName>Doe</lastName>
</employee>
97
REST vs SOAP
REST
The RESTful Web services are completely stateless. This can be tested by restarting the server and
checking if the interactions are able to survive.
Restful services provide a good caching infrastructure over HTTP GET method (for most servers).
This can improve the performance, if the data the Web service returns is not altered frequently
The service producer and service consumer need to have a common understanding of the context
as well as the content being passed along as there is no standard set of rules to describe the REST
Web services interface.
REST is particularly useful for restricted-profile devices such as mobile and PDAs for which the
overhead of additional parameters like headers and other SOAP elements are less.
REST services are easy to integrate with the existing websites and are exposed with XML so the
HTML pages can consume the same with ease. There is hardly any need to refactor the existing
website architecture. This makes developers more productive and comfortable as they will not
have to rewrite everything from scratch and just need to add on the existing functionality.
REST vs SOAP
SOAP
The Web Services Description Language (WSDL) contains and describes the common
set of rules to define the messages, bindings, operations and location of the Web
service. WSDL is a sort of formal contract to define the interface that the Web service
offers.
SOAP requires less plumbing code than REST services design (e.g. transactions,
security, coordination, addressing, trust, etc.). Most real-world applications are not
simple and support complex operations, which require conversational state and
contextual information to be maintained. With the SOAP approach, developers need
not worry about writing this plumbing code into the application layer themselves.
SOAP Web services (such as JAX-WS) are useful in handling asynchronous processing
and invocation.
SOAP supports several protocols and technologies, including WSDL, XSDs, SOAP, WSAddressing
99
What is WADL
WADL stands for Web Application Description Language
WADL is a machine-readable XML description of HTTP-based (typically REST) web applications
WADL is intended to simplify the reuse of web services that are based on the existing HTTP
architecture of the Web
WADL is the REST equivalent of SOAP's WSDL, which can also be used to describe REST web
services
WADL was submitted to W3 consortium for standardization but is not yet recognized, nor widely
supported
WADL
100
WADL Elements
Each resource contains param elements to describe the inputs, and method elements which
describe the request and response of a resource
The request element specifies how to represent the input, what types are required and any
The response describes the representation of the service's response, as well as any fault
information, to deal with errors.
101
The application element forms the root of a WADL description and contains the following:
resource_type elements
method elements
representation elements
param elements
102
Each WADL-defined element can have one or more child doc elements that can be used
to document that element. The doc element has the following attributes:
xml:lang Defines the language for the title attribute value and the contents of the doc
element. If an element contains more than one doc element then they MUST have
title A short plain text description of the element being documented, the value
SHOULD be suitable for use as a title for the contained documentation. The doc
element has mixed content and may contain text and zero or more child elements that
form the body of the documentation. It is RECOMMENDED that the child elements be
members of the text, list or table modules of XHTML
103
The grammars element acts as a container for definitions of the format of data
exchanged during execution of the protocol described by the WADL document. Such
definitions may be included inline or by reference using the include element
Include
The include element allows the definitions of one or more data format descriptions to be
included by reference. The href attribute provides a URI for the referenced definitions and is of
type xsd:anyURI. Use of the include element is logically equivalent to in-lining the referenced
document within the WADL grammars element.
104
105
A method element describes the input to and output from an HTTP protocol method that
may be applied to a resource. A method element can either be a method definition or a
reference to a method defined elsewhere.
Method Reference
A method reference element is a child of a resource element that has an href attribute whose type is
xsd:anyURI. The value of the href attribute is a cross reference (see section 2.1 ) to a method definition
element. A method reference element MUST NOT have any other WADL-defined attributes or contain any
WADL-defined child elements.
106
Method Definition
A method definition element is a child of a resource or application element and has the following attributes:
name - Indicates the HTTP method used.
id - An identifier for the method, required for globally defined methods, not allowed on
locally embedded methods. Methods are identified by an XML ID and are referred to using
a URI reference.
It is permissible to have multiple child method elements that have the same value of the name
attribute for a given resource; such siblings represent distinct variations of the same HTTP method
representation
response - Zero or more response elements that describe the possible outputs of the method
107
108
109
Right click on the project node and select New SoapUI Project.
110
Functional Testing
In the New SoapUI Project dialog enter a project name (i.e. Country_info) and click OK.
111
Functional Testing
Enter http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso?WSDL.
Click OK.
112
Functional Testing
113
Functional Testing
Click on the plus sign next to the web service in the navigator to expand.
You now have to enter your data manually in the code editor as shown below. Replace ? with RO (without
quotes)
114
Functional Testing
115
Functional Testing
Receive response
116
Functional Testing
The response of the Web Service will indicate that the country was not found.
After seeing the result, correct the input data.
117
Functional Testing
118
Functional Testing
Next step:
Adding a request to a TestCase will open the Create TestSuite dialog box. Enter a name for your TestSuite
and click OK.
After clicking OK, you will be asked to create a TestCase. In the Create TestCase dialog, enter a name for your
TestCase and click OK.
119
Functional Testing
Next step:
The dialog box Add Request to TestCase will appear. Click OK.
120
Functional Testing
Final step:
SoapUI will now generate a TestSuite and TestCase for you while the request will be added as a TestRequest.
Below is a copy of the request that appears in the interface. A TestCase editor will also open with your new
TestRequest.
The next step is to validate the response in your test by adding an Assertion.
121
Functional Testing
Now that we've created and run our first test, we are going to add a validation of the response. In SoapUI,
this is called adding an assertion.
Schema Compliance
Simple Contains
Simple Not Contains
SOAP Faults
Response SLA
XPath Match
XQuery Match
WS Security Status
WS-Addressing Request/Response Assertion
Script Assertion
122
Functional Testing
Double Click on your Test Request as shown below. This will open the request editor.
After clicking OK, you will be asked to create a TestCase. In the Create TestCase dialog, enter a name for your
TestCase and click OK.
123
Functional Testing
Next step:
In the Configure Response SLA Assertion dialog box, write 500 and click OK. This will validate that the
response of the SLA is under 500.
124
Functional Testing
Next step:
Now that you've added the assertion, you are going to run the request to validate the response. If all
assertions are successful, the SOAP icon should turn green in three places as shown below.
125
Functional Testing
126
Functional Testing
In the XPath Match Configuration press Declare button and write below //m:CapitalCityResult
Click Select from current and you should see the word Bucharest appearing in the Expected Results field.
Click Save
127
Functional Testing
Final step:
Now that you've added a new assertion, you are going to run the test again. If all assertions are successful,
the SOAP icon should turn green in three places as shown below.
128
Service Mocking
Service Mocking, or simulation, is the practice of creating a facsimile environment that works similar to the
environment youre facsimileing.
When to use it: You should use mocks when you cant use the real thing
Advantages:
Disadvantages:
129
Service Mocking
Click OK button.
130
Service Mocking
131
Service Mocking
In the dialog Generate Mock Service you can specify the local port/path for the service you're creating but for
the moment just click OK
132
Service Mocking
Enter the name of your Mock Service in the Name dialog and click OK. For example: Mock convertor
After creating the MockService, you should get a MockService with one operation and one request.
As you can see, the Icons are Grey and inactive. This is an indication that the MockService is not yet running. We
have successfully created our first MockService.
133
Service Mocking
Now, double click on the MockService to see the MockService editor. In the editor we can see a list of all
operations for the service, as well as a request and response log which logs all incoming requests that have
been handled by the MockService.
Double Click on the Conversion Rate Operation to see the MockResponses we have in the MockService
134
Service Mocking
As you can see we do only have one, Let's edit it, double click on it to open the Response Editor
The MockResponse editor is very similar to the standard SoapUI Request editor , but instead of requests, we'll
edit responses. The Incoming Request view is still very useful; it shows the last received request to the
operation which is useful for debugging client calls, including attachments and HTTP headers.
Edit the ConversionRateResult to be something else than the default empty value "?. For example: 2.5
135
Service Mocking
First we must start the MockService. Click the Start button in the MockService editor, the green arrow head ,
this will start the service on the configured port and path
To the Top Right of the Editor you should see that it's running, and the port it's responding on. The play Button
is greyed out and if you would like to stop the MockService, just click the stop button.
136
Service Mocking
This will prompt you to open one of the existing requests for its operation in your project.
137
Service Mocking
When you open the request, SoapUI will automatically change its endpoint to the endpoint of the locally
running MockService instead of the endpoint that the WSDL is using. Submit the opened request by clicking the
Run Button
As you can see the MockService returned the values we entered earlier as the response.
138
Service Mocking
Let's continue by making the created MockResponse a bit more dynamic by changing the dispatch and
by Groovy scripting.
139
Service Mocking
Let's write a script for the response. Click the Script tab in the Response and enter the following Groovy Script,
context.setProperty( "rate", Math.random() )
It will look like this:
This script sets a property called rate to a random number. As you might have noticed we do not use the
property rate anywhere, so let's add it.
140
Service Mocking
of property rate.
Now that we have written a script and the random results will be inserted into the response.
141
The End
Thank You
142