2. Content
• What
is
SOA
and
Web
Services?
• W3C
XML
Standards
– XML,
Schema
• JAXB
Java
– Conver;ng
objects
to
xml
and
vice-‐versa
• W3C
Web
Service
– SOAP,
WSDL,
UDDI
• SAAJ
• JAX-‐WS
• Implemen?ng
REST
Service
using
Java
3. Business
Needs
Flexibility
• Hook
up
new
partners
and
acquisi;ons
• Enable
reuse
of
exis;ng
systems
and
business
logic
• Integrate
• Flexibility
4. Technical
Problems
• Different
languages
and
plaRorms
• Integra;on
is
hard
and
costly
• Scalability
• Security
5. Solu;on:
Web
Service
• Web
Service
is
a
method
of
communica;on
of
two
electronic
devices
over
a
network
• SoTware
func;on
provided
at
a
network
address
over
a
Web
• There
is
no
"official
specifica;on"
for
web
services
• Possible
to
iden?fy
two
major
classes
1. REST-‐complient
Web
Services
2. SOAP
"Big"
Web
Services
6. What
is
Web
Service?
• Web
Service
is
request
/
response
mechanism
that
allows
client
to
access
or
modify
data
– It's
machine
to
machine,
not
intented
for
the
user
• User
uses
web
page
via
URL
and
receives
HTML
that
the
browser
understands
– http://openweathermap.org/find?q=Tampere
• Computer
app
uses
web
service
via
URL
and
receives
usually
either
XML
or
JSON
– http://api.openweathermap.org/data/2.5/weather?
q=Tampere
7. Web
Service
• Is
available
over
the
Internet
or
private
Intranet
• Uses
usually
either
XML
or
JSON
– XML
is
heavily
used
in
in
SOAP
Web
Services
• Is
not
?ed
to
any
opera?ng
system
or
programming
language
• Is
self-‐describing
and
discoverable
9. What
is
XML?
• SOAP
Web
Services
uses
XML,
we
need
to
learn
this
first!
• eXtensible
Markup
Language,
is
a
specifica;on
for
crea;ng
custom
markup
languages
• W3C
Recommenda;on
• Primary
purpose
is
to
help
computers
to
share
data
• XML
is
meta-‐language.
This
means
that
you
use
it
for
crea;ng
languages.
• XML
is
an
extensive
concept.
10. XML
Document
• Every
XML-‐document
is
text-‐based
• =>
sharing
data
between
different
computers!
• =>
sharing
data
in
Internet!
• =>
plaRorm
independence!
11. Binary
vs.
Text
• Problems
with
Binary
format
– PlaRorm
depence
– Firewalls
– Hard
to
debug
– Inspec;ng
the
file
can
be
hard
• Since
XML
is
text-‐based,
it
does
not
have
the
problems
men;oned
above.
• What
are
the
disadvantages
in
text
format?
12. XML
Doc
Advantages
• Easy
data
sharing,
text
documents
are
readable
between
any
device.
• Documents
can
be
modified
with
any
text
editor.
• Possible
to
understand
the
contents
of
the
xml-‐
document
just
by
looking
at
it
with
text
editor.
• Easy
to
manipulate
via
programming
languages
• Two
levels
of
correctness:
Well
formed
and
Valid.
13. .doc
–
file
format
Windows
MS
Word
2000
Mac
OS
X
Since
.doc
is
closed
binary-‐format,
there
are
very
few
alterna:ves
for
word
processors
that
fully
support
the
doc
–
file
format
0101011010101010001010
1010101110101010001011
1010101110101010110101
1110101010101010101010
14. .docx
–
file
format
(Office
Open
XML)
Windows
MS
Word
2007
Mac
OS
X
Hopefully
in
the
future
there
will
be
loads
of
free
programs
that
support
this
new
open
and
easy
access
file
format
<xml>
<heading1>title</heading1>
.
.
</xml>
Now
the
format
is
open
and
it's
much
easier
to
access
15. SGML
vs.
XML
SGML:
Standard
Generalized
Markup
Language
Meta
language
XML
Meta
language
(subset
of
SGML)
HTML
(.html)
XHTML
(.xhtml)
MathML
(.mml)
OOXML
(.docx)
16. XML
–
Meta
Language
• XML
is
meta
language,
which
you
can
use
to
create
your
own
markup
languages.
• There
are
several
XML
Markup
Languages
made
for
different
purposes
• All
the
languages
have
common
xml-‐rules
• Languages:
XHTML,
OOXML,
Open
Document,
RSS,
SVG,
SOAP,
SMIL,
MathML...
• List:
– http://en.wikipedia.org/wiki/List_of_XML_markup_languages
17. XHTML
-‐
Example
<?xml version="1.0"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Minimal XHTML 1.0 Document</title>
</head>
<body>
<p>This is a minimal <a href="http://www.w3.org/TR/xhtml1/">XHTML 1.0</a>
document.</p>
</body>
</html>
20. RSS
2.0
-‐
Example
<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title>W3Schools Home Page</title>
<link>http://www.w3schools.com</link>
<description>Free web building tutorials</description>
<item>
<title>RSS Tutorial</title>
<link>http://www.w3schools.com/rss</link>
<description>New RSS tutorial on W3Schools</description>
</item>
<item>
<title>XML Tutorial</title>
<link>http://www.w3schools.com/xml</link>
<description>New XML tutorial on W3Schools</description>
</item>
</channel>
</rss>
21. WELL
FORMED
XML
-‐
DOCUMENT
Rules
that
Apply
to
Every
XML-‐Document
22. Correctness
• There
are
two
levels
of
correctness
of
an
XML
document:
1. Well-‐formed.
A
well-‐formed
document
conforms
to
all
of
XML's
syntax
rules.
2. Valid.
A
valid
document
addi;onally
conforms
to
some
seman;c
rules.
• Let's
first
look
at
the
XML's
syntax
rules
(1).
23. Simple
Generic
XML
Example
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<presentation>
<slide number="1">
<name>Introduction to XML</name>
<contents>XML is ...</contents>
</slide>
</presentation>
24. XML-‐Declara;on
• XML-‐declara;on
is
op?onal
in
XML
1.0,
mandatory
in
1.1.
– Recommenda;on:
use
it.
• Version:
1.0
or
1.1
• Encoding:
character
encoding,
default
uR-‐8
• Standalone:
– is
the
xml-‐document
linked
to
external
markup
declara;on
– yes:
no
external
markup
declara;ons
– no:
can
have
external
markup
declara;on
(open
issue..)
– default:
"no"
25. Comparing
Declara;ons
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<presentation>
<slide>
<name>Introduction to XML</name>
<contents>XML is ...</contents>
</slide>
</presentation>
<?xml version="1.0"?>
<presentation>
<slide>
<name>Introduction to XML</name>
<contents>XML is ...</contents>
</slide>
</presentation>
Same
Declara;on
26. Element
vs.
Tag
vs.
Alribute
• Element
consists
of
start
tag,
op:onal
content
and
an
end
tag:
– <name>Introduction to XML</name>
• Start
tag
– <name>
• Content
– Introduc;on
to
XML
• End
tag
– </name>
• Start
tag
may
have
a[ribute
– <slide number="1">
27. Rules
about
Elements
• Only
one
root
-‐
element
• Every
element
contains
star;ng
tag
and
an
ending
tag
• Content
is
op;onal:
Empty
element
– <x></x> <!-- same as -->
– <x/>
• Tag
–
names
are
case-‐sensi;ve:
– <X></x> <!-- Error -->
• Elements
must
be
ended
with
the
end
tag
in
correct
order:
– <p><i>problem here</p></i> <!– Error à
28. Rules
about
Alributes
• XML
elements
can
have
alributes
in
the
start
tag.
• Alributes
must
be
quoted:
– <person gender="female">
– <person gender='female'>
– <gangster name='George "Shotgun" Ziegler'>
– <gangster name="George "Shotgun" Ziegler">
29. Naming
Tags
• Names
can
contain
lelers,
numbers,
and
other
characters
• Names
must
not
start
with
a
number
or
punctua;on
character
• Names
must
not
start
with
the
lelers
xml
(or
XML,
or
Xml,
etc)
• Names
cannot
contain
spaces
30. Well-‐Formed
XML
• XML
document
is
well-‐formed
if
it
follows
the
syntax
rules.
• XML
document
must
be
well-‐formed!
– it's
not
an
xml-‐document,
if
it
does
not
follow
the
rules..
31. Is
this
Well-‐Formed
XML
Document?
<?xml version="1.0"?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Minimal XHTML 1.0 Document</title>
</head>
<body>
<p>This is a minimal <a href="http://www.w3.org/TR/xhtml1/">XHTML 1.0</a>
document.</p>
</body>
</html>
32. Is
this
Well-‐Formed
XML
Document?
<?xml version="1.0"?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Minimal XHTML 1.0 Document</title>
</head>
<body>
<jorma>This is a minimal <a href="http://www.w3.org/TR/xhtml1/">XHTML 1.0</a>
document.</jorma>
</body>
</html>
35. Valid
XML
• XML
document
is
valid
if
– 1)
It
is
well
formed
AND
– 2)
It
follows
some
seman;c
rules
• XML
document
is
usually
linked
to
an
external
file,
that
has
seman;c
rules
for
the
document.
– The
file
can
be
dtd
(.dtd)
or
schema
(.xsd)
• Seman;c
rules?
– Name
of
tags,
order
of
elements
36. DTD
Linking
<?xml version="1.0"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Minimal XHTML 1.0 Document</title>
</head>
<body>
<p>This is a minimal <a href="http://www.w3.org/TR/xhtml1/">XHTML 1.0</a>
document.</p>
</body>
</html>
Rules
for
XHTML
elements
(order,
names,
etc)
37. DTD
Linking
Defines
the
structure,
tag
names
and
order
for
all
xhtml
-‐
documents
W3C
has
created
XML-‐language
"XHTML"
by
defining
it's
rules
in
DTD.
38. Is
this
valid
XML
Document?
<?xml version="1.0"?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Minimal XHTML 1.0 Document</title>
</head>
<body>
<jorma>This is a minimal <a href="http://www.w3.org/TR/xhtml1/">XHTML 1.0</
a>
document.</jorma>
</body>
</html>
1. There
is
no
DTD!
What
language
is
this?
MathML?
SVG?
XHTML?
2. Assuming
this
is
XHTML,
what
version
of
XHTML?
Transi;onal?
Strict?
3. Assuming
this
is
XHTML
strict,
does
"jorma"
–
tag
belong
to
XHTML
Language?
39. Invalid
XHTML-‐document
<?xml version="1.0"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Minimal XHTML 1.0 Document</title>
</head>
<body>
<jorma>This is a minimal <a href="http://www.w3.org/TR/xhtml1/">XHTML 1.0</
a>
document.</jorma>
</body>
</html>
41. Invalid
XHTML
in
Browser?
May
work...
or
not.
Browser
tries
to
detect
the
errors
and
tries
to
understand
them.
If
it
works
with
one
browser,
are
you
certain
that
it
works
with
all
other
browsers?
And
with
all
the
versions
with
the
browsers?
What
about
browsers
in
handheld
devices?
And
it
might
work
now,
but
what
about
future?
How
will
Firefox
5.0
handle
incorrect
web
pages?
42. Invalid
XML
in
General
• Because
of
HTML
heritage,
browsers
try
to
understand
invalid
XHTML-‐pages
• This
is
not
the
case
in
other
XML-‐languages.
• In
general,
if
XML-‐document
is
invalid,
the
processing
of
the
document
is
cancelled.
47. Result
Nope..
It
does
not
try
to
understand
the
errors
in
the
document.
It
does
not
handle
the
document
at
all.
48. Benefits
of
WF
and
Valid
• XML
has
strict
rules
for
WF
and
Valid
• If
applica;on
tries
to
manipulate
xml-‐
document
it
does
not
have
to
try
to
understand
the
possible
errors
in
the
document
• This
means
that
handling
xml-‐files
via
programming
language
is
much
easier
– If
the
document
is
correctly
formed,
manipulate
it
– If
it
isn't
display
error
54. XML
Namespaces
• Schema
uses
namespaces
• The
idea
behing
XML
namespaces
is
to
avoid
element
name
conflicts.
• Example
of
name
conflict
(w3schools.com)
<table>
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
<table>
<name>African
Coffee
Table</name>
<width>80</width>
<length>120</length>
</table>
Same
tag-‐name,
different
content
and
meaning!
55. Solving
Name
Conflict
<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>
Prefix
h
has
xhtml-‐related
elements
and
prefix
f
has
furniture-‐related
elements
56. xmlns
-‐
alributes
• When
using
prefixes
in
XML,
a
so-‐called
namespace
for
the
prefix
must
be
defined.
• The
namespace
is
defined
by
the
xmlns
alribute
in
the
start
tag
of
an
element.
59. Namespace
name
• The
name
of
namespace
should
be
unique:
<h:table xmlns:h="http://www.w3.org/TR/html4/">
• It
is
just
a
string,
but
it
should
be
declared
as
URI.
• Using
URI
reduces
the
possibility
of
different
namespaces
using
duplicate
iden?fiers.
60. Example:
An
XHTML
+
MathML
+
SVG
Profile
• An
XHTML+MathML+SVG
profile
is
a
profile
that
combines
XHTML
1.1,
MathML
2.0
and
SVG
1.1
together.
• This
profile
enables
mixing
XHTML,
MathML
and
SVG
in
the
same
document
using
XML
namespaces
mechanism.
61. <?xml version="1.0"?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN"
"http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg-flat.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:svg = "http://www.w3.org/2000/svg">
<head>
<title>Example of XHTML, SVG and MathML</title>
</head>
<body>
<h2>MathML</h2>
<p>
<math xmlns="http://www.w3.org/1998/Math/MathML">
<mfrac>
<mi>a</mi>
<mi>b</mi>
</mfrac>
</math>
</p>
<h2>SVG</h2>
<p>
<svg:svg width="50px" height="50px">
<svg:circle cx="25px" cy="25px" r="20px" fill="green"/>
</svg:svg>
</p>
</body>
</html>
63. XML
Schema
(W3C)
• Language
for
defining
set
of
rules
for
XML
–
documents.
• W3C
Recommenda;on
(2001)
• More
specific
than
DTD
– Datatypes!
• Is
XML-‐language
and
it
uses
xml
namespaces
64. Schema
vs.
DTD
(W3Schools.com)
• XML
Schemas
are
extensible
to
future
addi;ons
• XML
Schemas
are
richer
and
more
powerful
than
DTDs
• XML
Schemas
are
wrilen
in
XML
• XML
Schemas
support
data
types
• XML
Schemas
support
namespaces
65. DTD
Linking
Defines
the
structure,
tag
names
and
order
for
all
xhtml
-‐
documents
W3C
has
created
XML-‐language
"XHTML"
by
defining
it's
rules
in
DTD.
66. DTD
Linking
Defines
the
structure,
tag
names
and
order
for
all
"book"-‐
documents
TAMK
has
created
XML-‐language
"Book"
by
defining
it's
rules
in
DTD.
67. Schema
Linking
Defines
the
structure,
tag
names
and
order
for
all
"book"-‐
documents
TAMK
has
created
XML-‐language
"Book"
by
defining
it's
rules
in
DTD.
68. Linking?
• The
basic
idea
with
linking
to
Schema:
<?xml version="1.0"?>
<root schemaLocation="note.xsd">
<foo>...</foo>
</root>
• The
problem
with
this
is
that
now
it
is
set
that
alribute
"schemaLoca;on"
is
part
of
your
XML-‐language
69. Linking
and
Namespace
Usage
• Linking
with
namespace
<?xml version="1.0"?>
<root
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="note.xsd">
<foo>...</foo>
</root>
• Now
the
"schemaLoca;on"
–
alribute
is
in
it's
own
namespaces
(xsi)
and
does
not
belong
to
the
"main"
language.
72. The
Basics:
Element
• You
define
the
name
for
the
elements
by
using
element-‐element.
J
– <element name="foo" type="bar" />
• Type?
– 44
Built-‐in
schema
datatypes
– string,
double,
;me,
date,
etc.
– See
all
the
datatypes
74. minOccurs
and
maxOccurs
• The
amount
of
elements
– In
DTD:
*,
?,
+
– In
Schema:
minOccurs,
maxOccurs
• Example
<xsd:element name="date" type="xsd:date"
minOccurs="1" maxOccurs="2" />
• Default
and
special
values
– default
minOccurs:
1
– default
maxOccurs:
same
as
minOccurs
– maxOccurs="unbounded"
:
unlimited
75. Defining
new
Datatypes
• If
the
the
built-‐in
datatypes
are
not
enough,
you
can
build
your
own
datatypes.
• This
does
not
necessarily
work:
– <xsd:element name="grade" type="xsd:integer" />
• There
are
two
ways
of
specifying
your
own
datatype
– Named
Data
Type
– Anonymous
Data
Type
76. 1)
Named
Data
Type
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="grade" type="grade_type" />
<xsd:simpleType name="grade_type">
<xsd:restriction base="xsd:positiveInteger">
<xsd:minInclusive value="4"/>
<xsd:maxInclusive value="10"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>
82. Structure
of
the
XML-‐file
• It's
possible
to
define
the
structure
of
the
XML-‐file
using
complexType
• If
element
A
has
child-‐elements,
then
element
A's
type
is
complexType
83. SimpleType
vs.
ComplexType
• SimpleType
– <grade>7</grade>
– Since
grade does
not
hold
other
child
–
elements,
grade's
type
is
simpleType
• ComplexType
– <students><student>Jack</student></students>
– Since
student does
hold
child
–
element(s),
student's
type
is
complexType
92. Order
of
the
elements
• Sequence:
Elements
appear
in
same
order
than
in
Schema
• All:
Elements
can
appear
in
any
order
• Choice:
One
element
can
appear
from
the
choice-‐list
<xsd:element name="person">
<xsd:complexType>
<xsd:choice>
<xsd:element name="employee" type="employee"/>
<xsd:element name="member" type="member"/>
</xsd:choice>
</xsd:complexType>
</xsd:element>
97. XML
and
Java
• How
do
you
read
and
write
XML
from
Java?
– Java
API
for
XML
Processing
(JAXP)
• Simple
API
for
XML
(SAX)
– Event
driven,
only
read
• DOM
Object
Model
(DOM)
– Creates
tree
object
in
memory,
read
and
manipulate
– Java
Architecture
for
XML
Binding
(JAXB)
• Unmarshal
xml
file
to
Java
objects
• Marshal
Java
objects
to
xml
file
98. Web
Server
Server.java
Book.java
class Book { .. }
class ClientApp {
public static void main(String [] args) {
Book book = new Book("Tuntematon Sotilas");
sendToServer(book);
}
}
<book>
<title>
Java 8 new features
</title>
</book>
Client
Computer
ClientApp.java
Book.java
The image cannot be displayed. Your computer
may not have enough memory to open the image,
or the image may have been corrupted. Restart
your computer, and then open the file again. If the
red x still appears, you may have to delete the
image and then insert it again.
100. JAXB
• Java
Architecture
for
XML
Binding
(JAXB)
allows
Java
developers
– marshal
Java
objects
to
XML
– unmarshal
XML
back
to
Java
objects
• JAXB
is
part
of
Java
SE
– Implementa;on
is
done
by
using
annota?ons
– Package:
javax.xml.bind.annotation.*;
• @XmlRootElement, @XmlElement
• Separate
tools
available
– xjc
-‐>
schema
to
classes
– schemagen
-‐>
classes
to
schema
101. Marshal:
Person.java
@XmlType( propOrder = { "name", "age"} )
@XmlRootElement( name = "Person" )
public class Person {
private String name;
private int age;
private int id;
@XmlAttribute(name = "id", required = true)
public void setId(int id) {
this.id = id;
}
@XmlElement(name = "age")
public void setAge(int age) {
this.age = age;
}
@XmlElement(name = "name")
public void setName(String name) {
this.name = name;
}
...
}
102. Marshal:
Person.java
public class Main {
public static void main(String[] args) throws Exception {
Person person = new Person("Jack", 28, 123);
JAXBContext jaxbContext = JAXBContext.newInstance( Person.class );
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
jaxbMarshaller.marshal(person, System.out);
/*
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Person id="123">
<name>Jack</name>
<age>28</age>
</Person>
*/
}
}
103. List
of
Persons
@XmlRootElement( name = "persons" )
public class Persons {
List<Person> persons;
@XmlElement( name = "person" )
public void setPersons(List<Person> persons) {
this.persons = persons;
}
public List<Person> getPersons() {
return this.persons;
}
}
104. Marshalling
a
List
public class Main {
public static void main(String[] args) throws Exception {
ArrayList<Person> personList = new ArrayList();
personList.add(new Person("jack", 28, 1));
personList.add(new Person("tina", 29, 2));
personList.add(new Person("john", 45, 3));
personList.add(new Person("samantha", 19, 4));
Persons persons = new Persons();
persons.setPersons(personList);
JAXBContext jaxbContext = JAXBContext.newInstance(Persons.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(persons, System.out);
}
}
109. From
Schema
to
Classes
> xjc schema1.xsd
parsing a schema...
compiling a schema...
generated/ObjectFactory.java
generated/Person.java
generated/Persons.java
110. ObjectFactory
• Some;mes
Schema
is
not
mappable
to
POJOs
(Plain
Old
Java
Objects)
• In
these
cases
JAXBElement
wrapper
objects
are
necessary
to
provide
addi;onal
informa;on
• The
xjc
generated
object
model
uses
JAXBElement
and
therefore
you
need
to
way
to
construct
these
JAXBElement
objects
– ObjectFactory
is
for
that
• When
using
the
ObjectFactory,
unmarshaling
is
a
bit
complicated
...
111. ...
Unmarshal
ObjectFactory
import java.io.*;
import javax.xml.bind.*;
import generated.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File( "/path/to/persons.xml" );
JAXBContext jaxbContext = JAXBContext.newInstance( ObjectFactory.class );
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
JAXBElement<Persons> jaxbElement = (JAXBElement<Persons>) jaxbUnmarshaller.unmarshal( file );
Persons persons = jaxbElement.getValue();
System.out.println( persons.getPerson().get(0).getName() ); // jack
}
}
112. Add
Root
Element
if
ObjectFactory
unneccessary
...
// Add import
import javax.xml.bind.annotation.XmlRootElement;
// Add root element
@XmlRootElement( name = "persons" )
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "persons", propOrder = {
"person"
})
public class Persons {
protected List<Person> person;
...
113. Adding
Root
Element
import java.io.*;
import javax.xml.bind.*;
import generated.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File( "/path/to/persons.xml" );
JAXBContext jaxbContext = JAXBContext.newInstance( Persons.class );
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Persons persons = (Persons) jaxbUnmarshaller.unmarshal( file );
List<Person> listOfPersons = persons.getPerson();
System.out.println( listOfPersons.get(0).getName() ); // jack
}
}
114. Marshal
import javax.xml.bind.*;
import generated.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Person p1 = new Person();
p1.setName("jack");
p1.setAge(28);
p1.setId(3);
Person p2 = new Person();
p1.setName("john");
p1.setAge(45);
p1.setId(4);
Persons persons = new Persons();
List<Person> listOfPersons = persons.getPerson();
listOfPersons.add(p1);
listOfPersons.add(p2);
JAXBContext jaxbContext = JAXBContext.newInstance( Persons.class );
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(persons, System.out);
}
}
117. Web
Service
• Web
Service
is
a
method
of
communica;on
of
two
electronic
devices
over
a
network
• SoTware
func;on
provided
at
a
network
address
over
a
Web
• There
is
no
"official
specifica;on"
for
web
services
• Possible
to
iden?fy
two
major
classes
1. REST-‐complient
Web
Services
2. SOAP
"Big"
Web
Services
118. Web
Services
and
XML
• WSDL
– XML
file
that
describes
the
service
• (
UDDI
)
– Directory
of
wsdls,
legacy
stuff..
• SOAP
– Simple
Object
Access
Protocol
– XML
Format
for
sending
messages
119. WSDL
• Web
Services
Descrip;on
Language
(WSDL)
describes
a
web
service
– Specifies
the
loca;on
of
the
service
– Specifies
the
opera;ons
of
the
service
• Is
wrilen
in
XML
and
it's
W3C
recommenda;on
• Descrip;on
how
to
the
service
is
called,
what
parameter
it
expects,
what
data
structures
it
returns.
120. Descrip;on
• WSDL
describes
services
as
collec;on
of
Ports
(wsdl
1.1)
or
Endpoints
(wsdl
2.0)
– Defines
the
address
or
connec;on
point
to
web
service
-‐>
HTTP
URL
string
124. Genera;ng
Simple
Java
Client
• Java
6
includes
wsimport
as
part
of
JAX-‐WS
• Generates
all
necessary
classes
to
contact
the
service!
• Usage
– wsimport -keep -verbose
http://www.webservicex.net/stockquote.asmx?WSDL
125. Client
import net.webservicex.*;
class Main {
public static void main(String[] args) throws Exception {
StockQuote sq = new StockQuote();
StockQuoteSoap soap = sq.getStockQuoteSoap();
System.out.println( soap.getQuote("aapl") );
}
}
126. SOAP
• SOAP,
simple
object
access
protocol
• Exchanging
informa;on
between
web
services
• Mandatory
building
blocks:
– Envelope
• Iden;fies
the
xml
document
as
soap
– Body
• Call
and
response
informa;on
• Usually
SOAP
envelope
is
transferred
via
HTTP
127. HTTP
Request
POST
POST /test/page.html HTTP/1.1
Host: server.com
name1=value1
128. HTTP
Request
GET
POST /test/page.php?name1=value HTTP/1.1
Host: server.com
133. Soap
1.2
Server
Response
in
HTTP
HTTP/1.1 200 OK
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<GetQuoteResponse xmlns="http://www.webserviceX.NET/">
<GetQuoteResult>string</GetQuoteResult>
</GetQuoteResponse>
</soap12:Body>
</soap12:Envelope>
134. Disadvantages
• XML
can
slow
things
down,
because
XML
files
can
be
big
• SOAP
Web
Services
can
be
tricky
to
implement
• REST
Architecture
is
replacing
SOAP
Web
Services?
136. SOAP
Alachment
API
for
Java
• SAAJ:
Implement
directly
SOAP
handling
in
Java
• Read,
Write
and
Send
SOAP
• Support
for
SOAP
1.1
and
1.2
• Is
bundled
with
Java
SE
– javax.xml.soap.*
145. Web
Service
on
Server
• To
create
providing
Web
Service,
you
need
some
server:
– Apache
Tomcat
– Glassfish
• To
create
SAAJ
Web
Service,
create
regular
servlet
and
use
the
SAAJ
API
to
create
a
SOAP
message
response
146. GlassFish
• Open
Source
applica?on
server
project
started
by
Sun
Microsystems
for
Java
EE
• Reference
implementa;on
of
Java
EE
• Supports
– EJB,
JavaServer
Faces
/
Pages,
RMI,
Servlets
etc..
• Allows
developers
to
create
enterprise
apps
that
are
portable
and
scalable
• Download
– https://glassfish.java.net/download.html
147. Install
• Fetch
the
.zip,
unzip
it
and
place
in
some
directory:
c:glassfish
• Put
c:glassfishglassfish4bin to
path
• Start
– asadmin start-domain
• Mac
OS
X:
sudo asadmin start-domain
• Stop
– asadmin stop-domain domain1
• Open
admin
–
console
– http://localhost:4848/common/index.jsf
148. WAR
• WAR
(Web
Applica;on
Archive)
is
a
JAR
file
to
be
used
to
distribute
collec;on
of
java
servlets,
xmls,
htmls
etc.
• Must
contain
– /WEB-INF/web.xml
– /WEB-INF/classes/SomeClass.class
• web.xml
defines
the
structure
of
your
app
150. HelloServlet.java
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
public class HelloServlet extends HttpServlet {
public void doGet (HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
PrintWriter out = res.getWriter();
out.println("Hello, world!");
out.close();
}
}
151. Compile
• Compile
using
Java
EE
libraries
• Add
needed
.jar
to
classpath
– classpath
=
where
to
find
third-‐party
classes
• You
can
classpath
when
compiling
– javac -classpath ".;/path/to/glassfish4/
glassfish/modules/javax.servlet-api.jar"
HelloServlet.java
• Or
add
all
Java
EE
libraries
to
classpath
for
easier
access
– set CLASSPATH = /path/to/glassfish4/glassfish/
lib/*;/path/to/glassfish4/glassfish/modules/*
152. Create
war
• Once
you
have
– WEB-INF/web.xml
– WEB-INF/classes/HelloServlet.class
• Package
these
into
war
– jar -cf HelloServlet.war .
• Deploy
– asadmin deploy --force=true HelloServlet.war
• Test
on
Browser:
– http://localhost:8080/HelloServlet
• Test
in
CLI
using
CURL
– curl -X POST http://localhost:8080/HelloServlet
160. JAX-‐WS
• SAAJ
API
is
very
powerful
and
flexible
way
to
create
web
services
at
low
level
• Java
API
for
XML
Web
Services
(JAX-‐WS)
is
high-‐level
API
for
consuming
and
providing
Web
Services
• You
don't
have
to
know
XML,
WSDL
etc.
• En;re
XML
layer
is
hidden
from
developers
• Encapsulates
all
of
the
work
of
crea;ng
SOAP
messages.
• JAX-‐WS
is
built
on
top
of
SAAJ
and
it
uses
JAXB
for
binding
• It's
really
easy!
161. Client
using
JAX-‐WS
and
wsimport
• Generate
classes
from
WSDL
file
using
wsimport
– wsimport -verbose -extension -keep
http://www.webservicex.net/
stockquote.asmx?WSDL
• Create
client
that
uses
the
generated
class
files
• Compile
and
run
162. Client
import net.webservicex.*;
// javac Client.java
// java –classpath .:gen Client
class Client {
public static void main(String [] args) {
StockQuote service = new StockQuote();
StockQuoteSoap port = service.getStockQuoteSoap();
String xml = port.getQuote("aapl");
System.out.println(xml);
}
}
164. Requirements
• Service
endpoint
is
Java
interface
or
class
that
declares
methods
that
the
client
can
invoke
– Interface
is
not
required
• Class
must
be
annotated
with
javax.jws.WebService
• Methods
must
be
public
and
cannot
be
final
or
sta;c
165. Server
• You
can
deploy
your
web
service
to
glassfish
• Also
in
Java
6
you
can
use
javax.xml.ws.Endpoint
to
create
your
own
lightweight
hlp
server!
166. Define
Service
package mycompany;
import javax.jws.WebService;
@WebService
public class CircleFunctions {
public double getArea(double r) {
return java.lang.Math.PI * r * r;
}
}
167. Create
Server
import javax.xml.ws.Endpoint;
import mycompany.*;
class Server {
public static void main(String [] args) {
Endpoint.publish("http://localhost:9999/circlefunctions", new
CircleFunctions());
}
}
168. Client
// wsimport -verbose -extension -keep http://localhost:9999/circlefunctions?wsdl
import mycompany.*;
class Client {
public static void main(String [] args) {
CircleFunctionsService service = new CircleFunctionsService();
CircleFunctions port = service.getCircleFunctionsPort();
double area = port.getArea(5.5);
System.out.println(area);
}
}
171. RESTful
Web
Services
• Representa;onal
State
Transfer
(REST)
is
architectural
style
with
uniform
interface
using
URIs
• Resources
are
manipulated
with
fixed
set
– create
(HTTP
PUT),
read
(HTTP
GET),
update
(HTTP
POST)
and
delete
(HTTP
DELETE)
• Resources
are
usually
either
XML
or
JSON
177. JAX-‐RS
2.0
• JAX-‐RS
(JSR
339)
is
a
framework/class
library
that
help
you
write
RESTful
apps
both
on
the
client
and
server
side
• Packages
– javax.ws.*
179. Client
import
javax.ws.rs.client.Client;
import
javax.ws.rs.client.ClientBuilder;
import
javax.ws.rs.client.Invocation;
import
javax.ws.rs.client.WebTarget;
import
javax.ws.rs.core.MediaType;
public
class
Main
{
public
static
void
main(String[]
args)
{
//
Build
a
new
client
instance.
Client
client
=
ClientBuilder.newClient();
//
Build
a
new
web
resource
target.
WebTarget
webTarget
=
client.target("http://www.thomas-‐bayer.com/sqlrest/CUSTOMER/0");
//
Start
building
a
request
to
the
targeted
web
resource.
Accepts
only
XML
Invocation.Builder
builder
=
webTarget.request(MediaType.APPLICATION_XML);
//
Create
HTTP
GET
invocation
Invocation
invocation
=
builder.buildGet();
//
Synchronously
invoke
the
request
and
receive
a
response
of
the
specified
type
back.
String
result
=
invocation.invoke(String.class);
System.out.println(result);
}
}
180. Client
and
unmarshal
XML
import
javax.ws.rs.client.Client;
import
javax.ws.rs.client.ClientBuilder;
import
javax.ws.rs.client.Invocation;
import
javax.ws.rs.client.WebTarget;
import
javax.ws.rs.core.MediaType;
public
class
Main
{
public
static
void
main(String[]
args)
{
//
Build
a
new
client
instance.
Client
client
=
ClientBuilder.newClient();
//
Build
a
new
web
resource
target.
WebTarget
webTarget
=
client.target("http://www.thomas-‐bayer.com/sqlrest/CUSTOMER/0");
//
Start
building
a
request
to
the
targeted
web
resource.
Accepts
only
XML
Invocation.Builder
builder
=
webTarget.request(MediaType.APPLICATION_XML);
//
Create
HTTP
GET
invocation
Invocation
invocation
=
builder.buildGet();
//
Synchronously
invoke
the
request
and
receive
a
response
of
the
specified
type
back.
Customer
result
=
invocation.invoke(Customer.class);
System.out.println(result.getFirstname());
}
}
181. Customer.java
@XmlRootElement(
name
=
"CUSTOMER"
)
public
class
Customer
{
private
String
firstname;
private
String
lastname;
private
String
street;
private
String
city;
private
int
id;
public
String
getFirstname()
{
return
firstname;
}
@XmlElement(name
=
"FIRSTNAME")
public
void
setFirstname(String
firstname)
{
this.firstname
=
firstname;
}
...
184. Root
Resource
Class
• Uses
annota;ons
to
simplify
development
of
REST
services
• Root
resource
classes
are
POJOs
that
are
annotated
with
@Path
or
a
request
method
designator:
– @GET, @PUT, @POST or @DELETE
185. HelloWorldResource
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;
// The Java class will be hosted at the URI path "/helloworld"
@Path("/helloworld")
public class HelloWorldResource {
// The Java method will process HTTP GET requests
@GET
// The Java method will produce content identified by the MIME Media
// type "text/plain"
@Produces("text/plain")
public String getClichedMessage() {
// Return some cliched textual content
return "Hello World";
}
}
186. App
Model
• JAX-‐RS
provides
deployment
agnos;c
class
Applica;on
for
declaring
root
resource
and
provider
classes
• Create
class
that
extends
the
Applica;on
class
187. Star;ng
Point
of
Your
App
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
// http://localhost:8080/RestProvider/rest/helloworld
@ApplicationPath("/rest")
public class MyApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
final Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(HelloWorldResource.class);
return classes;
}
}
189. Client.java
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Client {
private String firstName;
private String lastName;
private int id;
public Client() {}
public Client(String firstName, String lastName, int id) {
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
}
// getters and setters
...
}
190. ClientResource.java
// The Java class will be hosted at the URI path "/clients"
@Path("/clients")
public class ClientsResource {
// Holds client information
List<Client> clients;
public ClientsResource() {
// Populate the clients array in some way
}
// http://.../rest/clients
@GET
@Produces(MediaType.APPLICATION_XML)
public List<Client> getClients() {
// like magic, this produces a xml version of all clients!
return clients;
}
// http://.../rest/clients/1
@GET
@Produces(MediaType.APPLICATION_XML)
@Path("{id}")
public Client getClient(@PathParam("id") int id) {
// Find a client with the given id and return it
}
// using POST
// firstname: John
// lastname: Smith
// id: 99
// http://.../rest/clients/
@POST
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String newClient(@FormParam("id") int id,
@FormParam("firstname") String firstname,
@FormParam("lastname") String lastname) {
// add a new client to the list and return a url
return "restapp/rest/clients/" + id;
}
}
191. Star;ng
Point
of
Your
App
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
// http://localhost:8080/RestProvider/rest/clients
@ApplicationPath("/rest")
public class MyApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
final Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(ClientsResource.class);
return classes;
}
}
193. Java
Client
App
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
public class Main {
public static void main(String[] args) {
// Build a new client instance.
Client client = ClientBuilder.newClient();
// Build a new web resource target.
WebTarget webTarget = client.target("http://localhost:8080/restapp/rest/clients");
// Start building a request to the targeted web resource. Accepts only XML
Invocation.Builder builder = webTarget.request(MediaType.APPLICATION_XML);
// Create HTTP GET invocation
Invocation invocation = builder.buildGet();
// Synchronously invoke the request and receive a response of the specified type back.
String result = invocation.invoke(String.class);
System.out.println(result);
}
}