Вы находитесь на странице: 1из 45

REST, dojo, JavaFX

Carol McDonald, Java Architect


RESTful Catalog
Dojo client, JAX-RS, JAXB, JPA
Registration Application
JAX-RS class Entity Class

Item DB

ItemsConverter
ItemsResource
JAXB class
Dojo client

2
Example RESTful Catalog

3
Example RESTful Catalog

4
REST and JAX-RS

5
REpresentational State Transfer
Response data =
Get http://petcatalog/items REST Web Service
REpresentational State
Client Transfer Client
State1 State2
REST Tenets
Resources (nouns)
Identified and exposed through web URIs, For example:
http://www.petstore.com/catalog/items
Methods (verbs) small fixed set
HTTP methods POST, GET, PUT, DELETE:
to create, retrieve, update, and delete resources
Representation of the Resource
XML, JSON.. data state exchanged between client and Service
6
HTTP Example
Request
GET /catalog/items HTTP/1.1
Host: petstore.com
Accept: application/xml

Method Resource
Response
HTTP/1.1 200 OK
Date: Tue, 08 May 2007 16:41:58 GMT
Server: Apache/1.3.6
Content-Type: application/xml; charset=UTF-8
State
transfer <?xml version="1.0"?>
<items xmlns="…">
<item>…</item> Representation

</items>
7
Why REST ?
Uniform Interface:
URI is a uniform way to identify resources
HTTP uniform interface to get, update resources
REST base services are easy to work with
Easy to consume and develop
Examples:
Amazon, yahoo, flickr, google

8
Agenda
REST and JAX-RS
Dojo JavaScript RESTful Client
JavaFX RESTful Client
Comet RESTful Client

9
JAX-RS: Clear mapping to REST concepts
High level, Declarative
Uses @ annotation in POJOs
Resources: what are the URIs?
@Path("/items/{id}")
Methods: what are the HTTP methods?
@GET
public XXX find()
Representations: what are the formats?
@Consumes("application/xml")
@Produces("application/json")

10
POJO responds to the URI http://host/catalog/items/
resource
@Path("/items/")
public class ItemsResource {
responds with JSON
Representation
@Produces("application/json")
@GET responds to HTTP GET
method public ItemsConverter get() {
...
}

...
}

11
Example RESTful Catalog

12
URIs and Methods:
Item Catalog Example
/items
GET - list all items
POST – add item to catalog
/items/{id}
GET - get an item representation
PUT - update an item
DELETE – remove an item
http://www.infoq.com/articles/rest-introduction

13
Methods
@Path(“/items”)
class ItemsResource {
@GET Items get() { ... }
@POST Response create(Item) { ... }
}

class ItemResource {
@GET Item get(...) { ... }
@PUT void update(...) { ... }
@DELETE void delete(...) { ... }
} Java method name is not significant
The @HTTP method is the method

14
RESTful Catalog
Dojo client, JAX-RS, JAXB, JPA
Registration Application
JAX-RS class Entity Class

Item DB

ItemsConverter
ItemsResource
JAXB class
Dojo client

15
Entity Classes
Use JPA to map/retrieve data from the database as
entities
expose entities as RESTful resources
entity = resource identified by URL

http://host/catalog/items/123 Item
ID NAME DESC URL

@Entity
public class Item {
@Id
int id;
String name;
String descr;
String url;
}

16
Converter Classes

JAXB to convert the domain objects (JPA entities)


into XML and/or JSON.

JAX-RS class Entity Class

Item DB

ItemsConverter
ItemsResource
JAXB class
Dojo client

17
ItemConverter JAXB annotated
@XmlRootElement(name = "item")
public class ItemConverter {
private Item entity;
private URI uri;

@XmlAttribute
public URI getUri() {
return uri;
}
@XmlElement
public Long getId() {
return (expandLevel > 0) ? entity.getId() : null;
}
...
}

18
XML
<item uri="http://localhost/Web/resources/items/1/">
<description> black cat is nice</description>
<id>1</id>
<imagethumburl>/images/anth.jpg</imagethumburl>
<name>not Friendly Cat</name>
<price>307.10</price>
<productid>feline01</productid>
</item>

19
JSON

{
"@uri":"http://host/catalog/resources/items/1/",
"name":"Friendly Cat",
"description":"This black and white colored cat is super friendly.",
"id":"1",
"imageurl":"http://localhost:8080/CatalogService/images/anthony.jpg"
}

20
ItemsConverter JAXB annotated
@XmlRootElement(name = "items")
public class ItemsConverter {
private Collection<ItemConverter> items;
private URI uri;

@XmlAttribute
public URI getUri() {
return uri;
}
@XmlElement
public Collection<ItemConverter> getItem() {
...
return items;
}
}

21
XML
<?xml version="1.0" encoding="UTF-8"?>
<items uri="http://localhost/Web/resources/items/">
<item uri="http://localhost/Web/resources/items/1/">
<description> black cat is nice</description>
<id>1</id>
<imagethumburl>/images/anth.jpg</imagethumburl>
<name>not Friendly Cat</name>
<price>307.10</price>
<productid>feline01</productid>
</item>
<item
. . .
</item>
</items>

22
JSON

{
"@uri":"http://host/catalog/resources/items/",
"item":[
{"@uri":"http://host/catalog/resources/items/1/",
"name":"Friendly Cat",
"description":"This black and white colored cat is super friendly.",
"id":"1",
"imageurl":"http://localhost:8080/CatalogService/images/anthony.jpg"},
{"@uri":"http://host/catalog/resources/items/2/",
"name":"Fluffy Cat",
"description":"A great pet for a hair stylist!
"id":"2",
"imageurl":"http://localhost:8080/CatalogService/images/bailey.jpg"}
]
}

23
Resource Classes
Items Resource retrieves updates a collection of Item entities
/items – URI for a list of Items
Item resource retrieves or updates one Item entity
/item/1 – URI for item 1

JAX-RS class Entity Class

Item DB

ItemsConverter
ItemsResource
JAXB class
Dojo client

24
Get Items responds to the URI http://host/catalog/items/

@Path("/items/") responds to HTTP GET


public class ItemsResource { responds with JSON
@Context
protected UriInfo uriInfo; JAXB class
@GET
@Produces("application/json")
public ItemsConverter get(){
return new ItemsConverter(
getEntities(), uriInfo.getAbsolutePath());

}
Performs JPA
Query, returns list
of entities

25
Example RESTful Catalog
http://weblogs.java.net/blog/caroljmcdonald/archive/2008/08/a_restful_pet_c.html

26
Dojo Client Side
JavaScript Library

27
The dojo Widget Library

28
Example RESTful Catalog

29
Dojo client index.html
<button dojoType="dijit.form.Button"
onclick="next">
Next Grid widget model=data to display in grid
</button>

<div id="grid" dojoType="dojox.Grid" model="model"


structure="layout" autoWidth="true" >

structure=layout for Grid

http://weblogs.java.net/blog/caroljmcdonald/archive/2008/08/a_restful_pet_c.html

30
Dojo client.js
formatImage = function(value) {
if (!value)
return '&nbsp;';
return "<img src='" + value + "'/>";
};
// Data Grid layout
// A grid view is a group of columns
var view1 = {
cells: [
[
{name: 'Name', field: "name"},
{name: 'Description', field: "description"},
{name: 'Photo',field: "imagethumburl",
formatter: formatImage, },
{name: 'Price',field: "price"}
]
]
}; layout for Grid
// a grid layout is an array of views.
var layout = [ view1 ];
// the model= collection of objects to be displayed in the grid
model = new dojox.grid.data.Objects(null,null);
model=data to display in grid 31
RESTful Pet Catalog Web Service
HTTP GET
http://petstore/catalog/resources/items/

Addressable
Client Resources

Response JSON items


Server Web Container
{"url":"http://store/catalog/item1",
{"url":"http://store/catalog/item2"}

32
Traditional Web AJAX
within a browser,
there is AJAX engine

33
Dojo Client
Use dojo.xhrGet to make HTTP method call to
catalog service to get JSON items data:
{"items":
{"@uri":"http://host/catalog/resources/items/",
"item":[
{"@uri":"http://host/catalog/resources/items/1/",
"name":"Friendly Cat",
"description":"This black and white colored cat is super friendly.",
"id":"1",
"imageurl":"http://localhost:8080/CatalogService/images/anthony.jpg"},
{"@uri":"http://host/catalog/resources/items/2/",
"name":"Fluffy Cat",
"description":"A great pet for a hair stylist!
"id":"2",
"imageurl":"http://localhost:8080/CatalogService/images/bailey.jpg"}
]
}
}

34
Dojo client.js
// make request to the items web service
function loadTable(page){
start = page * batchSize;
var targetURL = "resources/items/?start="+start;
dojo.xhrGet({
url: targetURL, Performs HTTP
handleAs: "json", GET on url
load: handleResponse,
error: handleError catalog/items
});
} Callback
// Process the response from the items web service
function handleResponse(responseObject, ioArgs){
// set the model object with the returned items list
model.setData(responseObject.items.item);

}
function next() { Callback puts response
page =page + 1;
loadTable(page); data in dojo model
} for grid table

35
Example RESTful Catalog

36
37
JavaFX Stage Scene
Stage is the top level
container window
Scene is a drawing surface
container that holds the scene
graph nodes.

content holds JavaFX


graphical elements which
define the graphical content
of the application.

38
JavaFX Stage Scene
// Application User Interface
var stageContent: Node[];

stageContent = [bgImage,
nextButton, backButton,
titleText,
thumbImageViewGroup,
fullImageView
];
def stage = Stage {
title: "Pet Catalog"
width: 201
height: 201
scene: Scene {
content: Group {
content: bind stageContent
}
fill: Color.TRANSPARENT
}
} 39
JavaFX Stage Scene
var stageContent: Node[];

stageContent = [bgImage,
nextButton, backButton,
titleText,
thumbImageViewGroup,
fullImageView
];
def stage = Stage {
title: "Pet Catalog"
width: 201
height: 201
scene: Scene {
content: Group {
content: bind stageContent
}
fill: Color.TRANSPARENT
}
}
40
RESTful Pet Catalog Web Service
HTTP GET
http://petstore/catalog/resources/items/

Addressable
Client Resources

Response XML items


Server Web Container
<item>
<imageurl>http://host/catalog/images/anthony.jpg</imageurl>
<name>Friendly Cat</name>
<price>307.10</price>
<productid>feline01</productid>
</item>

41
JavaFX HttpRequest Performs HTTP
function loadImageMetadata() {
GET on url
var start=page * 9; catalog/items
var request: HttpRequest = HttpRequest {

location: "http://localhost:8080/catalog/resources/items/"
method: HttpRequest.GET

onInput: function(input: java.io.InputStream) {

var parser = PhotoPullParser{};


photos = parser.parse(input); Parses xml
} data
onDone: function() {
updateImages();
}
} Callback puts response
request.enqueue(); data images
}
in grid

42
JavaFX HttpRequest
public class PhotoPullParser {
public function parse(input: InputStream): Photo[] {
var photos: Photo[];
var photo: Photo;
def parser = PullParser {input: input
onEvent: function(event: Event) {
if (event.type == PullParser.START_ELEMENT) {
if(event.qname.name == "item" and event.level == 1) {
photo = Photo { };
}
} else
if (event.type == PullParser.END_ELEMENT) {
if(event.qname.name == "item" and event.level == 1) {
insert photo into photos;
} else
if(event.qname.name == "imagethumburl" and event.level == 2) {
photo.imagethumburl = event.text;
} ... <item>
}
}
<imageurl>http://y.jpg</imageurl>
}
<name>Friendly Cat</name>
parser.parse(); ...
return photos; </item>
}

43
For More Information
Dojo
http://dojotoolkit.org/
JAX-RS Reference Implementation
http://jersey.dev.java.net/
Glassfish
https://glassfish.dev.java.net/
http://blogs.sun.com/theaquarium/
JavaFX
http://javafx.com/
Carol's Blog
http://weblogs.java.net/blog/caroljmcdonald/

44
P
r
e
s
e
n Carol McDonald
t Java Architect
e
r http://weblogs.java.net/blog/caroljmcdonald/


s

N
a
m 45

Вам также может понравиться