REST dojo Comet
Upcoming SlideShare
Loading in...5
×
 

REST dojo Comet

on

  • 6,480 views

a look at using REST dojo and Comet together

a look at using REST dojo and Comet together

Statistics

Views

Total Views
6,480
Views on SlideShare
6,377
Embed Views
103

Actions

Likes
1
Downloads
0
Comments
1

5 Embeds 103

http://owen.com 73
http://www.slideshare.net 20
http://localhost 8
http://us-w1.rockmelt.com 1
http://sysdecom-projects.com 1

Accessibility

Categories

Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • thank you very much for your share!
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • 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 "Dojo widget" 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 "Dojo Experimental" 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: * Google:
  • 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 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
  • The
  • 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
  • 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 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 "/chat/demo" 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 "" . 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: 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 "/chat/demo" 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 "" . This updates the browser page with the image corresponding to the slide URL which was published.

REST dojo Comet REST dojo Comet Presentation Transcript

  • REST, dojo, Comet Carol McDonald, Java Architect
  • About the Speaker
    • Carol cDonald:
      • Java Architect at Sun Microsystems
      • Before Sun, worked on software development of:
        • Application to manage car Loans for Toyota (>10 million loans)
        • Pharmaceutical Intranet apps ( Roche Switzerland)
        • Telecom Network Mgmt ( Digital France)
        • X.400 Email Server ( IBM Germany)
  • Agenda
    • REST and JAX-RS
    • Dojo
    • Comet
    View slide
  • Example RESTful Catalog View slide
  • RESTful Slideshow using JAX-RS and comet
  • REST and JAX-RS
  • REpresentational State Transfer
    • Get
    • http://www.parts-depot.com/parts
    Response XML data = REpresentational State Transfer
        • The URL identifies the resource
        • GET the page from the server
        • html page is transferred to the browser
          • REpresentational State transfer
        • You click on a hyperlink in page (hypermedia), the process is repeated
        • The page ( application state ) is stored on the client (browser)
  • REST Tenets
    • Resources ( nouns )
      • Identified by a URI , For example:
        • http://petstore/catalog/items/
    • Methods ( verbs ) to manipulate the nouns
      • Small fixed set:
        • GET =Read , PUT =Update , POST =Create , Delete
    • Representation of the Resource
      • data and state transferred between client and server
      • XML, JSON ...
    • Use verbs to exchange application state and representation
  • HTTP Example Request GET /catalog/items HTTP/1.1 Host: petstore.com Accept: application/xml 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 <?xml version=&quot;1.0&quot;?> <items xmlns=&quot;…&quot;> <item>…</item> … </items> Method Resource Representation State transfer
  • JAX-RS: Clear mapping to REST concepts
    • High level, Declarative
      • Uses @ annotation in POJOs
    • Resources : what are the URIs ?
      • @Path(&quot;/items/{id}&quot;)
    • Methods : what are the HTTP methods ?
        • @GET
        • public XXX find()
    • Representations : what are the formats ?
      • @Consumes(&quot;application/xml&quot;)
      • @Produces(&quot;application/json&quot;)
  • Example RESTful Catalog
  • Example RESTful Catalog Service Catalog Database Web container (GlassFish™) + REST API Browser (Firefox) HTTP
  • URIs and Methods:
    • /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
    Item Catalog Example
      • http://www.infoq.com/articles/rest-introduction
  • POJO @Path(&quot;/items/&quot;) public class ItemsResource { @Produces(&quot;application/json&quot;) @GET public ItemsConverter get() { ... } ... } responds to the URI http://host/catalog/items/ responds with JSON responds to HTTP GET
  • Methods
      • Java method name is not significant
        • The @HTTP method is the method
    @Path(“/items”) class ItemsResource { @GET Items get() { ... } @POST Response create(Item) { ... } } class ItemResource { @GET Item get(...) { ... } @PUT void update(...) { ... } @DELETE void delete(...) { ... } }
  • RESTful Catalog
        • Dojo client, JAX-RS, JAXB, JPA
    DB Registration Application JAX-RS class Dojo client JAXB class Entity Class ItemsConverter Item ItemsResource
  • 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 public class Item { int id; String name; String descr; String url; } @Entity @Id Item ID NAME DESC URL
  • Converter Classes
    • JAXB to convert the domain objects (JPA entities ) into XML and/or JSON .
    DB JAX-RS class Dojo client JAXB class Entity Class ItemsConverter Item ItemsResource
  • ItemConverter JAXB annotated @XmlRootElement(name = &quot;item&quot;) 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; } ... }
  • XML <item uri=&quot;http://localhost/Web/resources/items/1/&quot; > <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>
  • JSON
    • {
    • &quot;@uri&quot;:&quot;http://host/catalog/resources/items/1/&quot;,
    • &quot;name&quot;:&quot;Friendly Cat&quot;,
    • &quot;description&quot;:&quot;This black and white colored cat is super friendly.&quot;,
    • &quot;id&quot;:&quot;1&quot;,
    • &quot;imageurl&quot;:&quot; http://localhost:8080/CatalogService/images/anthony.jpg &quot;
    • }
  • ItemsConverter JAXB annotated @XmlRootElement(name = &quot;items&quot;) public class ItemsConverter { private Collection<ItemConverter> items; private URI uri; @XmlAttribute public URI getUri() { return uri; } @XmlElement public Collection<ItemConverter> getItem() { ... return items; } }
  • XML <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> <items uri=&quot;http://localhost/Web/resources/items/&quot;> <item uri=&quot;http://localhost/Web/resources/items/1/&quot; > <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>
  • JSON
    • {
    • &quot;@uri&quot;:&quot;http://host/catalog/resources/items/&quot;,
    • &quot; item &quot;:[
    • {&quot;@uri&quot;:&quot;http://host/catalog/resources/items/1/&quot;,
    • &quot;name&quot;:&quot;Friendly Cat&quot;,
    • &quot;description&quot;:&quot;This black and white colored cat is super friendly.&quot;,
    • &quot;id&quot;:&quot;1&quot;,
    • &quot;imageurl&quot;:&quot;http://localhost:8080/CatalogService/images/anthony.jpg&quot;},
    • {&quot;@uri&quot;:&quot;http://host/catalog/resources/items/2/&quot;,
    • &quot;name&quot;:&quot;Fluffy Cat&quot;,
    • &quot;description&quot;:&quot;A great pet for a hair stylist!
    • &quot;id&quot;:&quot;2&quot;,
    • &quot;imageurl&quot;:&quot;http://localhost:8080/CatalogService/images/bailey.jpg&quot;}
    • ]
    • }
  • 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
    DB JAX-RS class Dojo client JAXB class Entity Class ItemsConverter Item ItemsResource
  • Get Items @Path(&quot;/items/&quot;) public class ItemsResource { @Context protected UriInfo uriInfo; @GET @Produces (&quot;application/json&quot;) 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
  • Get Item @Path(&quot;/items/&quot;) public class ItemsResource { @Path(&quot;{id}/&quot;) public ItemResource getItemResource( @PathParam (&quot;id&quot;) Long id) { return new ItemResource (id, context); } } public class ItemResource { @GET @Produces ( &quot;application/json&quot;) public ItemConverter get() { return new ItemConverter(getEntity(), context.getAbsolutePath(), expandLevel); } JAXB class http://host/catalog/items/123
  • Dojo Client Side JavaScript Library
  • What is the Dojo Toolkit?
    • Open Source set of JavaScript libraries
    • Simplifies javascript
    • support
      • SitePen , IBM, Sun, JotSpot, Renkoo, AOL TurboAjax, OpenLaszlo, Nexaweb, Bea Systems
    • http://dojotoolkit.com/
    • Server side technology independent,
    source: dojotoolkit.org
  • Dojo 3 main parts:
    • Dojo
      • Browser normalization, package loading, DOM access and manipulation, Firebug Lite debugging, events, data access, Drag and drop, Asynchronous remote calls, JSON encoding/decoding
    • dijit
      • Interface widgets, Advanced UI controls,Template driven
    • dojoX
      • Inventive innovative: graphics, offline, widgets like grid spreadsheat,
  • Loading d ojo
  • Use Dojo from Content Distribution Network :
    • 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=” http://ajax.googleapis.com/ajax/libs/dojo/1.2.0/dojo/dojo.xd.js &quot;>
    • </SCRIPT>
  • Use Dojo from your Web Server :
    • Download from http://dojotoolkit.org/downloads
    • Unzip the file, rename top folder to src
    • <script type=&quot;text/javascript&quot;
    • djConfig=&quot;parseOnLoad: true&quot;
    • src=&quot;js/dojo/dojo.js&quot; >
    • </script>
  • Use bundled Dojo with Netbeans project:
    • Create a Netbeans project. Add Netbeans bundled dojo library to project:
  • Or Use downloaded Dojo with Netbeans project: (if you want a different version)
    • Download from http://dojotoolkit.org/downloads
    • Unzip the file, rename top folder to js
    • Create a Netbeans project. Copy js folder into the web folder of your Netbeans project :
  • Run File themeTester.html
  • Try out dojo dijit widgets
  • Setting up dojo javascript in the page
    • <head>
    • <style type=&quot;text/css&quot;>
    • @import &quot;js/dojo/resources/dojo.css&quot;;&quot;;
    • </style>
    • <script type=&quot;text/javascript&quot;
    • src=&quot;js/dojo/dojo.js&quot;
    • djConfig=&quot;parseOnLoad: true&quot;
    • isDebug: true >
    • </script>
    • </head>
  • Logging
    • console.log(&quot;log button clicked&quot;);
    • console.debug(&quot;debug button clicked&quot;);
    • console.info(&quot;info button clicked&quot;);
    • console.warn(&quot;warn button clicked&quot;);
    • console.error(&quot;error button clicked&quot;);
  • Dijit = d ojo Widget
  • dijit is a UI widget system layered on top of dojo The dojo Widget Library
  • What is a dojo Widget?
    • Is a UI element such as a button, text box , scroll bar, calendar , tree etc
      • Easy to use
      • Event handlers can be registered on widget
      • handle browser incompatibilities
    • HTML+CSS bound by JavaScript
  • Creating a Button Widget
    • <head>
    • <style type=&quot;text/css&quot;>
    • @import &quot;js/dijit/themes/tundra/tundra.css&quot;;
    • @import &quot;js/dojo/resources/dojo.css&quot;;
    • </style>
    • <script type=&quot;text/javascript&quot;
    • djConfig=&quot; parseOnLoad : true&quot;
    • src=&quot;js/dojo/dojo.js&quot; > </script>
    • <script type=&quot;text/javascript&quot;>
    • dojo.require(&quot;dijit.form.Button&quot;);
    • </script>
    • </head>
    • <body class=&quot; tundra &quot;>
    • <button dojoType=&quot; dijit.form.Button &quot;
    • onclick=&quot;call_function&quot;>
    • Log Button
    • </button>
  • Form Widgets
    • CheckBox, RadioButton,ComboBox, CurrencyTextBox, DateTextBox, NumberTextBox, Slider, ValidationTextBox, Textarea
    • Attributes: disabled: Boolean
    • Methods:
      • focus Set the focus on this widget
      • getValue get the value of the widget.
      • setValue set the value of the widget.
      • reset resets the widget to it's initial value
      • undo restore the value to the last value
    • Extension Points: onChange: callback function
  • Example dijit.form.DateTextBox
    • <script>
      • dojo.require(&quot;dijit.form.DateTextBox&quot;);
    • </script>
    • <body>
    • <input type=&quot;text&quot; name=&quot;date1&quot;
      • value=&quot;2005-12-30&quot;
      • dojoType=&quot;dijit.form.DateTextBox&quot;
      • required=&quot;true&quot; />
  • Dijit Layout
    • Accordion Container,Content Pane, Layout Container, Split Container, Stack Container, Tab Container
  • Dijit Command Control
    • Button, ComboButton, DropDownButton, Menu, Toolbar
  • Dojo Event system
  • dojo.event.connect(srcObj,&quot;srcFunc&quot;, targetFunc);
    • function myFunction () { alert(&quot;dojo.connect handler&quot;);
    • }
    • var link = dojo.byId(&quot; mylink &quot;);
    • dojo.event.connect ( link , &quot;onclick&quot;, myFunction );
    • <a href=&quot;#&quot; id=&quot; mylink &quot;>Click Me</a>
  • XMLHttpRequest (XHR): dojo.xhrDelete(), dojo.xhrGet(), dojo.xhrPost(), dojo.xhrPut()
  • Traditional Web AJAX within a browser, there is AJAX engine
  • RESTful Pet Catalog Web Service http://petstore/catalog/resources/items/ HTTP GET {&quot;url&quot;:&quot;http://store/catalog/item1&quot;, {&quot;url&quot;:&quot;http://store/catalog/item2&quot;} Response JSON slide urls Server Client Addressable Resources Web Container
  • Dojo Client
    • Use dojo.xhrGet to make HTTP method call to catalog service to get JSON items data:
    • {&quot; items &quot;:
    • {&quot;@uri&quot;:&quot;http://host/catalog/resources/items/&quot;,
    • &quot; item &quot;:[
    • {&quot;@uri&quot;:&quot;http://host/catalog/resources/items/1/&quot;,
    • &quot;name&quot;:&quot;Friendly Cat&quot;,
    • &quot;description&quot;:&quot;This black and white colored cat is super friendly.&quot;,
    • &quot;id&quot;:&quot;1&quot;,
    • &quot;imageurl&quot;:&quot;http://localhost:8080/CatalogService/images/anthony.jpg&quot;},
    • {&quot;@uri&quot;:&quot;http://host/catalog/resources/items/2/&quot;,
    • &quot;name&quot;:&quot;Fluffy Cat&quot;,
    • &quot;description&quot;:&quot;A great pet for a hair stylist!
    • &quot;id&quot;:&quot;2&quot;,
    • &quot;imageurl&quot;:&quot;http://localhost:8080/CatalogService/images/bailey.jpg&quot;}
    • ]
    • }
    • }
  • Getting Items from the RESTful Service
    • loadSlides: function (){
    • var targetURL = &quot; resources/items/ &quot;;
    • dojo.xhrGet({
    • url: targetURL,
    • handleAs: &quot; json &quot;,
    • load: room. handleResponse ,
    • error: room.handleError
    • });
    • },
    • handleResponse : function (responseObject, ioArgs){
    • if(!responseObject.item ){
    • return ;
    • }
    • ...
    • },
  • Example RESTful Catalog
  • Dojo client index.html <button dojoType=&quot;dijit.form.Button&quot; onclick=&quot; next &quot;> Next </button> <div id=&quot;grid&quot; dojoType =&quot; dojox.Grid &quot; model =&quot; model &quot; structure=&quot; layout &quot; autoWidth=&quot;true&quot; > http://weblogs.java.net/blog/caroljmcdonald/archive/2008/08/a_restful_pet_c.html Grid widget
  • Dojo client.js formatImage = function(value) { if (!value) return '&nbsp;'; return &quot;<img src='&quot; + value + &quot;'/>&quot;; }; // Data Grid layout // A grid view is a group of columns var view1 = { cells: [ [ {name: 'Name', field: &quot;name&quot;}, {name: 'Description', field: &quot;description&quot;}, {name: 'Photo',field: &quot;imagethumburl&quot;, formatter: formatImage , }, {name: 'Price',field: &quot;price&quot;} ] ] }; // 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);
  • Dojo client.js // make request to the items web service function loadTable (page){ start = page * batchSize; var targetURL = &quot;resources/items/?start=&quot;+ encodeURIComponent(start); dojo.xhrGet ({ url: targetURL , handleAs: &quot;json&quot;, 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
  • COMET
  • Comet: the server pushes data to the client over a long-lived HTTP connection Server Client 1 Client 2
  • Ajax Push and HTTP keep-alive
      • Comet:
      • server pushes data to the client over a previously opened connection
      • HTTP/1.1 Keep-Alive or Persistent Connection:
      • keeps connection open until an explicit 'close connection' message or timeout
    Long Poll : Send a request to the server, request waits for an event, then response sent
  • Ajax Push HTTP example
    • GET /slideshow/resources/slides
    • Accept: */*
    • Connection: keep-alive
    • Host: localhost:8080
    HTTP/1.1 200 OK Content-Type: application/json-comment-filtered Server: GlassFish/v3 /*[{&quot;id&quot;:&quot;0&quot;, &quot;minimumVersion&quot;:0.9, &quot;supportedConnectionTypes&quot;:[&quot;long-polling&quot;,&quot;callback-polling&quot;], &quot;successful&quot;:true,&quot;advice&quot;:{&quot;reconnect&quot;:&quot;retry&quot;,&quot;interval&quot;:0}, &quot;channel&quot;:&quot;/meta/handshake&quot;,&quot;clientId&quot;:&quot;3b37f0aae53ab2f1&quot; ,&quot;ext&quot;:{&quot;json-comment-filtered&quot;:true},&quot;version&quot;:1.0}]*/ Handshake
  • 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
  • GlassFish Grizzly Comet
      • NIO:
      • non-blocking sockets
      • ARP Asynchronous Request Processing:
      • Doesn't block a thread per http request
      • availability of threads gives scalability
  • Introduction to Grizzly Comet
    • Grizzly Comet is a framework that ship with GlassFish v1|2|3, and can also be embedded into any application using the Grizzly Embed interface (no fish involved).
    • The Grizzly Comet Framework includes a set of components that can be used for building Comet based application:
      • Grizzly Comet, Continuation, Grizzlet, Messages Bus, Bayeux support
  • 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
  • The Bayeux Protocol
    • http://svn.xantus.org/shortbus/trunk/bayeux/bayeux.html
    • Bayeux is a JSON-based protocol for clients to register interest in events and for servers to deliver them in a more timely fashion than Ajax-based polling allows.
    • With Bayeux, you only needs to write the client.
    • The goals of the Bayeux spec so far have been to:
      • make event delivery fast
      • keep it simple
      • provide extension points in the protocol
  • 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
  • Bayeux Multiple Channels Http Comet and Reverse Ajax Cometd clients
      • JSON Messages are published on specified channels
  • Bayeux/Cometd JSON Publish/Subscribe
    • JSON Messages are published on specified channels
    • Channel operations: connect, subscribe, unsubscribe, etc.
    • Multiple transports: polling, long-polling, iframe, flash
    • Server-side just event bus for client side
    [ { &quot;channel&quot;: &quot;/some/name&quot;, &quot;clientId&quot;: &quot;83js73jsh29sjd92&quot;, &quot;data&quot;: { &quot;myapp&quot; : &quot;specific data&quot;, value: 100 } } ]
  • Enable Comet in GlassFish V2 Admin Console
  • Configure Cometd
    • Enabling Bayeux in GlassFish
      • web.xml
      • <servlet>
      • <servlet-name> Grizzly Cometd Servlet </servlet-name>
      • <servlet-class> com.sun.grizzly.cometd.servlet.CometdServlet </servlet-class>
      • </servlet>
      • <servlet-mapping>
      • <servlet-name> Grizzly Cometd Servlet </servlet-name>
      • <url-pattern> /cometd/* </url-pattern>
      • </servlet-mapping>
  • Cometd HTTP Requests
    • dojox.cometd
    • Dojo-based JavaScript client
    • Implementation of Bayeux Protocol
  • RESTful Web Services and Comet http://developers.sun.com/appserver/reference/techart/cometslideshow.html
  • RESTful Slideshow Web Service http://host/slideshow/resources/slides/ HTTP GET {&quot;url&quot;:&quot;http://host/slideshow/image1.jpg&quot;, {&quot;url&quot;:&quot;http://host/slideshow/image2.jpg&quot;} Response JSON slide urls Server Client Addressable Resources Web Container
  • Cometd Step1 : Initialize dojo.require(&quot; dojox.cometd &quot;); //Initialize a connection to the given Comet server: the GlassFish Grizzly Bayeux servlet dojox.cometd. init (&quot;serverURL&quot;); Comet Server Client 1 Client 2
  • Cometd Step 2: Subscribe dojox.cometd. subscribe (“topic”, &quot;object&quot;, &quot;callbackFunction&quot;);
    • Subscribes the client to the topic channel
    • Any time a message is sent to the topic channel
    • the object's callback will be invoked
    Comet Server Client 1 Client 2
  •  
  •  
  • Cometd Step 3: Publish dojox.cometd. publish (&quot;topic&quot;, {slide: url}); a client publishes the next slide url to the topic channel JSON message client 1 Comet Server Next slide url
  •  
  • Cometd Step 4: Update Clients: CallBack callBackFunction(slideUrl) { slide.innerHTML =&quot;<img src='&quot; + slideUrl + &quot;'/>&quot;; ... }
    • The callback function is called with the published message when a new message is received
    • This callback function updates the browser content
      • html img tag with the slide url from the published message
    Update Browser Update Browser Comet Server Client 2 Client 3
  •  
  • Summary
    • REST architecture is gaining popularity
      • Simple, scalable and the infrastructure is already in place
    • JAX-RS (JSR-311) provides a high level declarative programming model
      • http://jersey.dev.java.net
      • NetBeans 6.1 , 6.5 has wizards to help
    • Dojo makes javascript easier
    • Dojo cometd with Grizzly makes building comet apps easy
  • RESTful Web Services and Comet http://developers.sun.com/appserver/reference/techart/cometslideshow.html
  • RESTful Web Services http://netbeans.tv/screencasts/offset/7/
  • Example RESTful Catalog http://weblogs.java.net/blog/caroljmcdonald/archive/2008/08/a_restful_pet_c.html
  • For More Information
    • Web 2.0 & ajax
      • http://developers.sun.com/ajax/
    • Dojo
      • http://dojotoolkit.org/
    • JAX-RS Reference Implementation
      • http://jersey.dev.java.net/
    • Glassfish
      • https://glassfish.dev.java.net/
      • http://blogs.sun.com/theaquarium/
    • Cometd
      • http://cometdproject.dojotoolkit.org/
    • Carol's Blog
      • http://weblogs.java.net/blog/caroljmcdonald/
    • Presenter’s Name
      • [email_address]
    Carol McDonald Java Architect http://weblogs.java.net/blog/caroljmcdonald/