12. Example RESTful Catalog Service Catalog Database Web container (GlassFish™) + REST API Browser (Firefox) HTTP
13.
14. POJO @Path("/items/") public class ItemsResource { @Produces("application/json") @GET public ItemsConverter get() { ... } ... } responds to the URI http://host/catalog/items/ responds with JSON responds to HTTP GET
15.
16.
17.
18.
19. 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; } ... }
20. 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>
21.
22. 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; } }
23. 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>
24.
25.
26. Get Items @Path("/items/") public class ItemsResource { @Context protected UriInfo uriInfo; @GET @Produces ("application/json") public ItemsConverter get(){ return new ItemsConverter( getEntities(), uriInfo.getAbsolutePath()); } Performs JPA Query, returns list of entities JAXB class responds with JSON responds to the URI http://host/catalog/items/ responds to HTTP GET
27. Get Item @Path("/items/") public class ItemsResource { @Path("{id}/") public ItemResource getItemResource( @PathParam ("id") Long id) { return new ItemResource (id, context); } } public class ItemResource { @GET @Produces ( "application/json") public ItemConverter get() { return new ItemConverter(getEntity(), context.getAbsolutePath(), expandLevel); } JAXB class http://host/catalog/items/123
52. RESTful Pet Catalog Web Service http://petstore/catalog/resources/items/ HTTP GET {"url":"http://store/catalog/item1", {"url":"http://store/catalog/item2"} Response JSON slide urls Server Client Addressable Resources Web Container
56. Dojo client index.html <button dojoType="dijit.form.Button" onclick=" next "> Next </button> <div id="grid" dojoType =" dojox.Grid " model =" model " structure=" layout " autoWidth="true" > http://weblogs.java.net/blog/caroljmcdonald/archive/2008/08/a_restful_pet_c.html Grid widget
57. Dojo client.js formatImage = function(value) { if (!value) return ' '; 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"} ] ] }; // 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);
58. Dojo client.js // make request to the items web service function loadTable (page){ start = page * batchSize; var targetURL = "resources/items/?start="+ encodeURIComponent(start); dojo.xhrGet ({ url: targetURL , handleAs: "json", load: handleResponse , error: handleError }); } // 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() { page =page + 1; loadTable (page); } Performs HTTP GET on url catalog/items
60. Comet: the server pushes data to the client over a long-lived HTTP connection Server Client 1 Client 2
61.
62.
63. Blocking http request =server catastrophe GET /updates HTTP/1.1 Connection: keep-alive GET /updates HTTP/1.1 Connection: keep-alive GET /updates HTTP/1.1 Connection: keep-alive GET /updates HTTP/1.1 Connection: keep-alive GET /updates HTTP/1.1 Connection: keep-alive
64.
65.
66. Server-side Ajax Push: Who supports what The asynchronicity matrix. X WebLogic Container Asynchronous IO Suspendible Request/ Response Delivery Guarantee Jetty X Tomcat X X GlassFish X X X Resin X
67.
68. Bayeux HTTP Publish Subscribe protocol for routing JSON -encoded events between clients and servers in a publish-subscribe model Grizzly provides an implementation of Bayeux Just configure Glassfish domain.xml and Web App web.xml
74. RESTful Web Services and Comet http://developers.sun.com/appserver/reference/techart/cometslideshow.html
75. RESTful Slideshow Web Service http://host/slideshow/resources/slides/ HTTP GET {"url":"http://host/slideshow/image1.jpg", {"url":"http://host/slideshow/image2.jpg"} Response JSON slide urls Server Client Addressable Resources Web Container
76. Cometd Step1 : Initialize dojo.require(" dojox.cometd "); //Initialize a connection to the given Comet server: the GlassFish Grizzly Bayeux servlet dojox.cometd. init ("serverURL"); Comet Server Client 1 Client 2
77.
78.
79.
80. Cometd Step 3: Publish dojox.cometd. publish ("topic", {slide: url}); a client publishes the next slide url to the topic channel JSON message client 1 Comet Server Next slide url
81.
82.
83.
84.
85. RESTful Web Services and Comet http://developers.sun.com/appserver/reference/techart/cometslideshow.html
87. Example RESTful Catalog http://weblogs.java.net/blog/caroljmcdonald/archive/2008/08/a_restful_pet_c.html
88.
89.
Notas del editor
Representational State Transfer (REST) is a style of software architecture for distributed systems such as the World Wide Web. The term was introduced in the doctoral dissertation of Roy Fielding in 2000, and has since come into widespread use in the networking community. An important concept in REST is the existence of resources, each of which can be referred to using a global identifier, that is, a URI. In order to manipulate these resources, components of the network, clients and servers, communicate using a standardized interface such as HTTP and exchange representations of these resources.
What Are RESTful Web Services? Representational State Transfer (REST) is a software application architecture modeled after the way data is represented, accessed, and modified on the web. In the REST architecture, data and functionality are considered resources, and these resources are accessed using Uniform Resource Identifiers (URIs), typically links on the web. The resources are acted upon by using a set of simple, well-defined operations. The REST architecture is designed to use a stateless communication protocol, typically HTTP. In the REST architecture, clients and servers exchange representations of resources using a standardized interface and protocol. These principles encourages REST applications to be simple, lightweight, and have high performance. RESTful web services are web applications built upon the REST architecture. They: expose resources (data and functionality) through web URIs use the four main HTTP methods to create, retrieve, update, and delete resources RESTful web services typically map the four main HTTP methods to the so-called CRUD actions: create, retrieve, update, and delete. The following table shows a mapping of HTTP methods to these CRUD actions.
Use an annotation to mark the methods that you want the runtime to to call to service the http request. Can either put http method in the annotation or in the method
The uniform interface also enables every component that understands the HTTP application protocol to interact with your application. Examples of components that benefit from this are generic clients such as curl and wget, proxies, caches, HTTP servers, gateways, even Google/Yahoo!/MSN, and many more. To summarize: For clients to be able to interact with your resources, they should implement the default application protocol (HTTP) correctly, i.e. make use of the standard methods GET, PUT, POST, DELETE.
UriTemplate annotation defines the URI Template to which the resource responds, HTTP methods are mapped to Java programming language methods using the HttpMethod annotation. @ProduceMime annotation is used to specify the MIME types a resource can produce and send back to the client. variables are specified as parameters to the method by decoration the parameter location with a @UriParam annotation when the method is called the id will be put into the artist parameter by the runtime
To obtain an container managed EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; you don't need any cm lifecycle methods With a container-managed entity manager, an EntityManager instance's persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. JTA transactions usually involve calls across application components. To complete a JTA transaction, these components usually need access to a single persistence context. This occurs when an EntityManager is injected into the application components via the javax.persistence.PersistenceContext annotation. The persistence context is automatically propagated with the current JTA transaction, and EntityManager references that are mapped to the same persistence unit provide access to the persistence context within that transaction. By automatically propagating the persistence context, application components don't need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.
To obtain an container managed EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; you don't need any cm lifecycle methods With a container-managed entity manager, an EntityManager instance's persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. JTA transactions usually involve calls across application components. To complete a JTA transaction, these components usually need access to a single persistence context. This occurs when an EntityManager is injected into the application components via the javax.persistence.PersistenceContext annotation. The persistence context is automatically propagated with the current JTA transaction, and EntityManager references that are mapped to the same persistence unit provide access to the persistence context within that transaction. By automatically propagating the persistence context, application components don't need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.
Dojo toolkit is open source DHTML toolkit written in JavaScript. In other words, it is a set of JavaScript libraries. Dojo toolkit aims to solve some long-standing historical problems with DHTML such as browser incompatibility. Dojo toolkit also allows you easily add dynamic capabilites into the web pages by the usage of pre-built widgets and animations. Because it is only client-side technology, it can work with any server side technology.
Think of Base as the kernel of the toolkit. It's a tiny library wrapped up into a single JavaScript file ( dojo.js ) that provides the foundation for everything in the toolkit. Among other things, Base handles bootstrapping the toolkit, includes convenient language and AJAX utilities, provides mechanisms for simulating class-based inheritance, offers a slick packaging system that preserves the global namespace, and more. Core builds on Base by providing additional facilities for accessing data stores, providing effects such as wipes/slides, internationalization (i18n), and back-button handling among other things. For the most part, any module or resource associated with the dojo namespace that you have to explicitly import into the page is part of Core. Dijit is shorthand for &quot;Dojo widget&quot; and, depending on the context and capitalization, could refer to a single Dojo widget (a dijit) or to the entire component of the toolkit containing all of Dojo's widgets (Dijit). Dijit directly leverages the power of Base and Core to provide a powerful widget layer that's highly usable and simple in design. DojoX stands for &quot;Dojo Experimental&quot; and contains features that stand a chance of one day migrating into Core, Dijit, or even a new Dojo module that doesn't exist yet. Think of DojoX as an incubator or sandbox
download nothing and simply pull Dojo from a CDN near you: * AOL: <SCRIPT TYPE=&quot;text/javascript&quot; SRC=&quot;http://o.aolcdn.com/dojo/1.2.0/dojo/dojo.xd.js&quot;></SCRIPT> * Google: <SCRIPT TYPE=&quot;text/javascript&quot; SRC=&quot;http://ajax.googleapis.com/ajax/libs/dojo/1.2.0/dojo/dojo.xd.js&quot;></SCRIPT>
Use Dojo from a CDN or download and follow these simple steps: 1. Extract files from the download locally or on a web server. 2. Include <SCRIPT TYPE=&quot;text/javascript&quot; SRC=&quot;dojo/dojo.js&quot;></SCRIPT> and you're on your way. 3. Browse to dojo/tests/runTests.html or dijit/themes/themeTester.html to see Dojo in action The most important thing to know when installing the Dojo Toolkit is where your copy of dojo.js is located. The package system handles the loading of all other dependencies and modules once dojo.js has been loaded into the page.
The <script> tag pulls the Dojo code from your server. The djConfig=&quot; parseOnLoad:true&quot; attribute is required to use Dojo elements declaratively. To use Firebug Lite, you must include the isDebug config parameter. This parameter has no effect on Firefox browsers with Firebug already present. So including this parameter makes your debugging code usable in IE, Safari, and Firefox with no changes.
The <script> tag pulls the Dojo code from your server. The djConfig=&quot; parseOnLoad:true&quot; attribute is required to use Dojo elements declaratively. To use Firebug Lite, you must include the isDebug config parameter. This parameter has no effect on Firefox browsers with Firebug already present. So including this parameter makes your debugging code usable in IE, Safari, and Firefox with no changes.
What is a widget? You probably have some idea already on what it is. It is a UI element such as a button, text box, scroll bar, calendar, tree and so on. Widgets are a lot easier to deal with than manipulating HTML page with DOM APIs. A widget can be a composite element meaning it could be made of other widgets. A widget can have a custom style so that it can be presented on a page in a particular style. And of course, event handlers can be registered or attached. The event handlers then might call backend service using AJAX-based asynchronous calls.
The @import rule loads the Dojo stylesheet and the theme Tundra. a theme is a set of fonts, colors... for components . Three themes come prepackaged with Dijit—Tundra, Soria, and Nihilo.You must always import dojo.css, but if you’re using Dojo without Dijit, you can omit the theme style sheet import. The <script> tag pulls the Dojo code from your server. The djConfig=&quot; parseOnLoad:true&quot; attribute is required to use Dojo elements declaratively. you set the class of the body to match the theme. In this example tundra. It is also possible to create a custom build of Dojo, which eliminates the need for dojo.require() by putting everything in dojo.js .
You can use the built-in widgets just by adding them in your html or jsp pages. There are many widgets that come with Dojo toolkit already and more are being created by community members. An attribute is a data element used for controlling display or behavior. A method is a function you call to control something. An extension point is a function you provide to override behavior.
This is how you add editor widget to your page. First, you indicates that you would need “dojo.widget.Editor” package. Then you use dojoType attribute to the <div> element. The “items” attribute specifies the list of icons.
You can use the built-in widgets just by adding them in your html or jsp pages. There are many widgets that come with Dojo toolkit already and more are being created by community members.
You can use the built-in widgets just by adding them in your html or jsp pages. There are many widgets that come with Dojo toolkit already and more are being created by community members.
So how does AJAX application performs the asynchronous communication with the server? This slide also compares conventional web application and AJAX application. In the left side, which shows the conventional web application, HTTP request/response interaction occurs directly between a browser and a backend web application. In the right side, which shows AJAX based web application, within a browser, there is AJAX engine, which is actually represented by a JavaScript object called XMLHttpRequest which handles the HTTP request/response interaction in an asynchronous fashion.
Connecting an Event to the Widget A button is all well and good, but what about getting it to do something when it's clicked? We could just specify an onClick event handler for the button, but there's another, more efficient way - the Dojo event system! The easiest way to attach an event to a button is through a script tag. But not just any script tag ... this one has a type of dojo/method, like this:
When a message is published to a Bayeux channel on the server, it is delivered to all clients subscribed to that channel, in this case to the &quot;/chat/demo&quot; channel . The _chat callback function, is called with the published message as an input argument. The _chat callback function updates the browser page by setting the slide dom element innerHTML to an html img tag with the slide url from the published message &quot;<img src='&quot; + slideUrl + &quot;'/>&quot; . This updates the browser page with the image corresponding to the slide URL which was published.
Grizzly is an HTTP framework. It uses all the NIO facilities and provides people an easy to use, high performance API for socket communications. Grizzly actually has a couple of different modes. It has a blocking mode and a non-blocking mode. But, for the purpose of here, we are primarily interested in the non-blocking implementation. In fact, all the implementations that we deal with are going to be the non-blocking implementation Grizzly. So Grizzly essentially, its point is to bring these non-blocking sockets to the HTTP processing layer. Later on, as we will see in the benchmarks, that's what gives us the high-performance HTTP processing. Grizzly is written architecturally as a connector within Tomcat. Our app server likes a large number of application servers leverages the Coyote implementation for the web container. Coyote is used in Tomcat 3,4, 5. It's used in our app servers. The Coyote architecture you can stick this thing called a connector in front of the actual Coyote section, which does the JSP and servlet processing. The Grizzly part is actually the small little piece that only responsible for handling communications with the clients and then it passes it off to Coyote to do the actual work. So, it can utilize Coyote's buffers, and processing parsing classes and all that sort of work. It 's not the full HTTp engine, it is just that part that manages connections.
Grizzly is an HTTP framework. It uses all the NIO facilities and provides people an easy to use, high performance API for socket communications. Grizzly actually has a couple of different modes. It has a blocking mode and a non-blocking mode. But, for the purpose of here, we are primarily interested in the non-blocking implementation. In fact, all the implementations that we deal with are going to be the non-blocking implementation Grizzly. So Grizzly essentially, its point is to bring these non-blocking sockets to the HTTP processing layer. Later on, as we will see in the benchmarks, that's what gives us the high-performance HTTP processing. Grizzly is written architecturally as a connector within Tomcat. Our app server likes a large number of application servers leverages the Coyote implementation for the web container. Coyote is used in Tomcat 3,4, 5. It's used in our app servers. The Coyote architecture you can stick this thing called a connector in front of the actual Coyote section, which does the JSP and servlet processing. The Grizzly part is actually the small little piece that only responsible for handling communications with the clients and then it passes it off to Coyote to do the actual work. So, it can utilize Coyote's buffers, and processing parsing classes and all that sort of work. It 's not the full HTTp engine, it is just that part that manages connections.
Bayeux’s concept of channels allows multiple decoupled conversations on top of a single HTTP connection. The client-side Cometd object and server-side Bayeux implementation communicate over several notional channels all bundled within a single HTTP request-response pair.
JOSN data needs to to be parsed by browser, and this may introduce in sufficient and insecure problems, so the other way of doing it is by using the primitive xml parser. Server does not really participate, it is a reflector to send the message to the right chat room. Server just peer to peer mediates the messages to the right channel. Server can implement in any languages, java, python, ... Because server is not involved, it takes less benefit from the server side data.
# Add the following property in between the http-listener start and end tags: <property name=&quot;cometSupport&quot; value=&quot;true&quot;/> o enable the Bayeux protocol on the Enterprise Server, you must reference the CometdServlet in your web application's web.xml file. In addition, if your web application includes a servlet, set the load-on-startup value for your servlet to 0 (zero) so that it will not load until the client makes a request to it.
Grizzly is an HTTP framework. It uses all the NIO facilities and provides people an easy to use, high performance API for socket communications. Grizzly actually has a couple of different modes. It has a blocking mode and a non-blocking mode. But, for the purpose of here, we are primarily interested in the non-blocking implementation. In fact, all the implementations that we deal with are going to be the non-blocking implementation Grizzly. So Grizzly essentially, its point is to bring these non-blocking sockets to the HTTP processing layer. Later on, as we will see in the benchmarks, that's what gives us the high-performance HTTP processing. Grizzly is written architecturally as a connector within Tomcat. Our app server likes a large number of application servers leverages the Coyote implementation for the web container. Coyote is used in Tomcat 3,4, 5. It's used in our app servers. The Coyote architecture you can stick this thing called a connector in front of the actual Coyote section, which does the JSP and servlet processing. The Grizzly part is actually the small little piece that only responsible for handling communications with the clients and then it passes it off to Coyote to do the actual work. So, it can utilize Coyote's buffers, and processing parsing classes and all that sort of work. It 's not the full HTTp engine, it is just that part that manages connections.
In chat.js, the application uses the dojo.require function (similar to the import directive in Java) to specify which Dojo modules to load. the call to dojox.cometd.init initialises a connection to the given Comet server, in this case with the Glassfish Grizzly Bayeux servlet (note /cometd/* is the url-pattern for the Grizzly Cometd Servlet configured in the web.xml for the application).
The dojox.cometd.subscribe line subscribes the callback function to the topic channel. Any time a message is sent to the topic channel the callback function will be called.
The function room.next, shown below, calls dojox.cometd.publish to publish the next slide url (input argument) to the /chat/demo channel. Subscribers to the /chat/demo channel will get this message.
When a message is published to a Bayeux channel on the server, it is delivered to all clients subscribed to that channel, in this case to the &quot;/chat/demo&quot; channel . The _chat callback function, is called with the published message as an input argument. The _chat callback function updates the browser page by setting the slide dom element innerHTML to an html img tag with the slide url from the published message &quot;<img src='&quot; + slideUrl + &quot;'/>&quot; . This updates the browser page with the image corresponding to the slide URL which was published.