SlideShare une entreprise Scribd logo
1  sur  142
Ionut David &
Sorin Nita
December 2013
WebServices
Workshop
•What is XML and XSD
•What is a Web Service
•What is SOAP
•What is WSDL
•What is JSON
•What is REST
•What is WADL
•Tools
Agenda
2
What is XML
3
• 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 it’s 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>
XML Tree Structure
4
• The first line is the XML declaration. It defines the XML version (1.0) and the encoding used (ISO-
8859-1 = Latin-1/West European character set).
• 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-8859-
1”?>
<note>
<to>Sam</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
XML Tree Structure
5
• XML documents must contain a root element. This element is "the parent" of all other elements.
• All elements can have sub elements (child elements).
• Children on the same level are called siblings (brothers or sisters).
• All elements can have text content and attributes (just like in HTML).
XML Syntax Rules
6
• The syntax rules of XML are very simple and logical.
• All elements must have a closing tag.
• <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>
• All XML elements must be properly nested within each other.
• <b><i>This text is incorrect</b></i>
<b><i>This text is correct</i></b>
• In XML, the attribute values must always be quoted.
• <note date="12/11/2007">
XML Naming Rules
7
• XML elements must follow these naming rules:
• Names can contain letters, numbers, and other characters
• Names cannot start with a number or punctuation character
• Names cannot start with the letters xml (or XML, or Xml, etc)
• Names cannot contain spaces
• Any name can be used, no words are reserved.
• Avoid using the following characters: - (line) . (dot) or : (colon)
XML Namespaces
8
• 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>
• Name conflicts in XML can easily be avoided using a name prefix.
<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>
XML Namespaces
9
• 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>
XML Namespaces
10
• 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.
• It has the following syntax: xmlns=“namespaceURI”
• This XML carries HTML table information:
<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>
Quiz time
11
• Time to test the XML knowledge
XML Schema
12
• 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>
XSD features
13
• An XML Schema:
• defines elements and attributes that can appear in a document
• defines which elements are child elements
• defines the order and the number of child elements
• defines whether an element is empty or can include text
• defines data types for elements and attributes
• defines default and fixed values for elements and attributes
XSD Reference
14
• 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>
• The following fragment: xmlns=http://www.w3schools.com specifies the default namespace
declaration.
• This fragment: xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance indicates the XML Schema
Instance namespace
• 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
XSD <schema> Element
15
• The <schema> element is the root element of every XML Schema.
• The <schema> element may contain some attributes. A schema declaration often looks something
like this:
<?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>
XSD <schema> Element
16
• The following fragment: xmlns:xs=http://www.w3.org/2001/XMLSchema indicates that the
elements and data types used in the schema come from „http://www.w3.org/2001/XMLSchema“
namespace .
• This fragment: targetNamespace="http://www.w3schools.com” indicates that the elements
defined by this schema come from http://www.w3schools.com
• This fragment: xmlns="http://www.w3schools.com” indicates the default namespace.
• This fragment: elementFormDefault=“qualified” indicates that any elements used by the XML
instance document which were declares in this schema must be namespace qualified
<?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>
XSD Simple Element
17
• A simple element is an XML element that contains only text. It cannot contain any other elements
or attributes.
• 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.
• The syntax for defining a simple element is:
<xs:element name=„xxx“ type=„yyy“/>
• 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"/>
XSD Simple Element Values
18
• Simple elements may have a default value OR a fixed value specified.
• A default value is automatically assigned to the element when no other value is specified.
• In the following example the default value is "red":
<xs:element name="color" type="xs:string" default="red"/>
• 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"/>
XSD Attributes
19
• 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.
• The syntax for defining an attribute is:
<xs:attribute name=“xxx" type=“yyy"/>
<xs:attribute name="lang" type="xs:string"/>
• 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:
XSD Attributes Values
20
• Attributes may have a default value OR a fixed value specified.
• A default value is automatically assigned to the attribute when no other value is specified.
• In the following example the default value is "EN":
<xs:attribute name="lang" type="xs:string" default="EN"/>
• 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.
XSD Restrictions/Facets
21
• 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>
• A value that is outside of 0-120 will not be validated.
XSD Restrictions/Facets
22
• 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:simpleType>
<xs:restriction
base="xs:string">
<xs:enumeration
value="Audi"/>
<xs:enumeration
value="Golf"/>
<xs:enumeration
value="BMW"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
• In right side case the type "carType" can be used by other elements because it is not a part of the
"car" element, it’s a new custom type that we’ve created.
<xs:element name="car"
type="carType"/>
<xs:simpleType
name="carType">
<xs:restriction
base="xs:string">
<xs:enumeration
value="Audi"/>
<xs:enumeration
value="Golf"/>
<xs:enumeration
value="BMW"/>
</xs:restriction>
</xs:simpleType>
XSD Restrictions on content
23
• The example below defines an element called "letter" with a restriction. The only acceptable value
is ONE of the LOWERCASE letters from a to z:
<xs:restriction base="xs:string">
<xs:pattern value="[a-z]"/>
</xs:restriction>
• 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>
XSD Restrictions on format
24
• The next example defines an element called "choice" with a restriction. The only acceptable value
is ONE of the following letters: x, y, OR z:
<xs:restriction base="xs:string">
<xs:pattern value="[xyz]"/>
</xs:restriction>
• 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>
XSD Restrictions on format
25
• The next example also defines an element called "letter" with a restriction. The acceptable value
is one or more pairs of letters, each pair consisting of a lower case letter followed by an upper
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>
XSD Restrictions on whitespaces
26
• This example defines an element called "address" with a restriction. The whiteSpace constraint is
set to "preserve", which means that the XML processor WILL NOT remove any white space:
<xs:restriction base="xs:string">
<xs:whiteSpace value="preserve"/>
</xs:restriction>
• 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>
XSD Restrictions on length
27
• To limit the length of a value in an element, we would use the length, maxLength, and minLength
constraints.
• 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.
XSD Complex element
28
• A complex element is an XML element that contains other elements and/or attributes.
• There are four kinds of complex elements:
• empty elements
• elements that contain only other elements
• elements that contain only text
• elements that contain both other elements and text
• Each of these elements may contain attributes as well.
XSD Complex element
29
• A complex XML element, "product", which is empty:
<product pid="1345"/>
• A complex XML element, "employee", which contains only other elements:
<employee>
<firstname>John</firstname>
<lastname>Smith</lastname>
</employee>
• A complex XML element, "food", which contains only text:
<food type="dessert">Ice cream</food>
• A complex XML element, "description", which contains both elements and text:
<description>
It happened on <date lang="norwegian">03.03.99</date> ....
</description>
XSD Complex element
30
• We can define a complex element in an XSD in two ways:
• The “employee” element can be declares directly by naming the element, like this:
<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
• 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"/>
XSD Complex element
31
• You can also base a complex element on an existing complex element and add some elements,
like this:
<xs:element name="employee" type="fullpersoninfo"/>
<xs:complexType name="personinfo">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<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>
XSD Empty Complex element
32
• An empty XML element:
<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>
• 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:
<product prodid="1345" />
• 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.
XSD Empty Complex element
33
• It is possible to declare the "product" element more compactly, like this:
<xs:element name="product" type="prodtype"/>
<xs:complexType name="prodtype">
<xs:attribute name="prodid" type="xs:positiveInteger"/>
</xs:complexType>
• 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">
<xs:complexType>
<xs:attribute name="prodid" type="xs:positiveInteger"/>
</xs:complexType>
</xs:element>
XSD Complex Types with Elements Only
34
• You can define the "person" element in a schema, like this:
• 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):
<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>
XSD Complex Types with Text Only
35
• This type contains only simple content (text and attributes), therefore we add a simpleContent
element around the content. When using simple content, you must define an extension OR a
restriction within the simpleContent element:
• 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>
XSD Complex Types with Mixed Content
36
• 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">
…..
…..
XSD Indicators
37
• 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
XSD Order Indicators
38
• Order indicators are used to define the order of the elements.
• The <all> indicator specifies that the child elements can appear in any order, and that each child
element must occur only once:
<xs:element name="person">
<xs:complexType>
<xs:all>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:all>
</xs:complexType>
</xs:element>
• 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).
XSD Order Indicators
39
• The <choice> indicator specifies that either one child element or another can occur:
<xs:element name="person">
<xs:complexType>
<xs:choice>
<xs:element name="employee" type="employee"/>
<xs:element name="member" type="member"/>
</xs:choice>
</xs:complexType>
</xs:element>
• 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>
XSD Occurrence Indicators
40
• Occurrence indicators are used to define how often an element can occur.
• The <maxOccurs> indicator specifies the maximum 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"/>
</xs:sequence>
</xs:complexType>
</xs:element>
• 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>
XSD Group Indicators
41
• Group indicators are used to define related sets of elements.
• The following example defines a group named "persongroup", that defines a group of elements
that must occur in an exact sequence:
<xs:group name="persongroup">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
<xs:element name="birthday" type="xs:date"/>
</xs:sequence>
</xs:group>
• Attribute groups are defined with the attributeGroup declaration, like this:
<xs:attributeGroup name="groupname">
...
</xs:attributeGroup>
XSD The <any> Element
42
• The <any> element enables us to extend the XML document with elements not specified by the
schema.
• 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.
XSD The <anyAttribute> Element
43
• The <anyAttribute> element enables us to extend the XML document with attributes not specified
by the schema.
• 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>
XSD String Data Types
44
• 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"/>
• An element in your document might look like this:
<customer>John Smith</customer>
• 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"/>
XSD String Data Types
45
• Other data types below derive from the String data type.
• ENTITIES, ENTITY, ID, IDREF, IDREFS
• Language, Name, NCName
• NMTOKEN, NMTOKENS
• Qname
• Restrictions that can be used with String data types:
• enumeration
• length
• maxLength
• minLength
• pattern (NMTOKENS, IDREFS, and ENTITIES cannot use this constraint)
• whiteSpace
XSD Date and Time Data Types
46
• The date data type is used to specify a date.
• The date is specified in the following form "YYYY-MM-DD“.
<xs:element name="start" type="xs:date"/>
• 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
• The time is specified in the following form "hh:mm:ss"
<xs:element name="start" type="xs:time"/>
• The dateTime is specified in the following form "YYYY-MM-DDThh:mm:ss“.
<xs:element name="startdate" type="xs:dateTime"/>
• The dateTime is specified in the following form "YYYY-MM-DDThh:mm:ss“.
<xs:element name="startdate" type="xs:dateTime"/>
XSD Date and Time Data Types
47
• Duration data type is used to specify a time interval in the following form "PnYnMnDTnHnMnS“
• P indicates the period (required)
• T indicates the start of a time section
<xs:element name="period" type="xs:duration"/>
• Other date and time date types used:
• gDay, gMonth, gMonthDay, gYear, gYearMonth
• Restrictions that can be used with Date data types:
• enumeration
• maxExclusive
• maxInclusive
• minExclusive
• minInclusive
• pattern
• whiteSpace
XSD Numeric Data Types
48
• 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
• Restrictions that can be used with Numeric data types
XSD Miscellaneous Data Types
49
• Other miscellaneous data types are boolean, base64Binary, hexBinary, float, double, anyURI,
QName, and NOTATION
• The boolean data type is used to specify a true or false value.
<xs:attribute name="disabled" type="xs:boolean"/>
• Binary data types are used to express binary-formatted data: base64Binary or hexBinary.
<xs:element name="blobsrc" type="xs:hexBinary"/>
• The anyURI data type is used to specify a URI.
• Restrictions that can be used with the other data types:
• enumeration (a Boolean data type cannot use this constraint)
• length (a Boolean data type cannot use this constraint)
• maxLength (a Boolean data type cannot use this constraint)
• minLength (a Boolean data type cannot use this constraint)
• pattern
• whiteSpace
<xs:attribute name="src" type="xs:anyURI"/>
XSD Schema – Business application
50
•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).
• For example a simple purchase order:
• Need to purchase an electric Lawnmower and a baby monitor from a merchant site
• The price for the mower is $148.95
• The price for the baby monitor is $39.98
• The billing should be done to Robert Smith with address: 8 Oak Avenue, 95819 Old Town, PA, USA
• The shipping should be done to Alice Smith with address: 123 Maple Street, 90952 Mill Valley, CA,
USA
XSD Schema – Business appliance
51
<?xml version="1.0"?>
<purchaseOrder orderDate="1999-10-20">
<comment>Hurry, my lawn is going wild!</comment>
<shipTo country="US">
<name>Alice Smith</name>
<street>123 Maple Street</street>
<city>Mill Valley</city>
<state>CA</state>
<zip>90952</zip>
</shipTo>
<billTo country="US">
<name>Robert Smith</name>
<street>8 Oak Avenue</street>
<city>Old Town</city>
<state>PA</state>
<zip>95819</zip>
</billTo>
<items>
<item partNum="872-AA">
<productName>Lawnmower</productName>
<quantity>1</quantity>
<USPrice>148.95</USPrice>
<comment>Confirm this is electric</comment>
</item>
<item partNum="926-AA">
<productName>Baby Monitor</productName>
<quantity>1</quantity>
<USPrice>39.98</USPrice>
<shipDate>1999-05-21</shipDate>
</item>
</items>
</purchaseOrder>
XSD Schema – Business application
52
•Implement a physical model upon which the rules execute
• The BOM must be mapped to a physical data model. This data model is called an
execution object model (XOM)
• 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
XSD Schema – Business appliance
53
• 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
XSD Schema – Business appliance
54
•XSD Schema corresponding to provided basic purchase order XML.
• 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>
XSD Schema – Business appliance
55
•XSD Schema corresponding to provided basic purchase order XML.
Business rule: The address should contain the following details: name of the recipient, street, city, state (all string
based) and zip code (a decimal value) and for USA the country should be implicitly set
maps to
<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>
XSD Schema – Business appliance
56
• The complete schema with all the elements
<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>
XSD Schema – Business appliance
57
<xsd:complexType name="Items">
<xsd:sequence>
<xsd:element name="item" minOccurs="1" maxOccurs="unbounded">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="productName" type="xsd:string"/>
<xsd:element name="quantity">
<xsd:simpleType>
<xsd:restriction base="xsd:positiveInteger">
<xsd:maxExclusive value="100"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="USPrice" type="xsd:decimal"/>
<xsd:element ref="comment" minOccurs="0"/>
<xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
</xsd:sequence>
<xsd:attribute name="partNum" type="SKU" use="required"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
XSD Schema – Business appliance
58
<!-- Stock Keeping Unit, a code for identifying products -->
<xsd:simpleType name="SKU">
<xsd:restriction base="xsd:string">
<xsd:pattern value="d{3}-[A-Z]{2}"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>
END of PART 1
59
What is a Web Service
60
• 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 can convert your applications into Web-applications
• A Web Service is a XML-based information exchange system that use the Internet for direct application-to-
application interaction.
Web Service components
61
• The basic Web services platform is XML + HTTP.
• All the standard Web Services works using following components
• SOAP (Simple Object Access Protocol)
• UDDI (Universal Description, Discovery and Integration)
• WSDL (Web Services Description Language)
What is SOAP
62
• 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
SOAP Building Blocks
63
• A SOAP message is an ordinary XML document containing the following elements:
• An Envelope element that identifies the XML document as a SOAP message
• A Header element that contains header information
• A Body element that contains call and response information
• A Fault element containing errors and status information
SOAP Syntax Rules
64
• Here are some important syntax rules:
• A SOAP message MUST be encoded using XML
• A SOAP message MUST use the SOAP Envelope namespace
• A SOAP message MUST use the SOAP Encoding namespace
• A SOAP message must NOT contain a DTD reference
• A SOAP message must NOT contain XML Processing Instructions
SOAP Message example
65
<?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:Header>
...
</soap:Header>
<soap:Body>
...
<soap:Fault>
...
</soap:Fault>
</soap:Body>
</soap:Envelope>
SOAP Envelope Element
66
• The required SOAP Envelope element is the root element of a SOAP message. This element
defines the XML document as a SOAP message:
<?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">
...
Message information goes here
...
</soap:Envelope>
• 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.
SOAP Header Element
67
• The optional SOAP Header element contains application-specific information (like
authentication, payment, etc) about the SOAP message.
• 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.
SOAP Header Attributes
68
• The SOAP mustUnderstand attribute can be used to indicate whether a header entry is
mandatory or optional for the recipient to process.
• 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.
• A SOAP message has no default encoding.
SOAP Body Element
69
• The required SOAP Body element contains the actual SOAP message intended for the ultimate
endpoint of the message.
• Immediate child elements of the SOAP Body element may be namespace-qualified.
<?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>
<m:GetPriceResponse xmlns:m="http://www.w3schools.com/prices">
<m:Price>1.90</m:Price>
</m:GetPriceResponse>
</soap:Body>
</soap:Envelope>
SOAP Fault Element
70
• The SOAP Fault element holds errors and status information for a SOAP message.
• The optional SOAP Fault element is used to indicate error messages.
• If a Fault element is present, it must appear as a child element of the Body element. A Fault
element can only appear once in a SOAP message.
• The SOAP Fault element has the following sub elements:
Sub Element Description
<faultcode> A code for identifying the fault
<faultstring> A human readable explanation of the fault
<faultactor> Information about who caused the fault to
happen
<detail> Holds application specific error information
related to the Body element
SOAP Fault Element
71
• The faultcode values defined below must be used in the faultcode element when describing
faults:
Error Description
VersionMismatch Found an invalid namespace for the SOAP
Envelope element
MustUnderstand An immediate child element of the Header
element, with the mustUnderstand attribute set
to "1", was not understood
Client The message was incorrectly formed or
contained incorrect information
Server There was a problem with the server so the
message could not proceed
SOAP Example
72
• 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>
SOAP Example
73
• 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>
What is WSDL
74
• WSDL stands for Web Services Description Language
• WSDL is an XML based protocol for information exchange in decentralized and distributed
environments.
• WSDL is a language for describing how to interface with XML-based services.
• WSDL is an XML language used to describe and locate web services
WSDL Elements
75
• 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
WSDL example
76
<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>
WSDL example
77
<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>
WSDL example
78
<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>
WSDL Definition Element
79
• The <definition> element must be the root element of all WSDL documents. It defines the name
of the web service.
• 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
WSDL Types Element
80
• A Web service needs to define its inputs and outputs and how they are mapped into and out of
services. WSDL <types> element take care of defining the data types that are used by the web
service. Types are XML documents or document parts.
<types>
<schema
targetNamespace="http://example.com/stockquote.xsd"
xmlns="http://www.w3.org/2000/10/XMLSchema">
<element name="TradePriceRequest">
<complexType>
<all>
<element name="tickerSymbol" type="string"/>
</all>
</complexType>
</element>
<element name="TradePrice">
<complexType>
<all>
<element name="price" type="float"/>
</all>
</complexType>
</element>
</schema>
</types>
WSDL Message Element
81
• The <message> element describes the data being exchanged between the Web service providers
and consumers.
• 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>
WSDL portType Element
82
• The <portType> element combines multiple message elements to form a complete oneway or
round-trip operation.
• 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>
WSDL portType Element
83
• WSDL has four transmission primitives that an endpoint can support:
• One-way. The endpoint receives a message.
• Request-response. The endpoint receives a message, and sends a correlated message.
• Solicit-response. The endpoint sends a message, and receives a correlated message.
• Notification. The endpoint sends a message.
WSDL Binding Element
84
• The <binding> element provides specific details on how a portType operation will actually be
transmitted over the wire.
• 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 bindings provide information where the service is located.
• You can specify multiple bindings for a single portType.
• For SOAP protocol, the binding is <soap:binding>, and the transport is SOAP messages on top of
HTTP protocol.
• The binding element has two attributes - the name attribute and the type attribute.
<binding name="Hello_Binding" type="tns:Hello_PortType">
WSDL Binding Element
85
<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>
• Here is the piece of code from Example section:
WSDL Ports Element
86
• A <port> element defines an individual endpoint by specifying a single address for a binding.
• The port element has two attributes - the name attribute and the binding attribute.
• A port MUST NOT specify more than one address.
• A port MUST NOT specify any binding information other than address information.
<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>
WSDL Service Element
87
• The <service> element defines the ports supported by the Web service. For each of the
supported protocols, there is one port element. The service element is a collection of ports.
• The service element includes a documentation element to provide human-readable
documentation.
• The name attribute provides a unique name among all services defined within in the enclosing
WSDL document.
• Here is a piece of code from Example:
<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>
WSDL Summary
88
• 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.
• A WSDL document is simply a set of definitions.
• A WSDL is composed from several elements, each one with a specific role.
What is JSON
89
• 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.
• JSON is smaller than XML, and faster and easier to parse.
• The following example is an array of 3 employee records (objects):
{
"employees": [
{ "firstName":"John" , "lastName":"Doe"
},
{ "firstName":"Anna" ,
"lastName":"Smith" },
{ "firstName":"Peter" ,
"lastName":"Jones" }
]
}
JSON Structure
90
• JSON is built on two structures:
• A collection of name/value pairs. In various languages, this is realized as an object, record,
struct, dictionary, hash table, keyed list, or associative array.
• 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"
},
JSON Structure
91
• 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" }
]
}
JSON vs XML
92
• 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>
JSON vs XML
93
• Simple corresponding conversion patterns between XML and JSON.
Patter
n
XML JSON Access
1 <tag/> "tag": null o.tag
2 <tag>text</tag> "tag": "text" o.tag
3 <tag name="value" /> "tag":{"@name": "value"}
o.tag["@name"
]
4
<tag
name="value">text</tag>
"tag": { "@name": "value",
"#text": "text" }
o.tag["@name"
] o.tag["#text"]
5
<tag> <a>text</a>
<b>text</b> </tag>
"tag": { "a": "text", "b":
"text" }
o.tag.a o.tag.b
6
<tag> <a>text</a>
<a>text</a> </tag>
"tag": { "a": ["text", "text"] }
o.tag.a[0]
o.tag.a[1]
7
<tag> text <a>text</a>
</tag>
"tag": { "#text": "text", "a":
"text" }
o.tag["#text"]
o.tag.a
What is REST
94
•Is an architecture style for designing networked applications focused on a system's
resources (including how resource states are addressed and transferred)
•REST stands for Representational State Transfer
•REST relies on a stateless, client-server, cacheable communications protocol (HTTP is
used)
•REST is platform independent
•REST is language independent
REST as Lightweight Web Services
95
•REST is a lightweight alternative to mechanisms like RPC (Remote Procedure Calls)
and Web Services (SOAP, WSDL, etc.)
•REST uses HTTP uniform interface (POST, GET, PUT, DELETE) for all four CRUD
(Create/Read/Update/Delete) operations
• E.g. GET to retrieve (read) simple information
 GET /employees/John HTTP/1.1
 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
REST as Lightweight Web Services
96
• Examples of CRUD operations made on a RESTful API
• Create with HTTP POST
 POST /employee HTTP/1.1
 Host: myserver.com
 Content-Type:application/xml
<?xml version="1.0"?>
<employee>
<firstName>John</firstName>
<lastName>Doe</lastName>
</employee>
• Read with HTTP GET
 GET /employee/John HTTP/1.1
 Host: myserver.com
 Content-Type: application/xml
• Output
• A new employee entry is created with
firstName = John and lastName = Doe
• Reads the employee entry
<?xml version="1.0"?>
<employee>
<firstName>John</firstName>
<lastName>Doe</lastName>
</employee>
REST as Lightweight Web Services
97
• Examples of CRUD operations made on a RESTful API
• Update over HTTP PUT
 PUT /employee/John HTTP/1.1
 Host: myserver.com
 Content-Type: application/xml
<?xml version="1.0"?>
<employee>
<firstName>Bob</firstName>
</employee>
• Delete with HTTP DELETE
 DELETE /employee HTTP/1.1
 Host: myserver.com
 Content-Type:application/xml
<?xml version="1.0"?>
<employee>
<firstName>John</firstName>
<lastName>Doe</lastName>
</employee>
• Output
• Updates the John Doe employee with
firstName to be Bob => the new entry will
be
<?xml version="1.0"?>
<employee>
<firstName>Bob</firstName>
<lastName>Doe</lastName>
</employee>
• Deletes the John Doe employee
REST vs SOAP
98
• 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
and not dynamic in nature.
• 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-based implementation is simple compared to SOAP.
REST vs SOAP
99
•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, WS-
Addressing
What is WADL
100
• 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
WADL Elements
101
• WSDL The service is described using a set of resource 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
specific HTTP headers that are required
• The response describes the representation of the service's response, as well as any fault
information, to deal with errors.
WADL application element
102
•The application element forms the root of a WADL description and contains the following:
• Zero or more doc elements
• An optional grammars element
• Zero or more resources elements
• Zero or more of the following:
• resource_type elements
• method elements
• representation elements
• param elements
WADL documentation element (doc)
103
•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
distinct values for their xml:lang attribute.
• 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
WADL grammars element
104
•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
•It is permissible to include multiple definitions of a particular format: such definitions are
assumed to be equivalent and consumers of a WADL description are free to choose
amongst the alternatives or even combine them if they support that capability.
• 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.
WADL resource element
105
•A resource element contains the following child elements:
• Zero or more doc elements
• Zero or more param elements with one of the following values for its style attribute:
• Template, Query, Matrix , Header
• Zero or more method elements
• Zero or more resource elements that describe sub-resources
WADL method element
106
•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.
WADL method element
107
• 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
and will typically have different input data.
• A method element has the following child elements:
• doc - Zero or more doc elements
• request - Describes the input to the method as a collection of parameters and an optional resource
representation
• response - Zero or more response elements that describe the possible outputs of the method
WADL Example (Yahoo News Search)
108
<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://wadl.dev.java.net/2009/02 wadl.xsd"
xmlns:tns="urn:yahoo:yn"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:yn="urn:yahoo:yn"
xmlns:ya="urn:yahoo:api"
xmlns="http://wadl.dev.java.net/2009/02">
<grammars>
<include href="NewsSearchResponse.xsd"/>
<include href="Error.xsd"/>
</grammars>
<resources base="http://api.search.yahoo.com/NewsSearchService/V1/">
<resource path="newsSearch">
<method name="GET" id="search">
<request>
<param name="appid" type="xsd:string" style="query" required="true"/>
<param name="query" type="xsd:string" style="query" required="true"/>
<param name="type" style="query" default="all">
<option value="all"/>
<option value="any"/>
<option value="phrase"/>
</param>
WADL Example (Yahoo News Search)
109
<param name="results" style="query" type="xsd:int" default="10"/>
<param name="start" style="query" type="xsd:int" default="1"/>
<param name="sort" style="query" default="rank">
<option value="rank"/>
<option value="date"/>
</param>
<param name="language" style="query" type="xsd:string"/>
</request>
<response status="200">
<representation mediaType="application/xml" element="yn:ResultSet"/>
</response>
<response status="400">
<representation mediaType="application/xml" element="ya:Error"/>
</response>
</method>
</resource>
</resources>
</application>
Testing with SoapUI
110
• Create a SoapUI Project
• Right click on the project node and select New SoapUI Project.
Functional Testing
111
• In the New SoapUI Project dialog enter a project name (i.e. Country_info) and click OK.
• Right click on the project node and select Add WSDL.
Functional Testing
112
• The Add WSDL dialog is now open
• Enter http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso?WSDL.
• Click OK.
Functional Testing
113
• Now see that the WSDL was successfully added to the
project by seeing the operations in the Web Service in
the navigatorEnter
Functional Testing
114
• Create a request from your WSDL
• Click on the plus sign next to the web service in the navigator to expand.
• Double click on the request.
• You now have to enter your data manually in the code editor as shown below. Replace “?” with “RO” (without
quotes)
Functional Testing
115
• Run a request to the Web Service
• Click on the green arrow head sign to submit the request.
Functional Testing
116
• Receive response
• On the right side of the window the response will be displayed.
Functional Testing
117
• Run an invalid request to the Web Service.
• Introduce a wrong country code (like “ZZ”).
• Click on the green arrow head sign to submit the request.
• The response of the Web Service will indicate that the country was not found.
• After seeing the result, correct the input data.
Functional Testing
118
• Create a Test Case from a request.
• In the request editor, select Add This Request to TestCase.
Functional Testing
119
• 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.
Functional Testing
120
• Next step:
• The dialog box Add Request to TestCase will appear. Click OK.
Functional Testing
121
• 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.
Functional Testing
122
• Add an Assertion to the test:
• 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.
• Examples of assertions that is possible in SoapUI are:
• 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
Functional Testing
123
• Close all windows you have open in SoapUI before starting:
• 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.
Functional Testing
124
• Next step:
• Select Response SLA from the Add Assertion menu.
• 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.
Functional Testing
125
• 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.
Functional Testing
126
• Validate response with XPath Match:
• Select XPath Match from the Add Assertion menu.
Functional Testing
127
• Validate response with XPath Match:
• 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
Functional Testing
128
• 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.
Service Mocking
129
• “Service Mocking, or simulation, is the practice of creating a facsimile environment that works similar to the
environment you’re facsimileing”.
• When to use it: You should use mocks when you can’t use the real thing
• Advantages:
• You can create tests in advance.
• Teams can work in parallel.
• You can create proof of concepts or demos.
• You can isolate systems.
• You can write test for resource not accessible.
• Mock can be delivered to the customer.
• Disadvantages:
• You have to do Double work.
• Deployment constraints.
• It’s not live is it?
Service Mocking
130
• Start a new SoapUI project using the following wsdl:
http://www.webservicex.net/CurrencyConvertor.asmx?WSDL
• Click OK button.
Service Mocking
131
• Right-click on one of the SOAP interfaces and select Generate MockService.
Service Mocking
132
• 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
Service Mocking
133
• 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.
Service Mocking
134
• 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
Service Mocking
135
• 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
Service Mocking
136
• 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.
Service Mocking
137
• Now in the MockResponse editor, Click the Button Create Request.
• This will prompt you to open one of the existing requests for its operation in your project.
• You will also need to give it a name.
Service Mocking
138
• 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.
Service Mocking
139
• Let's continue by making the created MockResponse a bit more dynamic by changing the dispatch and
by Groovy scripting.
• First we’ll create a second MockResponse.
• Give it a Groovy Name
Service Mocking
140
• 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.
Service Mocking
141
• In the ConversionRateResult element enter the following: ${rate}
This is called a Property expansion and it's a very powerful feature in SoapUI. By inserting a property expansion
in any element you can then fill the element programmatically. Basically it tells SoapUI to use the current value
of property rate.
• Now that we have written a script and the random results will be inserted into the response.
The End
142
Thank You

Contenu connexe

Tendances (20)

Xml 2
Xml  2 Xml  2
Xml 2
 
Xslt
XsltXslt
Xslt
 
fundamentals of XML
fundamentals of XMLfundamentals of XML
fundamentals of XML
 
Xml basics
Xml basicsXml basics
Xml basics
 
XML DTD and Schema
XML DTD and SchemaXML DTD and Schema
XML DTD and Schema
 
XML Schemas
XML SchemasXML Schemas
XML Schemas
 
XSLT
XSLTXSLT
XSLT
 
transforming xml using xsl and xslt
transforming xml using xsl and xslttransforming xml using xsl and xslt
transforming xml using xsl and xslt
 
Introductionto xslt
Introductionto xsltIntroductionto xslt
Introductionto xslt
 
Transforming xml with XSLT
Transforming  xml with XSLTTransforming  xml with XSLT
Transforming xml with XSLT
 
Xml schema
Xml schemaXml schema
Xml schema
 
Xml Schema
Xml SchemaXml Schema
Xml Schema
 
Dos and donts
Dos and dontsDos and donts
Dos and donts
 
Xslt
XsltXslt
Xslt
 
Learning XSLT
Learning XSLTLearning XSLT
Learning XSLT
 
XSLT
XSLTXSLT
XSLT
 
XSLT. Basic.
XSLT. Basic.XSLT. Basic.
XSLT. Basic.
 
XML and XSLT
XML and XSLTXML and XSLT
XML and XSLT
 
eXtensible Markup Language (XML)
eXtensible Markup Language (XML)eXtensible Markup Language (XML)
eXtensible Markup Language (XML)
 
XSLT
XSLTXSLT
XSLT
 

En vedette

TDD a REST API With Node.js and MongoDB
TDD a REST API With Node.js and MongoDBTDD a REST API With Node.js and MongoDB
TDD a REST API With Node.js and MongoDBValeri Karpov
 
Postman Collection Format v2.0 (pre-draft)
Postman Collection Format v2.0 (pre-draft)Postman Collection Format v2.0 (pre-draft)
Postman Collection Format v2.0 (pre-draft)Postman
 
Securty Testing For RESTful Applications
Securty Testing For RESTful ApplicationsSecurty Testing For RESTful Applications
Securty Testing For RESTful ApplicationsSource Conference
 
TestLink introduction
TestLink introductionTestLink introduction
TestLink introductionDavid Ionut
 
REST API testing with SpecFlow
REST API testing with SpecFlowREST API testing with SpecFlow
REST API testing with SpecFlowAiste Stikliute
 
How to Automate API Testing
How to Automate API TestingHow to Automate API Testing
How to Automate API TestingBruno Pedro
 
Product Design for Rapid Growth
Product Design for Rapid GrowthProduct Design for Rapid Growth
Product Design for Rapid GrowthAditi Kulkarni
 
Selenium Tips & Tricks
Selenium Tips & TricksSelenium Tips & Tricks
Selenium Tips & TricksDave Haeffner
 
Ppt of soap ui
Ppt of soap uiPpt of soap ui
Ppt of soap uipkslide28
 
Webservices testing using SoapUI
Webservices testing using SoapUIWebservices testing using SoapUI
Webservices testing using SoapUITesting World
 
Understanding and testing restful web services
Understanding and testing restful web servicesUnderstanding and testing restful web services
Understanding and testing restful web servicesmwinteringham
 
JSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons LearnedJSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons LearnedKazuho Oku
 
40+ tips to use Postman more efficiently
40+ tips to use Postman more efficiently40+ tips to use Postman more efficiently
40+ tips to use Postman more efficientlypostmanclient
 

En vedette (18)

TDD a REST API With Node.js and MongoDB
TDD a REST API With Node.js and MongoDBTDD a REST API With Node.js and MongoDB
TDD a REST API With Node.js and MongoDB
 
JSON Injection
JSON InjectionJSON Injection
JSON Injection
 
Postman Collection Format v2.0 (pre-draft)
Postman Collection Format v2.0 (pre-draft)Postman Collection Format v2.0 (pre-draft)
Postman Collection Format v2.0 (pre-draft)
 
Pentesting RESTful WebServices v1.0
Pentesting RESTful WebServices v1.0Pentesting RESTful WebServices v1.0
Pentesting RESTful WebServices v1.0
 
Securty Testing For RESTful Applications
Securty Testing For RESTful ApplicationsSecurty Testing For RESTful Applications
Securty Testing For RESTful Applications
 
API Testing
API TestingAPI Testing
API Testing
 
Api testing
Api testingApi testing
Api testing
 
TestLink introduction
TestLink introductionTestLink introduction
TestLink introduction
 
REST API testing with SpecFlow
REST API testing with SpecFlowREST API testing with SpecFlow
REST API testing with SpecFlow
 
Learn SoapUI
Learn SoapUILearn SoapUI
Learn SoapUI
 
How to Automate API Testing
How to Automate API TestingHow to Automate API Testing
How to Automate API Testing
 
Product Design for Rapid Growth
Product Design for Rapid GrowthProduct Design for Rapid Growth
Product Design for Rapid Growth
 
Selenium Tips & Tricks
Selenium Tips & TricksSelenium Tips & Tricks
Selenium Tips & Tricks
 
Ppt of soap ui
Ppt of soap uiPpt of soap ui
Ppt of soap ui
 
Webservices testing using SoapUI
Webservices testing using SoapUIWebservices testing using SoapUI
Webservices testing using SoapUI
 
Understanding and testing restful web services
Understanding and testing restful web servicesUnderstanding and testing restful web services
Understanding and testing restful web services
 
JSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons LearnedJSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons Learned
 
40+ tips to use Postman more efficiently
40+ tips to use Postman more efficiently40+ tips to use Postman more efficiently
40+ tips to use Postman more efficiently
 

Similaire à Web Service Workshop - 3 days (20)

02 xml schema
02 xml schema02 xml schema
02 xml schema
 
Xsd
XsdXsd
Xsd
 
Xsd
XsdXsd
Xsd
 
XML Fundamentals
XML FundamentalsXML Fundamentals
XML Fundamentals
 
XML, DTD & XSD Overview
XML, DTD & XSD OverviewXML, DTD & XSD Overview
XML, DTD & XSD Overview
 
XML
XMLXML
XML
 
1 xml fundamentals
1 xml fundamentals1 xml fundamentals
1 xml fundamentals
 
Xsd examples
Xsd examplesXsd examples
Xsd examples
 
Introduction to xml schema
Introduction to xml schemaIntroduction to xml schema
Introduction to xml schema
 
Xml and DTD's
Xml and DTD'sXml and DTD's
Xml and DTD's
 
Xml part4
Xml part4Xml part4
Xml part4
 
XML
XMLXML
XML
 
Xml
XmlXml
Xml
 
Xml unit1
Xml unit1Xml unit1
Xml unit1
 
Unit3wt
Unit3wtUnit3wt
Unit3wt
 
Unit3wt
Unit3wtUnit3wt
Unit3wt
 
Xml intro1
Xml intro1Xml intro1
Xml intro1
 
Xml schema
Xml schemaXml schema
Xml schema
 
XML SCHEMAS
XML SCHEMASXML SCHEMAS
XML SCHEMAS
 
paper about xml
paper about xmlpaper about xml
paper about xml
 

Dernier

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 

Dernier (20)

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 

Web Service Workshop - 3 days

  • 1. Ionut David & Sorin Nita December 2013 WebServices Workshop
  • 2. •What is XML and XSD •What is a Web Service •What is SOAP •What is WSDL •What is JSON •What is REST •What is WADL •Tools Agenda 2
  • 3. What is XML 3 • 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 it’s 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>
  • 4. XML Tree Structure 4 • The first line is the XML declaration. It defines the XML version (1.0) and the encoding used (ISO- 8859-1 = Latin-1/West European character set). • 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-8859- 1”?> <note> <to>Sam</to> <from>John</from> <heading>Reminder</heading> <body>Don't forget the meeting!</body> </note>
  • 5. XML Tree Structure 5 • XML documents must contain a root element. This element is "the parent" of all other elements. • All elements can have sub elements (child elements). • Children on the same level are called siblings (brothers or sisters). • All elements can have text content and attributes (just like in HTML).
  • 6. XML Syntax Rules 6 • The syntax rules of XML are very simple and logical. • All elements must have a closing tag. • <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> • All XML elements must be properly nested within each other. • <b><i>This text is incorrect</b></i> <b><i>This text is correct</i></b> • In XML, the attribute values must always be quoted. • <note date="12/11/2007">
  • 7. XML Naming Rules 7 • XML elements must follow these naming rules: • Names can contain letters, numbers, and other characters • Names cannot start with a number or punctuation character • Names cannot start with the letters xml (or XML, or Xml, etc) • Names cannot contain spaces • Any name can be used, no words are reserved. • Avoid using the following characters: - (line) . (dot) or : (colon)
  • 8. XML Namespaces 8 • 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> • Name conflicts in XML can easily be avoided using a name prefix. <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>
  • 9. XML Namespaces 9 • 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>
  • 10. XML Namespaces 10 • 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. • It has the following syntax: xmlns=“namespaceURI” • This XML carries HTML table information: <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>
  • 11. Quiz time 11 • Time to test the XML knowledge
  • 12. XML Schema 12 • 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>
  • 13. XSD features 13 • An XML Schema: • defines elements and attributes that can appear in a document • defines which elements are child elements • defines the order and the number of child elements • defines whether an element is empty or can include text • defines data types for elements and attributes • defines default and fixed values for elements and attributes
  • 14. XSD Reference 14 • 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> • The following fragment: xmlns=http://www.w3schools.com specifies the default namespace declaration. • This fragment: xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance indicates the XML Schema Instance namespace • 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
  • 15. XSD <schema> Element 15 • The <schema> element is the root element of every XML Schema. • The <schema> element may contain some attributes. A schema declaration often looks something like this: <?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>
  • 16. XSD <schema> Element 16 • The following fragment: xmlns:xs=http://www.w3.org/2001/XMLSchema indicates that the elements and data types used in the schema come from „http://www.w3.org/2001/XMLSchema“ namespace . • This fragment: targetNamespace="http://www.w3schools.com” indicates that the elements defined by this schema come from http://www.w3schools.com • This fragment: xmlns="http://www.w3schools.com” indicates the default namespace. • This fragment: elementFormDefault=“qualified” indicates that any elements used by the XML instance document which were declares in this schema must be namespace qualified <?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>
  • 17. XSD Simple Element 17 • A simple element is an XML element that contains only text. It cannot contain any other elements or attributes. • 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. • The syntax for defining a simple element is: <xs:element name=„xxx“ type=„yyy“/> • 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"/>
  • 18. XSD Simple Element Values 18 • Simple elements may have a default value OR a fixed value specified. • A default value is automatically assigned to the element when no other value is specified. • In the following example the default value is "red": <xs:element name="color" type="xs:string" default="red"/> • 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"/>
  • 19. XSD Attributes 19 • 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. • The syntax for defining an attribute is: <xs:attribute name=“xxx" type=“yyy"/> <xs:attribute name="lang" type="xs:string"/> • 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:
  • 20. XSD Attributes Values 20 • Attributes may have a default value OR a fixed value specified. • A default value is automatically assigned to the attribute when no other value is specified. • In the following example the default value is "EN": <xs:attribute name="lang" type="xs:string" default="EN"/> • 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.
  • 21. XSD Restrictions/Facets 21 • 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> • A value that is outside of 0-120 will not be validated.
  • 22. XSD Restrictions/Facets 22 • 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:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="Audi"/> <xs:enumeration value="Golf"/> <xs:enumeration value="BMW"/> </xs:restriction> </xs:simpleType> </xs:element> • In right side case the type "carType" can be used by other elements because it is not a part of the "car" element, it’s a new custom type that we’ve created. <xs:element name="car" type="carType"/> <xs:simpleType name="carType"> <xs:restriction base="xs:string"> <xs:enumeration value="Audi"/> <xs:enumeration value="Golf"/> <xs:enumeration value="BMW"/> </xs:restriction> </xs:simpleType>
  • 23. XSD Restrictions on content 23 • The example below defines an element called "letter" with a restriction. The only acceptable value is ONE of the LOWERCASE letters from a to z: <xs:restriction base="xs:string"> <xs:pattern value="[a-z]"/> </xs:restriction> • 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>
  • 24. XSD Restrictions on format 24 • The next example defines an element called "choice" with a restriction. The only acceptable value is ONE of the following letters: x, y, OR z: <xs:restriction base="xs:string"> <xs:pattern value="[xyz]"/> </xs:restriction> • 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>
  • 25. XSD Restrictions on format 25 • The next example also defines an element called "letter" with a restriction. The acceptable value is one or more pairs of letters, each pair consisting of a lower case letter followed by an upper 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>
  • 26. XSD Restrictions on whitespaces 26 • This example defines an element called "address" with a restriction. The whiteSpace constraint is set to "preserve", which means that the XML processor WILL NOT remove any white space: <xs:restriction base="xs:string"> <xs:whiteSpace value="preserve"/> </xs:restriction> • 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>
  • 27. XSD Restrictions on length 27 • To limit the length of a value in an element, we would use the length, maxLength, and minLength constraints. • 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.
  • 28. XSD Complex element 28 • A complex element is an XML element that contains other elements and/or attributes. • There are four kinds of complex elements: • empty elements • elements that contain only other elements • elements that contain only text • elements that contain both other elements and text • Each of these elements may contain attributes as well.
  • 29. XSD Complex element 29 • A complex XML element, "product", which is empty: <product pid="1345"/> • A complex XML element, "employee", which contains only other elements: <employee> <firstname>John</firstname> <lastname>Smith</lastname> </employee> • A complex XML element, "food", which contains only text: <food type="dessert">Ice cream</food> • A complex XML element, "description", which contains both elements and text: <description> It happened on <date lang="norwegian">03.03.99</date> .... </description>
  • 30. XSD Complex element 30 • We can define a complex element in an XSD in two ways: • The “employee” element can be declares directly by naming the element, like this: <xs:element name="employee"> <xs:complexType> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> • 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"/>
  • 31. XSD Complex element 31 • You can also base a complex element on an existing complex element and add some elements, like this: <xs:element name="employee" type="fullpersoninfo"/> <xs:complexType name="personinfo"> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> </xs:sequence> </xs:complexType> <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>
  • 32. XSD Empty Complex element 32 • An empty XML element: <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> • 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: <product prodid="1345" /> • 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.
  • 33. XSD Empty Complex element 33 • It is possible to declare the "product" element more compactly, like this: <xs:element name="product" type="prodtype"/> <xs:complexType name="prodtype"> <xs:attribute name="prodid" type="xs:positiveInteger"/> </xs:complexType> • 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"> <xs:complexType> <xs:attribute name="prodid" type="xs:positiveInteger"/> </xs:complexType> </xs:element>
  • 34. XSD Complex Types with Elements Only 34 • You can define the "person" element in a schema, like this: • 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): <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>
  • 35. XSD Complex Types with Text Only 35 • This type contains only simple content (text and attributes), therefore we add a simpleContent element around the content. When using simple content, you must define an extension OR a restriction within the simpleContent element: • 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>
  • 36. XSD Complex Types with Mixed Content 36 • 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"> ….. …..
  • 37. XSD Indicators 37 • 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
  • 38. XSD Order Indicators 38 • Order indicators are used to define the order of the elements. • The <all> indicator specifies that the child elements can appear in any order, and that each child element must occur only once: <xs:element name="person"> <xs:complexType> <xs:all> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> </xs:all> </xs:complexType> </xs:element> • 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).
  • 39. XSD Order Indicators 39 • The <choice> indicator specifies that either one child element or another can occur: <xs:element name="person"> <xs:complexType> <xs:choice> <xs:element name="employee" type="employee"/> <xs:element name="member" type="member"/> </xs:choice> </xs:complexType> </xs:element> • 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>
  • 40. XSD Occurrence Indicators 40 • Occurrence indicators are used to define how often an element can occur. • The <maxOccurs> indicator specifies the maximum 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"/> </xs:sequence> </xs:complexType> </xs:element> • 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>
  • 41. XSD Group Indicators 41 • Group indicators are used to define related sets of elements. • The following example defines a group named "persongroup", that defines a group of elements that must occur in an exact sequence: <xs:group name="persongroup"> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> <xs:element name="birthday" type="xs:date"/> </xs:sequence> </xs:group> • Attribute groups are defined with the attributeGroup declaration, like this: <xs:attributeGroup name="groupname"> ... </xs:attributeGroup>
  • 42. XSD The <any> Element 42 • The <any> element enables us to extend the XML document with elements not specified by the schema. • 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.
  • 43. XSD The <anyAttribute> Element 43 • The <anyAttribute> element enables us to extend the XML document with attributes not specified by the schema. • 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>
  • 44. XSD String Data Types 44 • 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"/> • An element in your document might look like this: <customer>John Smith</customer> • 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"/>
  • 45. XSD String Data Types 45 • Other data types below derive from the String data type. • ENTITIES, ENTITY, ID, IDREF, IDREFS • Language, Name, NCName • NMTOKEN, NMTOKENS • Qname • Restrictions that can be used with String data types: • enumeration • length • maxLength • minLength • pattern (NMTOKENS, IDREFS, and ENTITIES cannot use this constraint) • whiteSpace
  • 46. XSD Date and Time Data Types 46 • The date data type is used to specify a date. • The date is specified in the following form "YYYY-MM-DD“. <xs:element name="start" type="xs:date"/> • 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 • The time is specified in the following form "hh:mm:ss" <xs:element name="start" type="xs:time"/> • The dateTime is specified in the following form "YYYY-MM-DDThh:mm:ss“. <xs:element name="startdate" type="xs:dateTime"/> • The dateTime is specified in the following form "YYYY-MM-DDThh:mm:ss“. <xs:element name="startdate" type="xs:dateTime"/>
  • 47. XSD Date and Time Data Types 47 • Duration data type is used to specify a time interval in the following form "PnYnMnDTnHnMnS“ • P indicates the period (required) • T indicates the start of a time section <xs:element name="period" type="xs:duration"/> • Other date and time date types used: • gDay, gMonth, gMonthDay, gYear, gYearMonth • Restrictions that can be used with Date data types: • enumeration • maxExclusive • maxInclusive • minExclusive • minInclusive • pattern • whiteSpace
  • 48. XSD Numeric Data Types 48 • 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 • Restrictions that can be used with Numeric data types
  • 49. XSD Miscellaneous Data Types 49 • Other miscellaneous data types are boolean, base64Binary, hexBinary, float, double, anyURI, QName, and NOTATION • The boolean data type is used to specify a true or false value. <xs:attribute name="disabled" type="xs:boolean"/> • Binary data types are used to express binary-formatted data: base64Binary or hexBinary. <xs:element name="blobsrc" type="xs:hexBinary"/> • The anyURI data type is used to specify a URI. • Restrictions that can be used with the other data types: • enumeration (a Boolean data type cannot use this constraint) • length (a Boolean data type cannot use this constraint) • maxLength (a Boolean data type cannot use this constraint) • minLength (a Boolean data type cannot use this constraint) • pattern • whiteSpace <xs:attribute name="src" type="xs:anyURI"/>
  • 50. XSD Schema – Business application 50 •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). • For example a simple purchase order: • Need to purchase an electric Lawnmower and a baby monitor from a merchant site • The price for the mower is $148.95 • The price for the baby monitor is $39.98 • The billing should be done to Robert Smith with address: 8 Oak Avenue, 95819 Old Town, PA, USA • The shipping should be done to Alice Smith with address: 123 Maple Street, 90952 Mill Valley, CA, USA
  • 51. XSD Schema – Business appliance 51 <?xml version="1.0"?> <purchaseOrder orderDate="1999-10-20"> <comment>Hurry, my lawn is going wild!</comment> <shipTo country="US"> <name>Alice Smith</name> <street>123 Maple Street</street> <city>Mill Valley</city> <state>CA</state> <zip>90952</zip> </shipTo> <billTo country="US"> <name>Robert Smith</name> <street>8 Oak Avenue</street> <city>Old Town</city> <state>PA</state> <zip>95819</zip> </billTo> <items> <item partNum="872-AA"> <productName>Lawnmower</productName> <quantity>1</quantity> <USPrice>148.95</USPrice> <comment>Confirm this is electric</comment> </item> <item partNum="926-AA"> <productName>Baby Monitor</productName> <quantity>1</quantity> <USPrice>39.98</USPrice> <shipDate>1999-05-21</shipDate> </item> </items> </purchaseOrder>
  • 52. XSD Schema – Business application 52 •Implement a physical model upon which the rules execute • The BOM must be mapped to a physical data model. This data model is called an execution object model (XOM) • 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
  • 53. XSD Schema – Business appliance 53 • 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
  • 54. XSD Schema – Business appliance 54 •XSD Schema corresponding to provided basic purchase order XML. • 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>
  • 55. XSD Schema – Business appliance 55 •XSD Schema corresponding to provided basic purchase order XML. Business rule: The address should contain the following details: name of the recipient, street, city, state (all string based) and zip code (a decimal value) and for USA the country should be implicitly set maps to <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. XSD Schema – Business appliance 56 • The complete schema with all the elements <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>
  • 57. XSD Schema – Business appliance 57 <xsd:complexType name="Items"> <xsd:sequence> <xsd:element name="item" minOccurs="1" maxOccurs="unbounded"> <xsd:complexType> <xsd:sequence> <xsd:element name="productName" type="xsd:string"/> <xsd:element name="quantity"> <xsd:simpleType> <xsd:restriction base="xsd:positiveInteger"> <xsd:maxExclusive value="100"/> </xsd:restriction> </xsd:simpleType> </xsd:element> <xsd:element name="USPrice" type="xsd:decimal"/> <xsd:element ref="comment" minOccurs="0"/> <xsd:element name="shipDate" type="xsd:date" minOccurs="0"/> </xsd:sequence> <xsd:attribute name="partNum" type="SKU" use="required"/> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType>
  • 58. XSD Schema – Business appliance 58 <!-- Stock Keeping Unit, a code for identifying products --> <xsd:simpleType name="SKU"> <xsd:restriction base="xsd:string"> <xsd:pattern value="d{3}-[A-Z]{2}"/> </xsd:restriction> </xsd:simpleType> </xsd:schema>
  • 59. END of PART 1 59
  • 60. What is a Web Service 60 • 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 can convert your applications into Web-applications • A Web Service is a XML-based information exchange system that use the Internet for direct application-to- application interaction.
  • 61. Web Service components 61 • The basic Web services platform is XML + HTTP. • All the standard Web Services works using following components • SOAP (Simple Object Access Protocol) • UDDI (Universal Description, Discovery and Integration) • WSDL (Web Services Description Language)
  • 62. What is SOAP 62 • 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
  • 63. SOAP Building Blocks 63 • A SOAP message is an ordinary XML document containing the following elements: • An Envelope element that identifies the XML document as a SOAP message • A Header element that contains header information • A Body element that contains call and response information • A Fault element containing errors and status information
  • 64. SOAP Syntax Rules 64 • Here are some important syntax rules: • A SOAP message MUST be encoded using XML • A SOAP message MUST use the SOAP Envelope namespace • A SOAP message MUST use the SOAP Encoding namespace • A SOAP message must NOT contain a DTD reference • A SOAP message must NOT contain XML Processing Instructions
  • 65. SOAP Message example 65 <?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:Header> ... </soap:Header> <soap:Body> ... <soap:Fault> ... </soap:Fault> </soap:Body> </soap:Envelope>
  • 66. SOAP Envelope Element 66 • The required SOAP Envelope element is the root element of a SOAP message. This element defines the XML document as a SOAP message: <?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"> ... Message information goes here ... </soap:Envelope> • 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.
  • 67. SOAP Header Element 67 • The optional SOAP Header element contains application-specific information (like authentication, payment, etc) about the SOAP message. • 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.
  • 68. SOAP Header Attributes 68 • The SOAP mustUnderstand attribute can be used to indicate whether a header entry is mandatory or optional for the recipient to process. • 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. • A SOAP message has no default encoding.
  • 69. SOAP Body Element 69 • The required SOAP Body element contains the actual SOAP message intended for the ultimate endpoint of the message. • Immediate child elements of the SOAP Body element may be namespace-qualified. <?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> <m:GetPriceResponse xmlns:m="http://www.w3schools.com/prices"> <m:Price>1.90</m:Price> </m:GetPriceResponse> </soap:Body> </soap:Envelope>
  • 70. SOAP Fault Element 70 • The SOAP Fault element holds errors and status information for a SOAP message. • The optional SOAP Fault element is used to indicate error messages. • If a Fault element is present, it must appear as a child element of the Body element. A Fault element can only appear once in a SOAP message. • The SOAP Fault element has the following sub elements: Sub Element Description <faultcode> A code for identifying the fault <faultstring> A human readable explanation of the fault <faultactor> Information about who caused the fault to happen <detail> Holds application specific error information related to the Body element
  • 71. SOAP Fault Element 71 • The faultcode values defined below must be used in the faultcode element when describing faults: Error Description VersionMismatch Found an invalid namespace for the SOAP Envelope element MustUnderstand An immediate child element of the Header element, with the mustUnderstand attribute set to "1", was not understood Client The message was incorrectly formed or contained incorrect information Server There was a problem with the server so the message could not proceed
  • 72. SOAP Example 72 • 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>
  • 73. SOAP Example 73 • 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>
  • 74. What is WSDL 74 • WSDL stands for Web Services Description Language • WSDL is an XML based protocol for information exchange in decentralized and distributed environments. • WSDL is a language for describing how to interface with XML-based services. • WSDL is an XML language used to describe and locate web services
  • 75. WSDL Elements 75 • 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
  • 76. WSDL example 76 <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>
  • 77. WSDL example 77 <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>
  • 78. WSDL example 78 <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>
  • 79. WSDL Definition Element 79 • The <definition> element must be the root element of all WSDL documents. It defines the name of the web service. • 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
  • 80. WSDL Types Element 80 • A Web service needs to define its inputs and outputs and how they are mapped into and out of services. WSDL <types> element take care of defining the data types that are used by the web service. Types are XML documents or document parts. <types> <schema targetNamespace="http://example.com/stockquote.xsd" xmlns="http://www.w3.org/2000/10/XMLSchema"> <element name="TradePriceRequest"> <complexType> <all> <element name="tickerSymbol" type="string"/> </all> </complexType> </element> <element name="TradePrice"> <complexType> <all> <element name="price" type="float"/> </all> </complexType> </element> </schema> </types>
  • 81. WSDL Message Element 81 • The <message> element describes the data being exchanged between the Web service providers and consumers. • 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>
  • 82. WSDL portType Element 82 • The <portType> element combines multiple message elements to form a complete oneway or round-trip operation. • 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>
  • 83. WSDL portType Element 83 • WSDL has four transmission primitives that an endpoint can support: • One-way. The endpoint receives a message. • Request-response. The endpoint receives a message, and sends a correlated message. • Solicit-response. The endpoint sends a message, and receives a correlated message. • Notification. The endpoint sends a message.
  • 84. WSDL Binding Element 84 • The <binding> element provides specific details on how a portType operation will actually be transmitted over the wire. • 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 bindings provide information where the service is located. • You can specify multiple bindings for a single portType. • For SOAP protocol, the binding is <soap:binding>, and the transport is SOAP messages on top of HTTP protocol. • The binding element has two attributes - the name attribute and the type attribute. <binding name="Hello_Binding" type="tns:Hello_PortType">
  • 85. WSDL Binding Element 85 <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> • Here is the piece of code from Example section:
  • 86. WSDL Ports Element 86 • A <port> element defines an individual endpoint by specifying a single address for a binding. • The port element has two attributes - the name attribute and the binding attribute. • A port MUST NOT specify more than one address. • A port MUST NOT specify any binding information other than address information. <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>
  • 87. WSDL Service Element 87 • The <service> element defines the ports supported by the Web service. For each of the supported protocols, there is one port element. The service element is a collection of ports. • The service element includes a documentation element to provide human-readable documentation. • The name attribute provides a unique name among all services defined within in the enclosing WSDL document. • Here is a piece of code from Example: <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>
  • 88. WSDL Summary 88 • 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. • A WSDL document is simply a set of definitions. • A WSDL is composed from several elements, each one with a specific role.
  • 89. What is JSON 89 • 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. • JSON is smaller than XML, and faster and easier to parse. • The following example is an array of 3 employee records (objects): { "employees": [ { "firstName":"John" , "lastName":"Doe" }, { "firstName":"Anna" , "lastName":"Smith" }, { "firstName":"Peter" , "lastName":"Jones" } ] }
  • 90. JSON Structure 90 • JSON is built on two structures: • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. • 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" },
  • 91. JSON Structure 91 • 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" } ] }
  • 92. JSON vs XML 92 • 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>
  • 93. JSON vs XML 93 • Simple corresponding conversion patterns between XML and JSON. Patter n XML JSON Access 1 <tag/> "tag": null o.tag 2 <tag>text</tag> "tag": "text" o.tag 3 <tag name="value" /> "tag":{"@name": "value"} o.tag["@name" ] 4 <tag name="value">text</tag> "tag": { "@name": "value", "#text": "text" } o.tag["@name" ] o.tag["#text"] 5 <tag> <a>text</a> <b>text</b> </tag> "tag": { "a": "text", "b": "text" } o.tag.a o.tag.b 6 <tag> <a>text</a> <a>text</a> </tag> "tag": { "a": ["text", "text"] } o.tag.a[0] o.tag.a[1] 7 <tag> text <a>text</a> </tag> "tag": { "#text": "text", "a": "text" } o.tag["#text"] o.tag.a
  • 94. What is REST 94 •Is an architecture style for designing networked applications focused on a system's resources (including how resource states are addressed and transferred) •REST stands for Representational State Transfer •REST relies on a stateless, client-server, cacheable communications protocol (HTTP is used) •REST is platform independent •REST is language independent
  • 95. REST as Lightweight Web Services 95 •REST is a lightweight alternative to mechanisms like RPC (Remote Procedure Calls) and Web Services (SOAP, WSDL, etc.) •REST uses HTTP uniform interface (POST, GET, PUT, DELETE) for all four CRUD (Create/Read/Update/Delete) operations • E.g. GET to retrieve (read) simple information  GET /employees/John HTTP/1.1  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
  • 96. REST as Lightweight Web Services 96 • Examples of CRUD operations made on a RESTful API • Create with HTTP POST  POST /employee HTTP/1.1  Host: myserver.com  Content-Type:application/xml <?xml version="1.0"?> <employee> <firstName>John</firstName> <lastName>Doe</lastName> </employee> • Read with HTTP GET  GET /employee/John HTTP/1.1  Host: myserver.com  Content-Type: application/xml • Output • A new employee entry is created with firstName = John and lastName = Doe • Reads the employee entry <?xml version="1.0"?> <employee> <firstName>John</firstName> <lastName>Doe</lastName> </employee>
  • 97. REST as Lightweight Web Services 97 • Examples of CRUD operations made on a RESTful API • Update over HTTP PUT  PUT /employee/John HTTP/1.1  Host: myserver.com  Content-Type: application/xml <?xml version="1.0"?> <employee> <firstName>Bob</firstName> </employee> • Delete with HTTP DELETE  DELETE /employee HTTP/1.1  Host: myserver.com  Content-Type:application/xml <?xml version="1.0"?> <employee> <firstName>John</firstName> <lastName>Doe</lastName> </employee> • Output • Updates the John Doe employee with firstName to be Bob => the new entry will be <?xml version="1.0"?> <employee> <firstName>Bob</firstName> <lastName>Doe</lastName> </employee> • Deletes the John Doe employee
  • 98. REST vs SOAP 98 • 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 and not dynamic in nature. • 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-based implementation is simple compared to SOAP.
  • 99. REST vs SOAP 99 •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, WS- Addressing
  • 100. What is WADL 100 • 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
  • 101. WADL Elements 101 • WSDL The service is described using a set of resource 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 specific HTTP headers that are required • The response describes the representation of the service's response, as well as any fault information, to deal with errors.
  • 102. WADL application element 102 •The application element forms the root of a WADL description and contains the following: • Zero or more doc elements • An optional grammars element • Zero or more resources elements • Zero or more of the following: • resource_type elements • method elements • representation elements • param elements
  • 103. WADL documentation element (doc) 103 •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 distinct values for their xml:lang attribute. • 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
  • 104. WADL grammars element 104 •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 •It is permissible to include multiple definitions of a particular format: such definitions are assumed to be equivalent and consumers of a WADL description are free to choose amongst the alternatives or even combine them if they support that capability. • 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.
  • 105. WADL resource element 105 •A resource element contains the following child elements: • Zero or more doc elements • Zero or more param elements with one of the following values for its style attribute: • Template, Query, Matrix , Header • Zero or more method elements • Zero or more resource elements that describe sub-resources
  • 106. WADL method element 106 •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.
  • 107. WADL method element 107 • 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 and will typically have different input data. • A method element has the following child elements: • doc - Zero or more doc elements • request - Describes the input to the method as a collection of parameters and an optional resource representation • response - Zero or more response elements that describe the possible outputs of the method
  • 108. WADL Example (Yahoo News Search) 108 <application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://wadl.dev.java.net/2009/02 wadl.xsd" xmlns:tns="urn:yahoo:yn" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:yn="urn:yahoo:yn" xmlns:ya="urn:yahoo:api" xmlns="http://wadl.dev.java.net/2009/02"> <grammars> <include href="NewsSearchResponse.xsd"/> <include href="Error.xsd"/> </grammars> <resources base="http://api.search.yahoo.com/NewsSearchService/V1/"> <resource path="newsSearch"> <method name="GET" id="search"> <request> <param name="appid" type="xsd:string" style="query" required="true"/> <param name="query" type="xsd:string" style="query" required="true"/> <param name="type" style="query" default="all"> <option value="all"/> <option value="any"/> <option value="phrase"/> </param>
  • 109. WADL Example (Yahoo News Search) 109 <param name="results" style="query" type="xsd:int" default="10"/> <param name="start" style="query" type="xsd:int" default="1"/> <param name="sort" style="query" default="rank"> <option value="rank"/> <option value="date"/> </param> <param name="language" style="query" type="xsd:string"/> </request> <response status="200"> <representation mediaType="application/xml" element="yn:ResultSet"/> </response> <response status="400"> <representation mediaType="application/xml" element="ya:Error"/> </response> </method> </resource> </resources> </application>
  • 110. Testing with SoapUI 110 • Create a SoapUI Project • Right click on the project node and select New SoapUI Project.
  • 111. Functional Testing 111 • In the New SoapUI Project dialog enter a project name (i.e. Country_info) and click OK. • Right click on the project node and select Add WSDL.
  • 112. Functional Testing 112 • The Add WSDL dialog is now open • Enter http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso?WSDL. • Click OK.
  • 113. Functional Testing 113 • Now see that the WSDL was successfully added to the project by seeing the operations in the Web Service in the navigatorEnter
  • 114. Functional Testing 114 • Create a request from your WSDL • Click on the plus sign next to the web service in the navigator to expand. • Double click on the request. • You now have to enter your data manually in the code editor as shown below. Replace “?” with “RO” (without quotes)
  • 115. Functional Testing 115 • Run a request to the Web Service • Click on the green arrow head sign to submit the request.
  • 116. Functional Testing 116 • Receive response • On the right side of the window the response will be displayed.
  • 117. Functional Testing 117 • Run an invalid request to the Web Service. • Introduce a wrong country code (like “ZZ”). • Click on the green arrow head sign to submit the request. • The response of the Web Service will indicate that the country was not found. • After seeing the result, correct the input data.
  • 118. Functional Testing 118 • Create a Test Case from a request. • In the request editor, select Add This Request to TestCase.
  • 119. Functional Testing 119 • 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.
  • 120. Functional Testing 120 • Next step: • The dialog box Add Request to TestCase will appear. Click OK.
  • 121. Functional Testing 121 • 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.
  • 122. Functional Testing 122 • Add an Assertion to the test: • 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. • Examples of assertions that is possible in SoapUI are: • 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
  • 123. Functional Testing 123 • Close all windows you have open in SoapUI before starting: • 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.
  • 124. Functional Testing 124 • Next step: • Select Response SLA from the Add Assertion menu. • 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.
  • 125. Functional Testing 125 • 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.
  • 126. Functional Testing 126 • Validate response with XPath Match: • Select XPath Match from the Add Assertion menu.
  • 127. Functional Testing 127 • Validate response with XPath Match: • 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
  • 128. Functional Testing 128 • 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.
  • 129. Service Mocking 129 • “Service Mocking, or simulation, is the practice of creating a facsimile environment that works similar to the environment you’re facsimileing”. • When to use it: You should use mocks when you can’t use the real thing • Advantages: • You can create tests in advance. • Teams can work in parallel. • You can create proof of concepts or demos. • You can isolate systems. • You can write test for resource not accessible. • Mock can be delivered to the customer. • Disadvantages: • You have to do Double work. • Deployment constraints. • It’s not live is it?
  • 130. Service Mocking 130 • Start a new SoapUI project using the following wsdl: http://www.webservicex.net/CurrencyConvertor.asmx?WSDL • Click OK button.
  • 131. Service Mocking 131 • Right-click on one of the SOAP interfaces and select Generate MockService.
  • 132. Service Mocking 132 • 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
  • 133. Service Mocking 133 • 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.
  • 134. Service Mocking 134 • 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
  • 135. Service Mocking 135 • 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
  • 136. Service Mocking 136 • 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.
  • 137. Service Mocking 137 • Now in the MockResponse editor, Click the Button Create Request. • This will prompt you to open one of the existing requests for its operation in your project. • You will also need to give it a name.
  • 138. Service Mocking 138 • 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.
  • 139. Service Mocking 139 • Let's continue by making the created MockResponse a bit more dynamic by changing the dispatch and by Groovy scripting. • First we’ll create a second MockResponse. • Give it a Groovy Name
  • 140. Service Mocking 140 • 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.
  • 141. Service Mocking 141 • In the ConversionRateResult element enter the following: ${rate} This is called a Property expansion and it's a very powerful feature in SoapUI. By inserting a property expansion in any element you can then fill the element programmatically. Basically it tells SoapUI to use the current value of property rate. • Now that we have written a script and the random results will be inserted into the response.