SlideShare ist ein Scribd-Unternehmen logo
1 von 194
Downloaden Sie, um offline zu lesen
Java	
  Web	
  Services	
  
Jussi	
  Pohjolainen	
  
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	
  
Business	
  Needs	
  Flexibility	
  
•  Hook	
  up	
  new	
  partners	
  and	
  acquisi;ons	
  
•  Enable	
  reuse	
  of	
  exis;ng	
  systems	
  and	
  business	
  
logic	
  
•  Integrate	
  
•  Flexibility	
  
Technical	
  Problems	
  
•  Different	
  languages	
  and	
  plaRorms	
  
•  Integra;on	
  is	
  hard	
  and	
  costly	
  
•  Scalability	
  
•  Security	
  
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	
  
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
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	
  
XML	
  
XML	
  is	
  used	
  in	
  Web	
  Services!	
  
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.	
  
XML	
  Document	
  
•  Every	
  XML-­‐document	
  is	
  text-­‐based	
  
•  =>	
  sharing	
  data	
  between	
  different	
  computers!	
  
•  =>	
  sharing	
  data	
  in	
  Internet!	
  
•  =>	
  plaRorm	
  independence!	
  
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?	
  
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.	
  
	
  
.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	
  
.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	
  
SGML	
  vs.	
  XML	
  
SGML:	
  Standard	
  Generalized	
  Markup	
  Language	
  
Meta	
  language	
  	
  
XML	
  
Meta	
  language	
  (subset	
  of	
  SGML)	
  
HTML	
  
(.html)	
  
XHTML	
  
(.xhtml)	
  
MathML	
  
(.mml)	
  
OOXML	
  
(.docx)	
  
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
	
  
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>
SVG	
  -­‐	
  Example	
  
<?xml version="1.0"?>
<!DOCTYPE svg
PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" version="1.1"
xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="50" r="40" stroke="black"
stroke-width="2" fill="red"/>
</svg>
MathML	
  (Open	
  Office)	
  
<?xml version="1.0"?>
<!DOCTYPE math:math PUBLIC "-//OpenOffice.org//DTD Modified W3C MathML 1.01//
EN" "math.dtd">
<math:math xmlns:math="http://www.w3.org/1998/Math/MathML">
<math:semantics>
<math:mrow>
<math:mi>x</math:mi>
<math:mo math:stretchy="false">=</math:mo>
<math:mfrac>
<math:mrow>
...
</math:mrow>
<math:annotation math:encoding="StarMath 5.0">x = {-b +-sqrt{b^{2}-4{ac}} }
over {2 {a}} </math:annotation>
</math:semantics>
</math:math>
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>
WELL	
  FORMED	
  XML	
  -­‐	
  DOCUMENT	
  
Rules	
  that	
  Apply	
  to	
  Every	
  XML-­‐Document	
  
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).	
  
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>
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"	
  
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	
  
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">
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 à
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 &quot;Shotgun&quot; Ziegler">
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	
  
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..	
  
	
  
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>
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>
EXERCISE	
  1:	
  WELLFORMED	
  XML	
  
VALID	
  XML	
  DOCUMENT	
  
Defining	
  the	
  Structure	
  for	
  XML	
  documents	
  
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	
  
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)	
  	
  
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.	
  	
  
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?	
  
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>
Valida;ng	
  with	
  W3C	
  Service	
  
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?	
  	
  
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.	
  
Example:	
  MathML	
  and	
  Open	
  Office	
  
Open	
  the	
  Document	
  in	
  External	
  Editor	
  
Modify	
  and	
  Save	
  the	
  Document	
  
Break	
  the	
  XML	
  file	
  
Open	
  the	
  Document	
  
Result	
  
Nope..	
  It	
  does	
  not	
  try	
  to	
  understand	
  the	
  errors	
  in	
  
the	
  document.	
  It	
  does	
  not	
  handle	
  the	
  document	
  at	
  all.	
  
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	
  
WORD	
  ABOUT	
  DTD	
  
Scenario:	
  	
  
Moving	
  Books	
  from	
  Library	
  A	
  to	
  Library	
  B	
  
Java	
  EE	
   PHP	
  
if(is_wf("books.xml")) {
save_to_DB("books.xml");
}
Library	
  A	
   Library	
  B	
  
Beler	
  Way	
  
Java	
  EE	
   PHP	
  
if(is_wf("books.xml") and
is_valid("books.xml") {
save_to_DB("books.xml");
}
Library	
  A	
   Library	
  B	
  
Crea;ng	
  XML	
  languages	
  
XML	
  
XHTML	
  
(.xhtml)	
  
MathML	
  
(.mml)	
  
OOXML	
  
(.docx)	
  
XML	
  NAMESPACES	
  
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!	
  
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	
  
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.	
  
xmlns	
  -­‐	
  alribute	
  
<root>
<h:table xmlns:h="http://www.w3.org/TR/html4/">
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table xmlns:f="http://www.w3schools.com/furniture">
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
xmlns	
  -­‐	
  alribute	
  
<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>
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.
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.	
  
<?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>
W3C	
  SCHEMA	
  
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	
  
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	
  
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.	
  	
  
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.	
  	
  
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.	
  	
  
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
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.
Simple	
  Schema	
  
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="koululainen" type="koululaiset_tyyppi"/>
<xsd:complexType name="koululaiset_tyyppi">
<xsd:sequence>
<xsd:element name="etunimi" type="xsd:string"/>
<xsd:element name="sukunimi" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
Let's	
  remove	
  namespaces...	
  
<?xml version="1.0"?>
<schema>
<element name="koululainen" type="koululaiset_tyyppi"/>
<complexType name="koululaiset_tyyppi">
<sequence>
<element name="etunimi" type="string"/>
<element name="sukunimi" type="string"/>
</sequence>
</complexType>
</schema>
It	
  doesn't	
  look	
  so	
  confusing	
  
aTer	
  all?	
  
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	
  
Usage	
  of	
  Datatypes	
  
<xsd:element name="firstname"
type="xsd:string" />
<xsd:element name="ableToSwim"
type="xsd:boolean" />
<xsd:element name="date"
type="xsd:date" />	
  
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	
  	
  
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	
  
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>
2)	
  Anonymous	
  Data	
  Type	
  
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="grade">
<xsd:simpleType>
<xsd:restriction base="xsd:positiveInteger">
<xsd:minInclusive value="4"/>
<xsd:maxInclusive value="10"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
</xsd:schema>
Benefits	
  of	
  Named	
  Data	
  Type	
  
•  If	
  you	
  want	
  re-­‐use	
  your	
  datatype:	
  
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="grade" type="grade_type" />
<xsd:element name="teachers_IQ" 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>
SimpleType:	
  enumera;on	
  
•  Alterna;ve	
  content	
  
<xsd:simpleType name="car">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="Audi"/>
<xsd:enumeration value="Golf"/>
<xsd:enumeration value="BMW"/>
</xsd:restriction>
</xsd:simpleType>
SimpleType:	
  palern	
  
•  Using	
  REGEX:	
  
	
  
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:pattern value="[a-z]"/>
</xsd:restriction>
</xsd:simpleType>	
  
REGEX	
  Examples	
  
<xs:pattern value="[A-Z][A-Z][A-Z]"/>
<xs:pattern value="[a-zA-Z][a-zA-Z][a-zA-Z]"/>
<xs:pattern value="[xyz]"/>
<xs:pattern value="[0-9][0-9][0-9][0-9][0-9]"/>
<xs:pattern value="([a-z])*"/>
<xs:pattern value="male|female"/>
<xs:pattern value="[a-zA-Z0-9]{8}"/>
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
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	
  
Example:	
  XML	
  -­‐	
  File	
  
<?xml version="1.0"?>
<students>
<firstname>Pekka</firstname>
<lastname>Virtanen</lastname>
</students>
Example:	
  XSD	
  –	
  file	
  
Named	
  ComplexType	
  
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="students" type="students_type">
<xsd:complexType name="students_type">
<xsd:sequence>
<xsd:element name="firstname" type="xsd:string"/>
<xsd:element name="lastname" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
Use	
  now	
  
complexType	
  
(vs.	
  
simpleType)	
  
Example:	
  XSD	
  –	
  file	
  
Anonymous	
  ComplexType	
  
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="students">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="firstname" type="xsd:string"/>
<xsd:element name="lastname" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
Example:	
  ComplexType	
  
<xsd:element name="employee" type="personinfo"/>
<xsd:element name="student" type="personinfo"/>
<xsd:element name="member" type="personinfo"/>
<xsd:complexType name="personinfo">
<xsd:sequence>
<xsd:element name="firstname" type="xsd:string"/>
<xsd:element name="lastname" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
Deep	
  Structure	
  in	
  XML	
  -­‐	
  File	
  
<?xml version="1.0"?>
<students>
<student>
<name>
<firstname>Pekka</firstname>
</name>
</student>
</students>
Using	
  Anonymous	
  Data	
  Type:	
  The	
  Horror!	
  
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="students">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="student">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="name">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="firstname" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
"There	
  is	
  an	
  error	
  in	
  my	
  schema,	
  could	
  you	
  find	
  it	
  
for	
  me?"	
  
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="students">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="student">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="name">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="firstname" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:complexType>
</xsd:element>
</xsd:schema>
Use	
  Named	
  Datatypes!	
  It's	
  easier	
  to	
  find	
  errors..	
  
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="students" type="students_type" />
<xsd:complexType name="students_type">
<xsd:sequence>
<xsd:element name="student" name="student_type" />
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="student_type">
<xsd:sequence>
<xsd:element name="name" name="name_type" />
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="name_type">
<xsd:sequence>
<xsd:element name="firstname" name="xsd:string" />
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
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>
Alribute	
  
•  XML	
  
–  <student id="A1">...</student>
•  Schema	
  
<xsd:element name="student" type="student_type" />
<xsd:complexType name="student_type">
<xsd:sequence>
...
</xsd:sequence>
<xsd:attribute name="id" type="xsd:ID"/>
</xsd:complexType>	
  
	
   	
   	
  	
  
Empty	
  Element	
  with	
  Alribute	
  
•  XML	
  
– <student id="A1" />
•  Schema	
  
<xsd:element name="student" type="student_type" />
<xsd:complexType name="student_type">
<xsd:attribute name="id" type="xsd:ID"/>
</xsd:complexType>	
  
	
   	
   	
  	
  
EXERCISE	
  2:	
  XML	
  AND	
  SCHEMA	
  
XML	
  AND	
  JAVA	
  
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	
  
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.
JAXB	
  Binding	
  
book.xsd	
  
book.xml	
  
book.java	
  (class)	
  
new	
  Book();	
  
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	
  
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;
}
...
}
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>
*/
}
}
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;
}
}
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);
}
}
Result	
  and	
  unmarshal	
  
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persons>
<person id="1">
<name>jack</name>
<age>28</age>
</person>
<person id="2">
<name>tina</name>
<age>29</age>
</person>
<person id="3">
<name>john</name>
<age>45</age>
</person>
<person id="4">
<name>samantha</name>
<age>19</age>
</person>
</persons>
Unmarshal	
  
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 );
System.out.println( persons.getPersons().get(0).getName() ); // jack
}
}
Java	
  Architecture	
  for	
  XML	
  Binding	
  (JAXB)	
  
•  JAXB	
  gives	
  you	
  the	
  tools	
  to	
  	
  
– Transform	
  Schema	
  file	
  (.xsd)	
  to	
  classes	
  (.java)	
  
•  xjc polygon.xsd
– Transform	
  classes	
  (.java)	
  to	
  Schema	
  (.xsd)	
  
•  schemagen Class1.java ... ClassN.java
Generate	
  Schema	
  From	
  Classes	
  
> schemagen Persons.java Person.java
> cat schema1.xsd
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Person" type="person"/>
<xs:element name="persons" type="persons"/>
<xs:complexType name="persons">
<xs:sequence>
<xs:element name="person" type="person" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="person">
<xs:sequence>
<xs:element name="name" type="xs:string" minOccurs="0"/>
<xs:element name="age" type="xs:int"/>
</xs:sequence>
<xs:attribute name="id" type="xs:int" use="required"/>
</xs:complexType>
</xs:schema>
From	
  Schema	
  to	
  Classes	
  
> xjc schema1.xsd
parsing a schema...
compiling a schema...
generated/ObjectFactory.java
generated/Person.java
generated/Persons.java
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	
  ...	
  
...	
  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
}
}
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;
...
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
}
}
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);
}
}
EXERCISE	
  3:	
  JAXB	
  
W3C	
  SOAP	
  WEB	
  SERVICES	
  AND	
  XML	
  
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	
  
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	
  
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.	
  
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	
  
<definitions name="HelloService" >
<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>
<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>
Tes;ng	
  StockQuote	
  
•  WSDL	
  file	
  
–  http://www.webservicex.net/stockquote.asmx?WSDL
•  Opera;on	
  GetQuote
–  http://www.webservicex.net/stockquote.asmx?
op=GetQuote
Imitate	
  Client	
  
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
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") );
}
}
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	
  
HTTP	
  Request	
  POST	
  
POST /test/page.html HTTP/1.1
Host: server.com
name1=value1
HTTP	
  Request	
  GET	
  
POST /test/page.php?name1=value HTTP/1.1
Host: server.com
HTTP	
  Response	
  
HTTP/1.0 200 OK
Date: Fri, 31 Dec 1999 23:59:59 GMT
Content-Type: text/html
Content-Length: 1354
<html>
<body>
<h1>Web Page</h1>
(more file contents)
.
.
.
</body>
</html>
HTTP	
  Response	
  
HTTP/1.0 200 OK
Date: Fri, 31 Dec 2015 23:59:59 GMT
Content-Type: image/png
Content-Length: 1354
10100111010101010101001011111....
HTTP	
  Response	
  
HTTP/1.0 200 OK
Date: Fri, 31 Dec 2015 23:59:59 GMT
Content-Type: text/xml
Content-Length: 1354
<books><book>...</book></books>
Soap	
  1.2	
  Client	
  Message	
  in	
  HTTP	
  
POST /stockquote.asmx HTTP/1.1
Host: www.webservicex.net
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>
<GetQuote xmlns="http://www.webserviceX.NET/">
<symbol>aapl</symbol>
</GetQuote>
</soap12:Body>
</soap12:Envelope>
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>
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?	
  
JAVA	
  WEB	
  SERVICE	
  CLIENT:	
  SAAJ	
  
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.*
CREATING	
  SAAJ	
  CLIENT	
  
import	
  javax.xml.soap.*;	
  
import	
  java.io.*;	
  
import	
  javax.xml.parsers.*;	
  
import	
  javax.xml.transform.*;	
  
import	
  org.w3c.dom.*;	
  
import	
  org.xml.sax.*;	
  
import	
  javax.xml.transform.stream.*;	
  
	
  
class	
  Main	
  {	
  
	
  	
  	
  	
  public	
  static	
  void	
  main(String	
  args[])	
  throws	
  Exception	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  //	
  Create	
  SOAP	
  Connection	
  
	
  	
  	
  	
  	
  	
  	
  	
  SOAPConnectionFactory	
  soapConnectionFactory	
  =	
  SOAPConnectionFactory.newInstance();	
  
	
  	
  	
  	
  	
  	
  	
  	
  SOAPConnection	
  soapConnection	
  =	
  soapConnectionFactory.createConnection();	
  
	
  
	
  	
  	
  	
  	
  	
  	
  	
  //	
  Send	
  SOAP	
  Message	
  to	
  SOAP	
  Server	
  
	
  	
  	
  	
  	
  	
  	
  	
  String	
  url	
  =	
  "http://www.webservicex.net/stockquote.asmx";	
  
	
  
	
  	
  	
  	
  	
  	
  	
  	
  //	
  Sends	
  the	
  given	
  message	
  to	
  the	
  specified	
  endpoint	
  and	
  blocks	
  until	
  it	
  has	
  returned	
  the	
  response.	
  
	
  	
  	
  	
  	
  	
  	
  	
  //	
  Prints	
  also	
  the	
  the	
  request	
  SOAP	
  message	
  
	
  	
  	
  	
  	
  	
  	
  	
  SOAPMessage	
  soapResponse	
  =	
  soapConnection.call(createSOAPRequest(),	
  url);	
  
	
  
	
  	
  	
  	
  	
  	
  	
  	
  //	
  print	
  SOAP	
  Response	
  
	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Response	
  SOAP	
  Message:");	
  
	
  
	
  	
  	
  	
  	
  	
  	
  	
  //soapResponse.writeTo(System.out);	
  
	
  	
  	
  	
  	
  	
  	
  	
  //	
  Pretty	
  print	
  
	
  	
  	
  	
  	
  	
  	
  	
  System.out.println(	
  prettyPrint(soapResponse)	
  );	
  
	
  
	
  	
  	
  	
  	
  	
  	
  	
  String	
  price	
  =	
  getMyResult(soapResponse);	
  
	
  
	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("price	
  =	
  "	
  +	
  price);	
  
	
  
	
  	
  	
  	
  	
  	
  	
  	
  soapConnection.close();	
  
	
  	
  	
  	
  }	
  
	
  
private	
  static	
  SOAPMessage	
  createSOAPRequest()	
  throws	
  Exception	
  {	
  
	
  	
  	
  	
  MessageFactory	
  messageFactory	
  =	
  MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);	
  
	
  	
  	
  	
  SOAPMessage	
  soapMessage	
  =	
  messageFactory.createMessage();	
  
	
  	
  	
  	
  SOAPPart	
  soapPart	
  =	
  soapMessage.getSOAPPart();	
  
	
  
	
  	
  	
  	
  String	
  serverURI	
  =	
  "http://www.webserviceX.NET/";	
  
	
  
	
  	
  	
  	
  //	
  SOAP	
  Envelope	
  
	
  	
  	
  	
  SOAPEnvelope	
  envelope	
  =	
  soapPart.getEnvelope();	
  
	
  	
  	
  	
  envelope.addNamespaceDeclaration("w",	
  serverURI);	
  
	
  
	
  	
  	
  	
  //	
  SOAP	
  Body	
  
	
  	
  	
  	
  SOAPBody	
  soapBody	
  =	
  envelope.getBody();	
  
	
  	
  	
  	
  SOAPElement	
  soapBodyElem	
  =	
  soapBody.addChildElement("GetQuote",	
  "w");	
  
	
  	
  	
  	
  SOAPElement	
  soapBodyElem1	
  =	
  soapBodyElem.addChildElement("symbol",	
  "w");	
  
	
  	
  	
  	
  soapBodyElem1.addTextNode("aapl");	
  
	
  
	
  	
  	
  	
  soapMessage.saveChanges();	
  
	
  
	
  	
  	
  	
  /*	
  Print	
  the	
  request	
  message	
  */	
  
	
  	
  	
  	
  System.out.print("Request	
  SOAP	
  Message:");	
  
	
  	
  	
  	
  //	
  soapMessage.writeTo(System.out);	
  
	
  	
  	
  	
  System.out.println(	
  prettyPrint(soapMessage)	
  );	
  
	
  	
  	
  	
  System.out.println();	
  
	
  
	
  	
  	
  	
  return	
  soapMessage;	
  
}	
  
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:w="http://www.webserviceX.NET/">
<env:Header/>
<env:Body>
<w:GetQuote>
<w:symbol>aapl</w:symbol>
</w:GetQuote>
</env:Body>
</env:Envelope>
//	
  Using	
  DOM	
  to	
  fetch	
  the	
  content	
  of	
  the	
  given	
  XML	
  
private	
  static	
  String	
  getMyResult(	
  SOAPMessage	
  soapResponse	
  )	
  throws	
  Exception	
  {	
  
	
  	
  	
  	
  SOAPBody	
  body	
  =	
  soapResponse.getSOAPBody();	
  
	
  
	
  	
  	
  	
  String	
  xmlString	
  =	
  body.getElementsByTagName("GetQuoteResult").item(0).getTextContent();	
  
	
  
	
  	
  	
  	
  System.out.println("Content	
  XML:");	
  
	
  	
  	
  	
  System.out.println(xmlString);	
  
	
  	
  	
  	
  System.out.println();	
  
	
  
	
  	
  	
  	
  DocumentBuilderFactory	
  factory	
  =	
  DocumentBuilderFactory.newInstance();	
  
	
  	
  	
  	
  DocumentBuilder	
  builder	
  =	
  factory.newDocumentBuilder();	
  
	
  	
  	
  	
  Document	
  document	
  =	
  builder.parse(	
  new	
  InputSource(	
  new	
  StringReader(	
  xmlString	
  )	
  )	
  );	
  
	
  
	
  	
  	
  	
  return	
  document.getElementsByTagName("Last").item(0).getTextContent();	
  
}	
  
	
  
<?xml version="1.0" encoding="UTF-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-
envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/
XMLSchema">
<soap:Body>
<GetQuoteResponse xmlns="http://www.webserviceX.NET/">
<GetQuoteResult>&lt;StockQuotes&gt;&lt;Stock&gt;&lt;Symbol&gt;aapl&lt;/Symbol&gt;&lt;Last&gt;
124.50&lt;/Last&gt;&lt;Date&gt;7/24/2015&lt;/Date&gt;&lt;Time&gt;4:00pm&lt;/
Time&gt;&lt;Change&gt;-0.66&lt;/Change&gt;&lt;Open&gt;125.43&lt;/Open&gt;&lt;High&gt;125.74&lt;/
High&gt;&lt;Low&gt;123.90&lt;/Low&gt;&lt;Volume&gt;42162332&lt;/Volume&gt;&lt;MktCap&gt;709.99B&lt;/
MktCap&gt;&lt;PreviousClose&gt;125.16&lt;/PreviousClose&gt;&lt;PercentageChange&gt;-0.53%&lt;/
PercentageChange&gt;&lt;AnnRange&gt;93.28 - 134.54&lt;/AnnRange&gt;&lt;Earns&gt;8.65&lt;/
Earns&gt;&lt;P-E&gt;14.40&lt;/P-E&gt;&lt;Name&gt;Apple Inc.&lt;/Name&gt;&lt;/Stock&gt;&lt;/
StockQuotes&gt;</GetQuoteResult>
</GetQuoteResponse>
</soap:Body>
</soap:Envelope>
//	
  Using	
  DOM	
  to	
  fetch	
  the	
  content	
  of	
  the	
  given	
  XML	
  
private	
  static	
  String	
  getMyResult(	
  SOAPMessage	
  soapResponse	
  )	
  throws	
  Exception	
  {	
  
	
  	
  	
  	
  ...	
  
	
  	
  	
  	
  return	
  document.getElementsByTagName("Last").item(0).getTextContent();	
  
}	
  
	
  
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/
XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetQuoteResponse xmlns="http://www.webserviceX.NET/">
<GetQuoteResult>
<StockQuotes>
<Stock>
<Symbol>aapl</Symbol>
<Last>124.50</Last>
<Date>7/24/2015</Date>
<Time>4:00pm</Time>
<Change>-0.66</Change>
<Open>125.43</Open>
<High>125.74</High>
<Low>123.90</Low>
<Volume>42162332</Volume>
<MktCap>709.99B</MktCap>
<PreviousClose>125.16</PreviousClose>
<PercentageChange>-0.53%</PercentageChange>
<AnnRange>93.28 - 134.54</AnnRange>
<Earns>8.65</Earns>
<P-E>14.40</P-E>
<Name>Apple Inc.</Name>
</Stock>
</StockQuotes>
</GetQuoteResult>
</GetQuoteResponse>
</soap:Body>
</soap:Envelope>
 
//	
  Helper	
  method	
  for	
  pretty	
  print	
  xml	
  
public	
  static	
  String	
  prettyPrint(SOAPMessage	
  soapMessage)	
  {	
  
	
  	
  	
  	
  try	
  {	
  
	
  
	
  	
  	
  	
  	
  	
  	
  	
  TransformerFactory	
  tff	
  =	
  TransformerFactory.newInstance();	
  
	
  	
  	
  	
  	
  	
  	
  	
  Transformer	
  tf	
  =	
  tff.newTransformer();	
  
	
  	
  	
  	
  	
  	
  	
  	
  tf.setOutputProperty(OutputKeys.INDENT,	
  "yes");	
  
	
  	
  	
  	
  	
  	
  	
  	
  tf.setOutputProperty("{http://xml.apache.org/xslt}indent-­‐amount",	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  "2");	
  
	
  	
  	
  	
  	
  	
  	
  	
  Source	
  sc	
  =	
  soapMessage.getSOAPPart().getContent();	
  
	
  	
  	
  	
  	
  	
  	
  	
  ByteArrayOutputStream	
  streamOut	
  =	
  new	
  ByteArrayOutputStream();	
  
	
  	
  	
  	
  	
  	
  	
  	
  StreamResult	
  result	
  =	
  new	
  StreamResult(streamOut);	
  
	
  	
  	
  	
  	
  	
  	
  	
  tf.transform(sc,	
  result);	
  
	
  
	
  	
  	
  	
  	
  	
  	
  	
  String	
  strMessage	
  =	
  streamOut.toString();	
  
	
  	
  	
  	
  	
  	
  	
  	
  return	
  strMessage;	
  
	
  	
  	
  	
  }	
  catch	
  (Exception	
  e)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Exception	
  in	
  getSOAPMessageAsString	
  "	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  +	
  e.getMessage());	
  
	
  	
  	
  	
  	
  	
  	
  	
  return	
  null;	
  
	
  	
  	
  	
  }	
  
}	
  
	
  
EXERCISE	
  4:	
  WEATHER	
  SAAJ	
  CLIENT	
  
CREATING	
  SAAJ	
  WEB	
  SERVER	
  
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	
  
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
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
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	
  
WEB-­‐INF/web.xml	
  
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http:/java.sun.com/dtd/web-app_2_3.dtd">
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
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();
}
}
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/*
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
	
  
ant:	
  build.xml	
  
<project default="main">
<target name="compile">
<mkdir dir="war/WEB-INF/classes"/>
<javac includeantruntime="false" srcdir="src/" destdir="war/WEB-INF/classes">
<classpath>
<pathelement path="${classpath}"/>
<pathelement location="/path/to/glassfish4/glassfish/lib/javax.servlet-api.jar"/>
</classpath>
</javac>
</target>
<target name="war">
<jar destfile="WebServiceProvider.war" basedir="war/." />
</target>
<target name="deploy">
<exec executable="asadmin.bat">
<arg value="deploy"/>
<arg value="--force=true"/>
<arg value="WebServiceProvider.war"/>
</exec>
</target>
<target name="main" depends="compile,war,deploy"/>
</project>
Change	
  
"admin.bat"	
  to	
  
"admin"	
  if	
  in	
  Mac	
  -­‐	
  
environment	
  
SOAP	
  RESPONSE	
  
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain");
printResponse(response);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/soap+xml");
printResponse(response);
}
public void printResponse(HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();
String output = getSoapOutput();
out.println(output);
out.flush();
out.close();
}
public String getSoapOutput() {
String response = "<?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>" +
"<GetSomething xmlns='http://www.somecompany.com/'>" +
"<Result>Hello</Result>" +
"</GetSomething>" +
"</soap12:Body>" +
"</soap12:Envelope>";
return response;
}
}
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
try {
response.setContentType("application/soap+xml");
SOAPMessage message = createMessage(request);
message.writeTo(response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
// <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
// <SOAP-ENV:Header/>
// <SOAP-ENV:Body/>
// </SOAP-ENV:Envelope>
public SOAPMessage createMessage(HttpServletRequest request) throws Exception {
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage soapMessage = mf.createMessage();
return soapMessage;
}
}
//	
  <SOAP-­‐ENV:Envelope	
  xmlns:SOAP-­‐ENV="http://schemas.xmlsoap.org/soap/envelope/">	
  
//	
  <SOAP-­‐ENV:Header/>	
  
//	
  <SOAP-­‐ENV:Body>	
  
//	
  	
  	
  	
  	
  <soa:Result	
  xmlns:soa="http://www.somecompany.com">Hello</soa:Result>	
  
//	
  </SOAP-­‐ENV:Body>	
  
//	
  </SOAP-­‐ENV:Envelope>	
  
public	
  SOAPMessage	
  createMessage(HttpServletRequest	
  request)	
  throws	
  Exception	
  {	
  
	
  	
  	
  	
  MessageFactory	
  mf	
  =	
  MessageFactory.newInstance();	
  
	
  	
  	
  	
  SOAPMessage	
  soapMessage	
  =	
  mf.createMessage();	
  
	
  
	
  	
  	
  	
  //	
  Gets	
  the	
  SOAP	
  part	
  of	
  this	
  SOAPMessage	
  object.	
  
	
  	
  	
  	
  SOAPPart	
  sp	
  	
  	
  	
  	
  =	
  soapMessage.getSOAPPart();	
  
	
  	
  	
  	
  SOAPEnvelope	
  se	
  =	
  sp.getEnvelope();	
  
	
  	
  	
  	
  SOAPBody	
  sb	
  	
  	
  	
  	
  =	
  se.getBody();	
  
	
  
	
  	
  	
  	
  Name	
  bn	
  =	
  se.createName("Result",	
  "soa",	
  "http://www.somecompany.com");	
  
	
  	
  	
  	
  SOAPBodyElement	
  e	
  =	
  sb.addBodyElement(bn);	
  
	
  	
  	
  	
  e.addTextNode("Hello");	
  
	
  
	
  	
  	
  	
  soapMessage.saveChanges();	
  
	
  
	
  	
  	
  	
  return	
  soapMessage;	
  
}	
  
EXERCISE	
  5:	
  WEB	
  SERVICE	
  
PROVIDER	
  
JAX-­‐WS	
  
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!	
  
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	
  
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);
}
}
SERVICE	
  
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	
  
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!	
  
Define	
  Service	
  
package mycompany;
import javax.jws.WebService;
@WebService
public class CircleFunctions {
public double getArea(double r) {
return java.lang.Math.PI * r * r;
}
}
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());
}
}
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);
}
}
EXERCISE	
  6	
  &	
  7	
  
REST	
  SERVICE	
  USING	
  JAVA	
  
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	
  
Example	
  (wikipedia)	
  
Example:	
  REST	
  +	
  XML	
  
Example:	
  REST	
  +	
  XML	
  
Example:	
  REST	
  +	
  JSON	
  
EXERCISE	
  8	
  
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.*	
  
CLIENT	
  
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);	
  
	
  	
  	
  	
  }	
  
}	
  
	
  
	
  
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());	
  
	
  	
  	
  	
  }	
  
}	
  
	
  
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;	
  
	
  	
  	
  	
  }	
  
	
  	
  	
  	
  ...	
  
EXERCISE	
  9	
  
SERVICE	
  
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
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";
}
}
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	
  
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;
}
}
REST	
  JAVA	
  SERVER	
  EXAMPLE	
  
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
...
}
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;
}
}
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;
}
}
Browser	
  
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);
}
}
EXERCISES	
  10	
  -­‐>	
  

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to Web Standards
Introduction to Web StandardsIntroduction to Web Standards
Introduction to Web Standards
Jussi Pohjolainen
 

Was ist angesagt? (20)

Web Services Presentation - Introduction, Vulnerabilities, & Countermeasures
Web Services Presentation - Introduction, Vulnerabilities, & CountermeasuresWeb Services Presentation - Introduction, Vulnerabilities, & Countermeasures
Web Services Presentation - Introduction, Vulnerabilities, & Countermeasures
 
SOAP, UDDI, WSDL. XML definitions
SOAP, UDDI, WSDL. XML definitions SOAP, UDDI, WSDL. XML definitions
SOAP, UDDI, WSDL. XML definitions
 
Web Services
Web ServicesWeb Services
Web Services
 
SOAP--Simple Object Access Protocol
SOAP--Simple Object Access ProtocolSOAP--Simple Object Access Protocol
SOAP--Simple Object Access Protocol
 
Web services
Web servicesWeb services
Web services
 
REST vs SOAP
REST vs SOAPREST vs SOAP
REST vs SOAP
 
Web services SOAP
Web services SOAPWeb services SOAP
Web services SOAP
 
Overview of Rest Service and ASP.NET WEB API
Overview of Rest Service and ASP.NET WEB APIOverview of Rest Service and ASP.NET WEB API
Overview of Rest Service and ASP.NET WEB API
 
Soap vs rest
Soap vs restSoap vs rest
Soap vs rest
 
Webservices Overview : XML RPC, SOAP and REST
Webservices Overview : XML RPC, SOAP and RESTWebservices Overview : XML RPC, SOAP and REST
Webservices Overview : XML RPC, SOAP and REST
 
Webservice Testing
Webservice TestingWebservice Testing
Webservice Testing
 
PHP and Web Services
PHP and Web ServicesPHP and Web Services
PHP and Web Services
 
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
 
WebServices
WebServicesWebServices
WebServices
 
Webservices Workshop - september 2014
Webservices Workshop -  september 2014Webservices Workshop -  september 2014
Webservices Workshop - september 2014
 
Web architecture - overview of techniques.
Web architecture - overview of  techniques.Web architecture - overview of  techniques.
Web architecture - overview of techniques.
 
Web Services
Web ServicesWeb Services
Web Services
 
Java Web Programming [1/9] : Introduction to Web Application
Java Web Programming [1/9] : Introduction to Web ApplicationJava Web Programming [1/9] : Introduction to Web Application
Java Web Programming [1/9] : Introduction to Web Application
 
Introduction to Web Standards
Introduction to Web StandardsIntroduction to Web Standards
Introduction to Web Standards
 

Andere mochten auch

Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
Shreeraj Shah
 
Xml Java
Xml JavaXml Java
Xml Java
cbee48
 

Andere mochten auch (20)

libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
 
Java Web Services [4/5]: Java API for XML Web Services
Java Web Services [4/5]: Java API for XML Web ServicesJava Web Services [4/5]: Java API for XML Web Services
Java Web Services [4/5]: Java API for XML Web Services
 
Box2D and libGDX
Box2D and libGDXBox2D and libGDX
Box2D and libGDX
 
libGDX: Scene2D
libGDX: Scene2DlibGDX: Scene2D
libGDX: Scene2D
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDX
 
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
 
Restful Web Services
Restful Web ServicesRestful Web Services
Restful Web Services
 
Web Services (SOAP, WSDL, UDDI)
Web Services (SOAP, WSDL, UDDI)Web Services (SOAP, WSDL, UDDI)
Web Services (SOAP, WSDL, UDDI)
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
Testing web services
Testing web servicesTesting web services
Testing web services
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
 
libGDX: User Input
libGDX: User InputlibGDX: User Input
libGDX: User Input
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame Animation
 
JAXP
JAXPJAXP
JAXP
 
Java Web Service - Summer 2004
Java Web Service - Summer 2004Java Web Service - Summer 2004
Java Web Service - Summer 2004
 
Jaxp Xmltutorial 11 200108
Jaxp Xmltutorial 11 200108Jaxp Xmltutorial 11 200108
Jaxp Xmltutorial 11 200108
 
Simple API for XML
Simple API for XMLSimple API for XML
Simple API for XML
 
Java Web Services [2/5]: Introduction to SOAP
Java Web Services [2/5]: Introduction to SOAPJava Web Services [2/5]: Introduction to SOAP
Java Web Services [2/5]: Introduction to SOAP
 
Java Web Services [5/5]: REST and JAX-RS
Java Web Services [5/5]: REST and JAX-RSJava Web Services [5/5]: REST and JAX-RS
Java Web Services [5/5]: REST and JAX-RS
 
Xml Java
Xml JavaXml Java
Xml Java
 

Ähnlich wie Java Web Services

Data interchange integration, HTML XML Biological XML DTD
Data interchange integration, HTML XML Biological XML DTDData interchange integration, HTML XML Biological XML DTD
Data interchange integration, HTML XML Biological XML DTD
AnushaMahmood
 

Ähnlich wie Java Web Services (20)

Unit iv xml dom
Unit iv xml domUnit iv xml dom
Unit iv xml dom
 
xml and xhtml.pptx
xml and xhtml.pptxxml and xhtml.pptx
xml and xhtml.pptx
 
Cetpa dotnet taining
Cetpa dotnet tainingCetpa dotnet taining
Cetpa dotnet taining
 
Xml
XmlXml
Xml
 
The XML Forms Architecture
The XML Forms ArchitectureThe XML Forms Architecture
The XML Forms Architecture
 
00 introduction
00 introduction00 introduction
00 introduction
 
Markup For Dummies (Russ Ward)
Markup For Dummies (Russ Ward)Markup For Dummies (Russ Ward)
Markup For Dummies (Russ Ward)
 
Web servicesoverview
Web servicesoverviewWeb servicesoverview
Web servicesoverview
 
Web servicesoverview
Web servicesoverviewWeb servicesoverview
Web servicesoverview
 
8023.ppt
8023.ppt8023.ppt
8023.ppt
 
UNIT-1 Web services
UNIT-1 Web servicesUNIT-1 Web services
UNIT-1 Web services
 
WebServices
WebServicesWebServices
WebServices
 
Web programming and services
Web programming and servicesWeb programming and services
Web programming and services
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Data interchange integration, HTML XML Biological XML DTD
Data interchange integration, HTML XML Biological XML DTDData interchange integration, HTML XML Biological XML DTD
Data interchange integration, HTML XML Biological XML DTD
 
Agile xml
Agile xmlAgile xml
Agile xml
 
Xml
XmlXml
Xml
 
Fyp presentation 2 (SQL Converter)
Fyp presentation 2 (SQL Converter)Fyp presentation 2 (SQL Converter)
Fyp presentation 2 (SQL Converter)
 
Unit 3 WEB TECHNOLOGIES
Unit 3 WEB TECHNOLOGIES Unit 3 WEB TECHNOLOGIES
Unit 3 WEB TECHNOLOGIES
 
Dos and donts
Dos and dontsDos and donts
Dos and donts
 

Mehr von Jussi Pohjolainen

Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
Jussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
Jussi Pohjolainen
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Jussi Pohjolainen
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
Jussi Pohjolainen
 
Quick Intro to JQuery and JQuery Mobile
Quick Intro to JQuery and JQuery MobileQuick Intro to JQuery and JQuery Mobile
Quick Intro to JQuery and JQuery Mobile
Jussi Pohjolainen
 

Mehr von Jussi Pohjolainen (20)

Moved to Speakerdeck
Moved to SpeakerdeckMoved to Speakerdeck
Moved to Speakerdeck
 
libGDX: Tiled Maps
libGDX: Tiled MapslibGDX: Tiled Maps
libGDX: Tiled Maps
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDX
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
 
Intro to Asha UI
Intro to Asha UIIntro to Asha UI
Intro to Asha UI
 
Intro to PhoneGap
Intro to PhoneGapIntro to PhoneGap
Intro to PhoneGap
 
Quick Intro to JQuery and JQuery Mobile
Quick Intro to JQuery and JQuery MobileQuick Intro to JQuery and JQuery Mobile
Quick Intro to JQuery and JQuery Mobile
 
JavaScript Inheritance
JavaScript InheritanceJavaScript Inheritance
JavaScript Inheritance
 
JS OO and Closures
JS OO and ClosuresJS OO and Closures
JS OO and Closures
 
Short intro to ECMAScript
Short intro to ECMAScriptShort intro to ECMAScript
Short intro to ECMAScript
 
XAMPP
XAMPPXAMPP
XAMPP
 
Building Web Services
Building Web ServicesBuilding Web Services
Building Web Services
 
CSS
CSSCSS
CSS
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Kürzlich hochgeladen (20)

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 

Java Web Services

  • 1. Java  Web  Services   Jussi  Pohjolainen  
  • 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  
  • 8. XML   XML  is  used  in  Web  Services!  
  • 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>
  • 18. SVG  -­‐  Example   <?xml version="1.0"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg"> <circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/> </svg>
  • 19. MathML  (Open  Office)   <?xml version="1.0"?> <!DOCTYPE math:math PUBLIC "-//OpenOffice.org//DTD Modified W3C MathML 1.01// EN" "math.dtd"> <math:math xmlns:math="http://www.w3.org/1998/Math/MathML"> <math:semantics> <math:mrow> <math:mi>x</math:mi> <math:mo math:stretchy="false">=</math:mo> <math:mfrac> <math:mrow> ... </math:mrow> <math:annotation math:encoding="StarMath 5.0">x = {-b +-sqrt{b^{2}-4{ac}} } over {2 {a}} </math:annotation> </math:semantics> </math:math>
  • 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 &quot;Shotgun&quot; 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>
  • 34. VALID  XML  DOCUMENT   Defining  the  Structure  for  XML  documents  
  • 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>
  • 40. Valida;ng  with  W3C  Service  
  • 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.  
  • 43. Example:  MathML  and  Open  Office  
  • 44. Open  the  Document  in  External  Editor  
  • 45. Modify  and  Save  the  Document   Break  the  XML  file  
  • 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  
  • 50. Scenario:     Moving  Books  from  Library  A  to  Library  B   Java  EE   PHP   if(is_wf("books.xml")) { save_to_DB("books.xml"); } Library  A   Library  B  
  • 51. Beler  Way   Java  EE   PHP   if(is_wf("books.xml") and is_valid("books.xml") { save_to_DB("books.xml"); } Library  A   Library  B  
  • 52. Crea;ng  XML  languages   XML   XHTML   (.xhtml)   MathML   (.mml)   OOXML   (.docx)  
  • 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.  
  • 57. xmlns  -­‐  alribute   <root> <h:table xmlns:h="http://www.w3.org/TR/html4/"> <h:tr> <h:td>Apples</h:td> <h:td>Bananas</h:td> </h:tr> </h:table> <f:table xmlns:f="http://www.w3schools.com/furniture"> <f:name>African Coffee Table</f:name> <f:width>80</f:width> <f:length>120</f:length> </f:table> </root>
  • 58. xmlns  -­‐  alribute   <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>
  • 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.
  • 70. Simple  Schema   <?xml version="1.0"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="koululainen" type="koululaiset_tyyppi"/> <xsd:complexType name="koululaiset_tyyppi"> <xsd:sequence> <xsd:element name="etunimi" type="xsd:string"/> <xsd:element name="sukunimi" type="xsd:string"/> </xsd:sequence> </xsd:complexType> </xsd:schema>
  • 71. Let's  remove  namespaces...   <?xml version="1.0"?> <schema> <element name="koululainen" type="koululaiset_tyyppi"/> <complexType name="koululaiset_tyyppi"> <sequence> <element name="etunimi" type="string"/> <element name="sukunimi" type="string"/> </sequence> </complexType> </schema> It  doesn't  look  so  confusing   aTer  all?  
  • 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  
  • 73. Usage  of  Datatypes   <xsd:element name="firstname" type="xsd:string" /> <xsd:element name="ableToSwim" type="xsd:boolean" /> <xsd:element name="date" type="xsd:date" />  
  • 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>
  • 77. 2)  Anonymous  Data  Type   <?xml version="1.0"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="grade"> <xsd:simpleType> <xsd:restriction base="xsd:positiveInteger"> <xsd:minInclusive value="4"/> <xsd:maxInclusive value="10"/> </xsd:restriction> </xsd:simpleType> </xsd:element> </xsd:schema>
  • 78. Benefits  of  Named  Data  Type   •  If  you  want  re-­‐use  your  datatype:   <?xml version="1.0"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="grade" type="grade_type" /> <xsd:element name="teachers_IQ" 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>
  • 79. SimpleType:  enumera;on   •  Alterna;ve  content   <xsd:simpleType name="car"> <xsd:restriction base="xsd:string"> <xsd:enumeration value="Audi"/> <xsd:enumeration value="Golf"/> <xsd:enumeration value="BMW"/> </xsd:restriction> </xsd:simpleType>
  • 80. SimpleType:  palern   •  Using  REGEX:     <xsd:simpleType> <xsd:restriction base="xsd:string"> <xsd:pattern value="[a-z]"/> </xsd:restriction> </xsd:simpleType>  
  • 81. REGEX  Examples   <xs:pattern value="[A-Z][A-Z][A-Z]"/> <xs:pattern value="[a-zA-Z][a-zA-Z][a-zA-Z]"/> <xs:pattern value="[xyz]"/> <xs:pattern value="[0-9][0-9][0-9][0-9][0-9]"/> <xs:pattern value="([a-z])*"/> <xs:pattern value="male|female"/> <xs:pattern value="[a-zA-Z0-9]{8}"/>
  • 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  
  • 84. Example:  XML  -­‐  File   <?xml version="1.0"?> <students> <firstname>Pekka</firstname> <lastname>Virtanen</lastname> </students>
  • 85. Example:  XSD  –  file   Named  ComplexType   <?xml version="1.0"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="students" type="students_type"> <xsd:complexType name="students_type"> <xsd:sequence> <xsd:element name="firstname" type="xsd:string"/> <xsd:element name="lastname" type="xsd:string"/> </xsd:sequence> </xsd:complexType> </xsd:schema> Use  now   complexType   (vs.   simpleType)  
  • 86. Example:  XSD  –  file   Anonymous  ComplexType   <?xml version="1.0"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="students"> <xsd:complexType> <xsd:sequence> <xsd:element name="firstname" type="xsd:string"/> <xsd:element name="lastname" type="xsd:string"/> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema>
  • 87. Example:  ComplexType   <xsd:element name="employee" type="personinfo"/> <xsd:element name="student" type="personinfo"/> <xsd:element name="member" type="personinfo"/> <xsd:complexType name="personinfo"> <xsd:sequence> <xsd:element name="firstname" type="xsd:string"/> <xsd:element name="lastname" type="xsd:string"/> </xsd:sequence> </xsd:complexType>
  • 88. Deep  Structure  in  XML  -­‐  File   <?xml version="1.0"?> <students> <student> <name> <firstname>Pekka</firstname> </name> </student> </students>
  • 89. Using  Anonymous  Data  Type:  The  Horror!   <?xml version="1.0"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="students"> <xsd:complexType> <xsd:sequence> <xsd:element name="student"> <xsd:complexType> <xsd:sequence> <xsd:element name="name"> <xsd:complexType> <xsd:sequence> <xsd:element name="firstname" type="xsd:string"/> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema>
  • 90. "There  is  an  error  in  my  schema,  could  you  find  it   for  me?"   <?xml version="1.0"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="students"> <xsd:complexType> <xsd:sequence> <xsd:element name="student"> <xsd:complexType> <xsd:sequence> <xsd:element name="name"> <xsd:complexType> <xsd:sequence> <xsd:element name="firstname" type="xsd:string"/> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:complexType> </xsd:element> </xsd:schema>
  • 91. Use  Named  Datatypes!  It's  easier  to  find  errors..   <?xml version="1.0"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="students" type="students_type" /> <xsd:complexType name="students_type"> <xsd:sequence> <xsd:element name="student" name="student_type" /> </xsd:sequence> </xsd:complexType> <xsd:complexType name="student_type"> <xsd:sequence> <xsd:element name="name" name="name_type" /> </xsd:sequence> </xsd:complexType> <xsd:complexType name="name_type"> <xsd:sequence> <xsd:element name="firstname" name="xsd:string" /> </xsd:sequence> </xsd:complexType> </xsd:schema>
  • 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>
  • 93. Alribute   •  XML   –  <student id="A1">...</student> •  Schema   <xsd:element name="student" type="student_type" /> <xsd:complexType name="student_type"> <xsd:sequence> ... </xsd:sequence> <xsd:attribute name="id" type="xsd:ID"/> </xsd:complexType>          
  • 94. Empty  Element  with  Alribute   •  XML   – <student id="A1" /> •  Schema   <xsd:element name="student" type="student_type" /> <xsd:complexType name="student_type"> <xsd:attribute name="id" type="xsd:ID"/> </xsd:complexType>          
  • 95. EXERCISE  2:  XML  AND  SCHEMA  
  • 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.
  • 99. JAXB  Binding   book.xsd   book.xml   book.java  (class)   new  Book();  
  • 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); } }
  • 105. Result  and  unmarshal   <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <persons> <person id="1"> <name>jack</name> <age>28</age> </person> <person id="2"> <name>tina</name> <age>29</age> </person> <person id="3"> <name>john</name> <age>45</age> </person> <person id="4"> <name>samantha</name> <age>19</age> </person> </persons>
  • 106. Unmarshal   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 ); System.out.println( persons.getPersons().get(0).getName() ); // jack } }
  • 107. Java  Architecture  for  XML  Binding  (JAXB)   •  JAXB  gives  you  the  tools  to     – Transform  Schema  file  (.xsd)  to  classes  (.java)   •  xjc polygon.xsd – Transform  classes  (.java)  to  Schema  (.xsd)   •  schemagen Class1.java ... ClassN.java
  • 108. Generate  Schema  From  Classes   > schemagen Persons.java Person.java > cat schema1.xsd <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="Person" type="person"/> <xs:element name="persons" type="persons"/> <xs:complexType name="persons"> <xs:sequence> <xs:element name="person" type="person" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> <xs:complexType name="person"> <xs:sequence> <xs:element name="name" type="xs:string" minOccurs="0"/> <xs:element name="age" type="xs:int"/> </xs:sequence> <xs:attribute name="id" type="xs:int" use="required"/> </xs:complexType> </xs:schema>
  • 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); } }
  • 116. W3C  SOAP  WEB  SERVICES  AND  XML  
  • 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  
  • 121. <definitions name="HelloService" > <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> <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>
  • 122. Tes;ng  StockQuote   •  WSDL  file   –  http://www.webservicex.net/stockquote.asmx?WSDL •  Opera;on  GetQuote –  http://www.webservicex.net/stockquote.asmx? op=GetQuote
  • 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
  • 129. HTTP  Response   HTTP/1.0 200 OK Date: Fri, 31 Dec 1999 23:59:59 GMT Content-Type: text/html Content-Length: 1354 <html> <body> <h1>Web Page</h1> (more file contents) . . . </body> </html>
  • 130. HTTP  Response   HTTP/1.0 200 OK Date: Fri, 31 Dec 2015 23:59:59 GMT Content-Type: image/png Content-Length: 1354 10100111010101010101001011111....
  • 131. HTTP  Response   HTTP/1.0 200 OK Date: Fri, 31 Dec 2015 23:59:59 GMT Content-Type: text/xml Content-Length: 1354 <books><book>...</book></books>
  • 132. Soap  1.2  Client  Message  in  HTTP   POST /stockquote.asmx HTTP/1.1 Host: www.webservicex.net 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> <GetQuote xmlns="http://www.webserviceX.NET/"> <symbol>aapl</symbol> </GetQuote> </soap12:Body> </soap12:Envelope>
  • 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?  
  • 135. JAVA  WEB  SERVICE  CLIENT:  SAAJ  
  • 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.*
  • 138. import  javax.xml.soap.*;   import  java.io.*;   import  javax.xml.parsers.*;   import  javax.xml.transform.*;   import  org.w3c.dom.*;   import  org.xml.sax.*;   import  javax.xml.transform.stream.*;     class  Main  {          public  static  void  main(String  args[])  throws  Exception  {                  //  Create  SOAP  Connection                  SOAPConnectionFactory  soapConnectionFactory  =  SOAPConnectionFactory.newInstance();                  SOAPConnection  soapConnection  =  soapConnectionFactory.createConnection();                    //  Send  SOAP  Message  to  SOAP  Server                  String  url  =  "http://www.webservicex.net/stockquote.asmx";                    //  Sends  the  given  message  to  the  specified  endpoint  and  blocks  until  it  has  returned  the  response.                  //  Prints  also  the  the  request  SOAP  message                  SOAPMessage  soapResponse  =  soapConnection.call(createSOAPRequest(),  url);                    //  print  SOAP  Response                  System.out.println("Response  SOAP  Message:");                    //soapResponse.writeTo(System.out);                  //  Pretty  print                  System.out.println(  prettyPrint(soapResponse)  );                    String  price  =  getMyResult(soapResponse);                    System.out.println("price  =  "  +  price);                    soapConnection.close();          }    
  • 139. private  static  SOAPMessage  createSOAPRequest()  throws  Exception  {          MessageFactory  messageFactory  =  MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);          SOAPMessage  soapMessage  =  messageFactory.createMessage();          SOAPPart  soapPart  =  soapMessage.getSOAPPart();            String  serverURI  =  "http://www.webserviceX.NET/";            //  SOAP  Envelope          SOAPEnvelope  envelope  =  soapPart.getEnvelope();          envelope.addNamespaceDeclaration("w",  serverURI);            //  SOAP  Body          SOAPBody  soapBody  =  envelope.getBody();          SOAPElement  soapBodyElem  =  soapBody.addChildElement("GetQuote",  "w");          SOAPElement  soapBodyElem1  =  soapBodyElem.addChildElement("symbol",  "w");          soapBodyElem1.addTextNode("aapl");            soapMessage.saveChanges();            /*  Print  the  request  message  */          System.out.print("Request  SOAP  Message:");          //  soapMessage.writeTo(System.out);          System.out.println(  prettyPrint(soapMessage)  );          System.out.println();            return  soapMessage;   }   <?xml version="1.0" encoding="UTF-8" standalone="no"?> <env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:w="http://www.webserviceX.NET/"> <env:Header/> <env:Body> <w:GetQuote> <w:symbol>aapl</w:symbol> </w:GetQuote> </env:Body> </env:Envelope>
  • 140. //  Using  DOM  to  fetch  the  content  of  the  given  XML   private  static  String  getMyResult(  SOAPMessage  soapResponse  )  throws  Exception  {          SOAPBody  body  =  soapResponse.getSOAPBody();            String  xmlString  =  body.getElementsByTagName("GetQuoteResult").item(0).getTextContent();            System.out.println("Content  XML:");          System.out.println(xmlString);          System.out.println();            DocumentBuilderFactory  factory  =  DocumentBuilderFactory.newInstance();          DocumentBuilder  builder  =  factory.newDocumentBuilder();          Document  document  =  builder.parse(  new  InputSource(  new  StringReader(  xmlString  )  )  );            return  document.getElementsByTagName("Last").item(0).getTextContent();   }     <?xml version="1.0" encoding="UTF-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap- envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/ XMLSchema"> <soap:Body> <GetQuoteResponse xmlns="http://www.webserviceX.NET/"> <GetQuoteResult>&lt;StockQuotes&gt;&lt;Stock&gt;&lt;Symbol&gt;aapl&lt;/Symbol&gt;&lt;Last&gt; 124.50&lt;/Last&gt;&lt;Date&gt;7/24/2015&lt;/Date&gt;&lt;Time&gt;4:00pm&lt;/ Time&gt;&lt;Change&gt;-0.66&lt;/Change&gt;&lt;Open&gt;125.43&lt;/Open&gt;&lt;High&gt;125.74&lt;/ High&gt;&lt;Low&gt;123.90&lt;/Low&gt;&lt;Volume&gt;42162332&lt;/Volume&gt;&lt;MktCap&gt;709.99B&lt;/ MktCap&gt;&lt;PreviousClose&gt;125.16&lt;/PreviousClose&gt;&lt;PercentageChange&gt;-0.53%&lt;/ PercentageChange&gt;&lt;AnnRange&gt;93.28 - 134.54&lt;/AnnRange&gt;&lt;Earns&gt;8.65&lt;/ Earns&gt;&lt;P-E&gt;14.40&lt;/P-E&gt;&lt;Name&gt;Apple Inc.&lt;/Name&gt;&lt;/Stock&gt;&lt;/ StockQuotes&gt;</GetQuoteResult> </GetQuoteResponse> </soap:Body> </soap:Envelope>
  • 141. //  Using  DOM  to  fetch  the  content  of  the  given  XML   private  static  String  getMyResult(  SOAPMessage  soapResponse  )  throws  Exception  {          ...          return  document.getElementsByTagName("Last").item(0).getTextContent();   }     <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/ XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <GetQuoteResponse xmlns="http://www.webserviceX.NET/"> <GetQuoteResult> <StockQuotes> <Stock> <Symbol>aapl</Symbol> <Last>124.50</Last> <Date>7/24/2015</Date> <Time>4:00pm</Time> <Change>-0.66</Change> <Open>125.43</Open> <High>125.74</High> <Low>123.90</Low> <Volume>42162332</Volume> <MktCap>709.99B</MktCap> <PreviousClose>125.16</PreviousClose> <PercentageChange>-0.53%</PercentageChange> <AnnRange>93.28 - 134.54</AnnRange> <Earns>8.65</Earns> <P-E>14.40</P-E> <Name>Apple Inc.</Name> </Stock> </StockQuotes> </GetQuoteResult> </GetQuoteResponse> </soap:Body> </soap:Envelope>
  • 142.   //  Helper  method  for  pretty  print  xml   public  static  String  prettyPrint(SOAPMessage  soapMessage)  {          try  {                    TransformerFactory  tff  =  TransformerFactory.newInstance();                  Transformer  tf  =  tff.newTransformer();                  tf.setOutputProperty(OutputKeys.INDENT,  "yes");                  tf.setOutputProperty("{http://xml.apache.org/xslt}indent-­‐amount",                                  "2");                  Source  sc  =  soapMessage.getSOAPPart().getContent();                  ByteArrayOutputStream  streamOut  =  new  ByteArrayOutputStream();                  StreamResult  result  =  new  StreamResult(streamOut);                  tf.transform(sc,  result);                    String  strMessage  =  streamOut.toString();                  return  strMessage;          }  catch  (Exception  e)  {                  System.out.println("Exception  in  getSOAPMessageAsString  "                                  +  e.getMessage());                  return  null;          }   }    
  • 143. EXERCISE  4:  WEATHER  SAAJ  CLIENT  
  • 144. CREATING  SAAJ  WEB  SERVER  
  • 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  
  • 149. WEB-­‐INF/web.xml   <web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http:/java.sun.com/dtd/web-app_2_3.dtd"> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-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  
  • 153. ant:  build.xml   <project default="main"> <target name="compile"> <mkdir dir="war/WEB-INF/classes"/> <javac includeantruntime="false" srcdir="src/" destdir="war/WEB-INF/classes"> <classpath> <pathelement path="${classpath}"/> <pathelement location="/path/to/glassfish4/glassfish/lib/javax.servlet-api.jar"/> </classpath> </javac> </target> <target name="war"> <jar destfile="WebServiceProvider.war" basedir="war/." /> </target> <target name="deploy"> <exec executable="asadmin.bat"> <arg value="deploy"/> <arg value="--force=true"/> <arg value="WebServiceProvider.war"/> </exec> </target> <target name="main" depends="compile,war,deploy"/> </project> Change   "admin.bat"  to   "admin"  if  in  Mac  -­‐   environment  
  • 155. public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); printResponse(response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/soap+xml"); printResponse(response); } public void printResponse(HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); String output = getSoapOutput(); out.println(output); out.flush(); out.close(); } public String getSoapOutput() { String response = "<?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>" + "<GetSomething xmlns='http://www.somecompany.com/'>" + "<Result>Hello</Result>" + "</GetSomething>" + "</soap12:Body>" + "</soap12:Envelope>"; return response; } }
  • 156. public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { response.setContentType("application/soap+xml"); SOAPMessage message = createMessage(request); message.writeTo(response.getOutputStream()); } catch (Exception e) { e.printStackTrace(); } } // <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> // <SOAP-ENV:Header/> // <SOAP-ENV:Body/> // </SOAP-ENV:Envelope> public SOAPMessage createMessage(HttpServletRequest request) throws Exception { MessageFactory mf = MessageFactory.newInstance(); SOAPMessage soapMessage = mf.createMessage(); return soapMessage; } }
  • 157. //  <SOAP-­‐ENV:Envelope  xmlns:SOAP-­‐ENV="http://schemas.xmlsoap.org/soap/envelope/">   //  <SOAP-­‐ENV:Header/>   //  <SOAP-­‐ENV:Body>   //          <soa:Result  xmlns:soa="http://www.somecompany.com">Hello</soa:Result>   //  </SOAP-­‐ENV:Body>   //  </SOAP-­‐ENV:Envelope>   public  SOAPMessage  createMessage(HttpServletRequest  request)  throws  Exception  {          MessageFactory  mf  =  MessageFactory.newInstance();          SOAPMessage  soapMessage  =  mf.createMessage();            //  Gets  the  SOAP  part  of  this  SOAPMessage  object.          SOAPPart  sp          =  soapMessage.getSOAPPart();          SOAPEnvelope  se  =  sp.getEnvelope();          SOAPBody  sb          =  se.getBody();            Name  bn  =  se.createName("Result",  "soa",  "http://www.somecompany.com");          SOAPBodyElement  e  =  sb.addBodyElement(bn);          e.addTextNode("Hello");            soapMessage.saveChanges();            return  soapMessage;   }  
  • 158. EXERCISE  5:  WEB  SERVICE   PROVIDER  
  • 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); } }
  • 169. EXERCISE  6  &  7  
  • 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  
  • 173. Example:  REST  +  XML  
  • 174. Example:  REST  +  XML  
  • 175. Example:  REST  +  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; } }
  • 188. REST  JAVA  SERVER  EXAMPLE  
  • 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); } }