Service Oriented Architecture

quaggahooliganInternet and Web Development

Feb 5, 2013 (4 years and 6 months ago)

132 views

95
-
733 Internet Technologies

1

Master of Information System
Management

95
-
733 Internet Technologies

Lecture 1: Introduction

95
-
733 Internet Technologies

2

Master of Information System
Management

Course Web Site


http://www.andrew.cmu.edu/~mm6





95
-
733 Internet Technologies

3

Master of Information System
Management

Prerequisites


The ability to program in Java


Exposure to distributed systems
concepts
-

perhaps through


95
-
702 Distributed Systems


Enthusiasm for programming

95
-
733 Internet Technologies

4

Master of Information System
Management


Specific Technologies


Netbeans and Glassfish


JavaScript, Servlets and Java Server Pages


XML (various languages)


AJAX


Mashups


Freebase


Ruby


Frameworks


Ruby on Rails


Grammars
-

DTD

s and XSDL


XML Transformation
-

XSLT


Semantic Web


OWL, RDF, Protégé, Jena



95
-
733 Internet Technologies

5

Master of Information System
Management

Structure of the Course


Lectures / class participation


Demonstrations


Homework (programming)


Midterm


Final examination

95
-
733 Internet Technologies

6

Master of Information System
Management

Readings


Readings from the required text are assigned for each
lecture
--

read them in advance


Readings from the web also assigned


For this week read

Programming the World Wide Web

,
7
th

ed. Chapters 1, 2 and 3. Especially chapter 3 on
CSS.


For next week read

Programming the World Wide
Web

, 7
th

ed. chapters 4, 5 and 10.


Chapters 4 and 5 are on JavaScript


Chapter 10 covers AJAX.


Read the article by Philip McCarthy of IBM on AJAX

95
-
733 Internet Technologies

7

Master of Information System
Management

Grading


Homework/Programming (3
-
5) 50%


One of the homework problems is designed by
the student. A presentation and demonstration
is required. See me soon about your topic.


For the student designed homework, groups of
one or two are permitted.


Midterm 10%


Final Exam 40%

95
-
733 Internet Technologies

Some Suggested Topics For
Student Assigned Homework


Explore one of the many XML languages
in more detail than we do in class.


Discuss and demonstrate an HTML5
element (audio, video, time, canvas).


HTML5 document structure


HTML5 Local storage.


Flash, PhoneGap, GWT, Jquery, etc…


Many other options exist. See the
schedule for projects from previous
terms..

8

Master of Information System
Management

95
-
733 Internet Technologies

9

Master of Information System
Management

Rich Internet Applications


The traditional web employed thin
clients.


In RIA, the browser is extended by
downloaded code.


With AJAX, the downloaded code
interacts with the server
asynchronously.


This makes for a more responsive
web.


95
-
733 Internet Technologies

10

Master of Information System
Management

RIA Using Ajax

Asynchronous Java Script and XML



Why bother?


-

Everyone loves the browser but


communication with the server is


coarse
-
grained. A full page reload


interrupts the interaction flow.


Example Applications: (Web 2.0)


-

Google Maps runs in a browser but


behaves like an application.


-

Flikr photo sharing, Google Maps,


etc.. use AJAX.



95
-
733 Internet Technologies

AJAX


Typically uses JavaScript or VBScript on the client side.


The server side might be in any language, e.g., PHP, ASP.NET,
or Java.


Any XML document or text may be returned to the caller.
Simple text, JavaScript Object Notation (JSON) or XML is
common.


Client
-
side toolkits like Dojo or Prototype may be used.


Frameworks (RoR, JSF, etc.,) support Ajax.


Normally, requests may only go back to the originating


server.


However, mashups (combining diverse site output) may still
be constructed by having the originating server make calls to
other servers.


Mashups may also be built with a dynamic <script> tag.


Ajax is important to mobile phones.


See www.openajax.org



11

Master of Information System
Management

95
-
733 Internet Technologies

Before We Start


A
servlet

is Java code that runs on
the server when an HTTP request
arrives.


A
Java Server Page
(JSP) is
XHTML+ Java and is compiled to a
servlet.


JavaScript

is not Java and runs in
the browser.


XHTML

is one of many XML
languages

12

Master of Information System
Management

95
-
733 Internet Technologies

13

Master of Information System
Management


This is a UML

sequence diagram.


This shows a

typical AJAX

round trip.


A solid arrowhead

represents a

synchronous

call.


A stick

arrowhead

represents an

asynchronous

signal.

95
-
733 Internet Technologies

14

Master of Information System
Management

Typical Ajax(1)


1.
Javascript and HTML is delivered to the
browser.

2. The JavaScript code is pointed to by


a <script> tag.

3. The HTML defines a button that


calls a function.


95
-
733 Internet Technologies

15

Master of Information System
Management

Typical Ajax(2)

4. Within the function (which may be


passed a URL with GET data) a


browser dependent request object is


created with a URL (and, perhaps,


GET data).

5. A handler is defined.

6. The request object is told about the


handler.

7. The request object is told to send a


post or get request asynchronously.


95
-
733 Internet Technologies

16

Master of Information System
Management

Typical Ajax(3)

8. If POST is used, the send method is


called on the request object


with the POST data.

9. The handler executes on various state


changes in the request object.

10.The handler accesses the server


response by asking the request


object first for its state (and if it's


ready with no errors) its response.

95
-
733 Internet Technologies

17

Master of Information System
Management

Typical Ajax(4)

11. The response may be text,


or XML or JSON.

12. The handler performs some


action on the browser. This


action may alter the HTML's


DOM and change what the


browser displays.


95
-
733 Internet Technologies

18

Master of Information System
Management

The XMLHttpRequest Object as
Described by W3C


The
XMLHttpRequest

interface can be used by
scripts to programmatically connect to their
originating server via HTTP.


Implements an interface exposed by a
scripting engine.


Supports any text format (not only
XML).


Supports HTTP and HTTPS.


The term

Request


should be broadly
defined to include Request and
Response.

95
-
733 Internet Technologies

19

Master of Information System
Management

W3C Example 1

Some simple JavaScript code to do

something with data from

an XML document fetched over

the network:


function test(data) {


// taking care of data

}

95
-
733 Internet Technologies

20

Master of Information System
Management

function handler() {


if(this.readyState == 4 &&


this.status == 200) {


// so far so good


if(this.responseXML != null &&


this.responseXML.getElementById('test').firstChild.data)


// success!


test(this.responseXML.getElementById('test').firstChild.data);


else


test(null);


} else if (this.readyState == 4 && this.status != 200) {


// fetched the wrong page or network error...


test(null);


}

}

var client = new XMLHttpRequest();

client.onreadystatechange = handler;

client.open("GET", "test.xml");

client.send();


95
-
733 Internet Technologies

21

Master of Information System
Management

W3C Example 2

If you just want to ping the server with a message you could

do something like:


function ping(message) {


var client = new XMLHttpRequest();


client.open("POST", "/ping");


client.send(message);

}

We are not establishing a callback

handler.

95
-
733 Internet Technologies

22

Master of Information System
Management

W3C Example 3

Or, if you want to check the status of a document on the server,

you can make a head request.


function fetchStatus(address) {


var client = new XMLHttpRequest();


client.onreadystatechange = function() {


if(this.readyState == 4)


returnStatus(this.status);


}


client.open("HEAD", address);


client.send();

}

95
-
733 Internet Technologies

23

Master of Information System
Management

State and State Change

The state of the object. The readyState attribute must be

one of the following values:


0 Uninitialized
The initial value.


1 Open
The
open()

method has been successfully called.


2 Sent
The user agent successfully acknowledged the


request.


3 Receiving
Immediately before receiving the message


body (if any). All HTTP headers have been received.


4 Loaded
The data transfer has been completed.


When
readyState

changes value a
readystatechange



event is to be dispatched on the
XMLHttpRequest

object.

95
-
733 Internet Technologies

24

Master of Information System
Management

Typical Interaction

HTML Button

JavaScript function

XMLHTTPRequest

post

XML

handler

-

Executed on

state change.

-

this.responseXML

points to the root

of the XML

-
write HTML to

HTML DOM

95
-
733 Internet Technologies

25

Master of Information System
Management

A Complete Example From IBM

Demonstrations:




See article by Philip McCarthy on Ajax at:


http://www.ibm.com/developerworks/library/j
-
ajax1/




Eclipse workspace mm6/95
-
733


Visit
http://localhost:8080/AjaxProject/index.jsp



Netbeans workspace mm6/95
-
733/AjaxUsingNetbeans


ACoolAjaxShoppingCart and


ACoolAjaxShoppingCartImproved



95
-
733 Internet Technologies

26

Master of Information System
Management

Main Features of Index.jsp (1)


<%@
page
import
=
"java.util.*"
%>


<%@
page
import
=
"developerworks.ajax.store.*"
%>

This page needs access to these imported Java packages.

The store package contains

Item.java, Catalog.java and Cart.java

95
-
733 Internet Technologies

27

Master of Information System
Management

Main Features of Index.jsp (2)


<
script
type
=
"text/
javascript
"


language
=
"
javascript
"
src
=
"ajax1.js"
>


</
script
>


<
script
type
=
"text/
javascript
"


language
=
"
javascript
"
src
=
"
cart.js
"
>


</
script
>



This is not constrained by the same origin


policy!

The header holds pointers to script code to be included in the

page and then executed by the browser.

95
-
733 Internet Technologies

28

Master of Information System
Management

Main Features of Index.jsp (3)


<
tbody
>



<%


for

(Iterator<Item> I =


new

Catalog().getAllItems().iterator();


I.hasNext() ; ) {


Item item = I.next();


%>



The table body tag encloses table rows that are generated on

the server. This is Java (part of JSP) and is not JavaScript.


95
-
733 Internet Technologies

29

Master of Information System
Management

Main Features of Index.jsp (4)


<!
--

For each Item do
--
>


<
tr
>


<
td
>
<%=

item.getName()
%>
</
td
>


<
td
>
<%=

item.getDescription()
%>
</
td
>


<
td
>
<%=

item.getFormattedPrice()
%>
</
td
>


<
td
>


<
button
onclick
="
addToCart('
<%=

item.getCode()
%>
')
"
>


Add to Cart


</
button
>


</
td
>


</
tr
>


<%

}
%>

</
tbody
>


The
addToCart

call is a call on JavaScript.

95
-
733 Internet Technologies

30

Master of Information System
Management

Main Features of Index.jsp (5)

The <ul> and <span> tags each have a unique identifier.

These identifier will be used by the event handler.

<
div
style
=



>


<
h2
>
Cart Contents
</
h2
>


<
ul
id
=
"contents"
></
ul
>


Total cost:


<
span
id
=
"total"
>
$0.00
</
span
>

</
div
>

95
-
733 Internet Technologies

31

Master of Information System
Management

Main Features of Item.java

package

developerworks.ajax.store;


import

java.math.BigDecimal;


public

class

Item {


private

String
code
;


private

String
name
;


private

String
description
;


private

int

price
;



public

Item(String code,String name,String description,
int

price) {


this
.
code
=code;


this
.
name
=name;


this
.
description
=description;


this
.
price
=price;


}



public

String getCode() {


return

code
;


}

Getter and setters on

code, name,description

and price.

95
-
733 Internet Technologies

32

Master of Information System
Management

Main Features of Catalog.java(1)

package

developerworks.ajax.store;

import

java.util.*;

public

class

Catalog {



private

static

Map<String,Item>
items
;



static

{


items

=
new

HashMap<String,Item>();


items
.put(
"hat001"
,
new

Item(
"hat001"
,


"Hat"
,
"Stylish bowler hat (SALE!)"
,


1999));


:

}


95
-
733 Internet Technologies

33

Master of Information System
Management

Main Features of Catalog.java(2)



public

Collection<Item> getAllItems() {


return

items
.values();


}



public

boolean

containsItem(String itemCode)


{


return

items
.containsKey(itemCode);


}



public

Item getItem(String itemCode) {


return

items
.get(itemCode);


}

}


95
-
733 Internet Technologies

34

Master of Information System
Management

Main Features of Cart.java(1)

package developerworks.ajax.store;


public class Cart {



private HashMap<Item,Integer> contents;


public Cart() {


contents = new HashMap<Item,Integer>();


}



95
-
733 Internet Technologies

Main Features of Cart.java(2)

35

Master of Information System
Management


public void addItem(String itemCode) {


Catalog catalog = new Catalog();


if (catalog.containsItem(itemCode)) {


Item item = catalog.getItem(itemCode);


int newQuantity = 1;


if (contents.containsKey(item)) {


Integer currentQuantity = contents.get(item);


newQuantity += currentQuantity.intValue();


}


contents.put(item, new Integer(newQuantity));


}


}

95
-
733 Internet Technologies

36

Master of Information System
Management

Main Features of Cart.java(3)


public String toXml() {




StringBuffer xml = new StringBuffer();


xml.append("<?xml version=
\
"1.0
\
"?>
\
n");


xml.append("<cart generated=
\
""+


System.currentTimeMillis()+


"
\
" total=
\
""+getCartTotal()+"
\
">
\
n");



for (Iterator<Item> I = contents.keySet().iterator() ; I.hasNext() ; ) {


Item item = I.next();


int itemQuantity = contents.get(item).intValue();



xml.append("<item code=
\
""+item.getCode()+"
\
">
\
n");


xml.append("<name>");


:


xml.append("</cart>
\
n");


return xml.toString();


}


95
-
733 Internet Technologies

37

Master of Information System
Management

Main Features of
CartServlet.java(1)


private Cart getCartFromSession(HttpServletRequest req)


{


HttpSession session = req.getSession(true);


Cart cart = (Cart)session.getAttribute("cart");


if (cart == null) {


cart = new Cart();


session.setAttribute("cart", cart);


}


return cart;

}

95
-
733 Internet Technologies

38

Master of Information System
Management

Main Features of
CartServlet.java(2)


public

void

doPost(HttpServletRequest req,


HttpServletResponse res)


throws

java.io.IOException {



Enumeration headers = req.getHeaderNames();


while

(headers.hasMoreElements()) {


String header =(String) headers.nextElement();


System.
out
.println(header+
":


"
+req.getHeader(header));


}



Cart cart = getCartFromSession(req);



String action = req.getParameter(
"action"
);


String item = req.getParameter(
"item"
);





95
-
733 Internet Technologies

39

Master of Information System
Management

Main Features of
CartServlet.java(3)


if

((action !=
null
)&&(item !=
null
)) {



if

(
"add"
.equals(action)) {


cart.addItem(item);



}
else

if

()…..


}



String cartXml = cart.toXml();


res.setContentType(
"text/xml"
);


res.getWriter().write(cartXml);


}


95
-
733 Internet Technologies

40

Master of Information System
Management

Main Features Axis1.js (1)

/*


* Returns an new XMLHttpRequest object, or false if the browser


* doesn't support it


*/

function newXMLHttpRequest() {



var xmlreq = false;



// Create XMLHttpRequest object in non
-
Microsoft browsers


if (window.XMLHttpRequest) {


xmlreq = new XMLHttpRequest();


}

95
-
733 Internet Technologies

41

Master of Information System
Management

Main Features Axis1.js (2)


else if (window.ActiveXObject) {


try {


// Try to create XMLHttpRequest in later versions of Internet Explorer


xmlreq = new ActiveXObject("Msxml2.XMLHTTP");


} catch (e1) { // Failed to create required ActiveXObject


try {


// Try version supported by older versions of Internet Explorer


xmlreq = new ActiveXObject("Microsoft.XMLHTTP");


} catch (e2) {


// Unable to create an XMLHttpRequest by any means


xmlreq = false;


}


}


}



95
-
733 Internet Technologies

42

Master of Information System
Management

Main Features Axis1.js (3)



/* Returns a function that waits for the specified


XMLHttpRequest to complete, then passes it XML response


to the given handler function.


req
-

The XMLHttpRequest whose state is changing


responseXmlHandler
-

Function to pass the XML response to


*/



function getReadyStateHandler(req, responseXmlHandler) {




95
-
733 Internet Technologies

43

Master of Information System
Management

Main Features Axis1.js (4)



// Return an anonymous function that listens to the


// XMLHttpRequest instance




return function () {


// If the request's status is "complete"


if (req.readyState == 4) {


// Check that we received a successful response from the server


if (req.status == 200) {


// Pass the XML payload of the response to the handler


// function.


responseXmlHandler(req.responseXML);


} else {


// An HTTP problem has occurred


alert("HTTP error "+req.status+": "+req.statusText);


}}}}


95
-
733 Internet Technologies

44

Master of Information System
Management

Main Features Cart.js (1)


// Timestamp of cart that page was last updated with


var lastCartUpdate = 0;



// Adds the specified item to the shopping cart, via Ajax call


// itemCode
-

product code of the item to add



function addToCart(itemCode) {


var req = newXMLHttpRequest();


req.onreadystatechange = getReadyStateHandler(req, updateCart);


req.open("POST", "cart.do", true);


req.setRequestHeader("Content
-
Type", "application/x
-
www
-
form
-
urlencoded");


req.send("action=add&item="+itemCode);

}


Establish handler

and pack up and

send the request.

95
-
733 Internet Technologies

45

Master of Information System
Management

Main Features Cart.js (2)

/*


* Update shopping
-
cart area of page to reflect contents of cart


* described in XML document.


*/

function updateCart(cartXML) {


var cart = cartXML.getElementsByTagName("cart")[0];


var generated = cart.getAttribute("generated");


if (generated > lastCartUpdate) {


lastCartUpdate = generated;


var contents = document.getElementById("contents");


contents.innerHTML = "";



95
-
733 Internet Technologies

46

Master of Information System
Management

Main Features Cart.js (3)


var items = cart.getElementsByTagName("item");


for (var I = 0 ; I < items.length ; I++) {


var item = items[I];


var name = item.getElementsByTagName("name")[0].firstChild.nodeValue;


var quantity = item.getElementsByTagName("quantity")[0].firstChild.nodeValue;


var listItem = document.createElement("li");


listItem.appendChild(document.createTextNode(name+" x "+quantity));


contents.appendChild(listItem);


}


}


document.getElementById("total").innerHTML = cart.getAttribute("total");

}




95
-
733 Internet Technologies

47

Master of Information System
Management

Shopping Cart Interaction

HTML Button

addToCart(itemCode)

XMLHTTPRequest

post

XML

Anonymous handler

-

Executed on


state change.

-

req.responseXML


points to the root


of the XML

-

calls updateCart


UpdateCart


reads XML


writes HTML



95
-
733 Internet Technologies

48

Master of Information System
Management

Main Features Cart.js (4)


The handler is reading data with the following format:


<?xml version="1.0"?>

<cart generated="1200367057873" total="$19.99">

<item code="str001">

<name>String</name>

<quantity>1</quantity>

</item>

</cart>



95
-
733 Internet Technologies

49

Master of Information System
Management

Another Example From
Sebesta Chapter 10

A form is required to collect name, address, zip, city, and state.


The zip code entry causes an asynchronous call on a servlet

to automatically complete the city and state fields.


The asynchronous call is made when the user blurs (or moves

away from) the zip code field.


This demo is in the Netbeans project

mm6/www/95
-
733/AjaxUsingNetbeans/SebestaAjaxExample.

95
-
733 Internet Technologies

50

Master of Information System
Management

Index.jsp Main Features


<tr>


<td> Zip Code: </td>


<td> <input type = "text" name="zip" size = "10"


onblur = "getPlace(this.value)
" />


</td>


</tr>


<tr>


<td> City </td>


<td> <input type = "text" name="city"
id= "city"

size = "30" /> </td>


</tr>


<tr>


<td> State </td>


<td> <input type = "text" name="state"
id="state"

size = "30" /></td>


</tr>

Locations

written to by

ajax handler

95
-
733 Internet Technologies

51

Master of Information System
Management

Javascript Main Features

function getPlace(zip) {


var xhr;




if(window.XMLHttpRequest)


xhr = new XMLHttpRequest();


else


xhr = ActiveXObject("Microsoft.XMLHTTP");


xhr.onreadystatechange = function() {


if(xhr.readyState == 4) {


var result = xhr.responseText;


var place = result.split(', ');


document.getElementById("city").value = place[0];


document.getElementById("state").value = place[1];


}


}


xhr.open("GET", "ZipToCityStateServlet?zip="+zip,true);


xhr.send(null);

}

95
-
733 Internet Technologies

52

Master of Information System
Management

Two Servlets
-

One for
AJAX

protected void processRequest(HttpServletRequest request,


HttpServletResponse response)


throws ServletException, IOException {


response.setContentType("text/html;charset=UTF
-
8");


PrintWriter out = response.getWriter();


try {


// Return simple text to Ajax request


if(request.getParameter("zip").equals("15216"))


out.println("Pittsburgh, PA");


else


out.println("New York, NY");


} finally {


out.close();


}


}

95
-
733 Internet Technologies

53

Master of Information System
Management

Another For the Form

out.println("<h2>Name: " + request.getParameter("name") + "</h2>");

out.println("<h2>Street: " + request.getParameter("street") + "</h2>");

out.println("<h2>Zip: " + request.getParameter("zip") + "</h2>");

out.println("<h2>City: " + request.getParameter("city") + "</h2>");

out.println("<h2>State: " + request.getParameter("state") + "</h2>");

95
-
733 Internet Technologies

XML Or JSON ? (1)

54

Master of Information System
Management

<Person firstName="John" lastName="Smith">


<Address>


<streetAddress>21 2nd Street</streetAddress>


<city>New York</city>


<state>NY</state>


<postalCode>10021</postalCode>


</Address>


<phoneNumber type="home"> 212 555
-
1234 </phoneNumber>


<phoneNumber type="fax"> 646 555
-
4567 </phoneNumber>

</Person>

From Wikipedia.org

95
-
733 Internet Technologies

XML Or JSON ? (2)

55

Master of Information System
Management

{


"firstName": "John", "lastName": "Smith",


"address":


{ "streetAddress": "21 2nd Street",


"city": "New York", "state": "NY",


"postalCode": "10021"


},


"phoneNumbers":


[ { "type": "home", "number": "212 555
-
1234" },


{ "type": "fax", "number": "646 555
-
4567" } ]

}

If this text is in the variable coolText, then we can create a

JavaScript object with the line of code:

var x = eval("(" + coolText + ")");

And access the data with x.phoneNumbers[0].

From Wikipedia.org

95
-
733 Internet Technologies

Which To Use?

56

Master of Information System
Management

95
-
733 Internet Technologies

Which To Use?

57

Master of Information System
Management

JSON has some advantages over XML:



JSON messages are smaller and therefore faster.


Very little parsing is required.


JSON is simpler and simple is good.


XML has some advantages over JSON:



If the document is to be integrated more or less intact, XML is


better. With JSON, you would need to construct the tags.


XSLT can be used to transform a response into an appropriate


format.


XML Signature and XML Encryption not available for JSON.


95
-
733 Internet Technologies

Some Popular Toolkits

58

Master of Information System
Management

Any survey of all of the toolkits would quickly be obsolete.



jQuery

supports Ajax





ASP.NET AJAX


This is the free Microsoft AJAX framework.




Google Web Toolkit (GWT)


Write in Java and generate JavaScript.




Direct Web
Remoting

(DWR)


Easily make calls on Remote Java Objects through


JavaScript.




Dojo


A free JavaScript library increasing the level of abstraction.




Prototype


A JavaScript Framework that aims to ease development


of dynamic web applications.




95
-
733 Internet Technologies

jQuery AJAX Example

59

Master of Information System
Management

<!DOCTYPE html>

<html>

<head>

<script src="jquery.js"></script>

<script>

$(document).ready(function(){


$("button").click(function(){


$("div").load('test1.txt');


});

});

</script>

</head>

<body>


<div><h2>Let AJAX change this text</h2></div>

<button>Change Content</button>


</body>

</html>



From W3C Schools

95
-
733 Internet Technologies

Dojo Ajax Example

60

Master of Information System
Management

dojo.io.bind ( {


url :

getCityState.php?zip=


+ zip,


load: function( type, data, evt ) {


var place = data.split(

,

);


if(dojo.byID(

city

).value =
“”


dojo.byID(

city

).value = place[0];


if(dojo.byID(

state

).value =
“”


dojo.byID(

state

).value = place[1];


},


error: function(type, data, evt ) {


alert(

Error in request, returned data:

+data);


},


method:

GET

,


mimetype:

text/plain



}

);


Note the use of

JSON to describe

an AJAX call.

From Pg. 414

Of Sebesta