<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:series="http://organizeseries.com/"
	>

<channel>
	<title>SitePen Blog &#187; Cometd</title>
	<atom:link href="http://www.sitepen.com/blog/category/cometd/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sitepen.com/blog</link>
	<description>SitePen Services and notes about Dojo, Persevere, CometD, JavaScript, and the Web</description>
	<lastBuildDate>Wed, 22 May 2013 22:36:10 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5</generator>
		<item>
		<title>Dojo WebSocket with AMD</title>
		<link>http://www.sitepen.com/blog/2012/11/05/dojo-websocket-with-amd/</link>
		<comments>http://www.sitepen.com/blog/2012/11/05/dojo-websocket-with-amd/#comments</comments>
		<pubDate>Mon, 05 Nov 2012 19:23:29 +0000</pubDate>
		<dc:creator>Kris Zyp</dc:creator>
				<category><![CDATA[comet]]></category>
		<category><![CDATA[Cometd]]></category>
		<category><![CDATA[Dojo]]></category>
		<category><![CDATA[Persevere]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/?p=5475</guid>
		<description><![CDATA[<p>Dojo has an API for Comet-style real-time communication based on the WebSocket API. WebSocket provides a bi-directional connection to servers that is ideal for pushing messages from a server to a client in real-time. Dojo&#8217;s dojox/socket module provides access to this API with automated fallback to HTTP-based long-polling for browsers (or servers) that do not [...]</p><p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></description>
				<content:encoded><![CDATA[<p>Dojo has an API for Comet-style real-time communication based on the WebSocket API. WebSocket provides a bi-directional connection to servers that is ideal for pushing messages from a server to a client in real-time. Dojo&#8217;s  <code>dojox/socket</code> module provides access to this API with automated fallback to HTTP-based long-polling for browsers (or servers) that do not support the new WebSocket API. This allows you start using this API with Dojo now.</p>
<p><span id="more-5475"></span></p>
<p>The <code>dojox/socket</code> module is designed to be simple, lightweight, and protocol agnostic. In the past Dojo has provided protocol specific modules like CometD and RestChannels, but there are numerous other Comet protocols out there, and <code>dojox/socket</code> provides the flexibility to work with virtually any of them, with a simple foundational interface. The <code>dojox/socket</code> module simply passes strings over the HTTP or WebSocket connection, making it compatible with any system.</p>
<p>The simplest way to start a <code>dojox/socket</code> is to simply call it with a URL path:</p>
<pre lang="javascript">
require(["dojox/socket"], function (Socket) {
	// Create socket instance
	var socket = new Socket("/comet");
});
</pre>
<p>The socket module will then connect to the origin server using WebSocket, or HTTP as a fallback. We can now listen for message events from the server:</p>
<pre lang="javascript">
socket.on("message", function(event){
	var data = event.data;
	// do something with the data from the server
});
</pre>
<p>Here we use the <code>socket.on()</code> event registration method (inspired by <a href="http://github.com/LearnBoost/Socket.IO">socket.io</a> and NodeJS&#8217;s registration method) to listen to &#8220;message events&#8221; and retrieve data when they occur. This method is also aliased to the deprecated Dojo style <code>socket.connect()</code>.</p>
<p>We can also use <code>send()</code> to send data to the server. If you have just started the connection, you should wait for the <code>open</code> event to ensure the connection is ready to send data:</p>
<pre lang="javascript">
socket.on("open", function(event){
  socket.send("hi server");
});
</pre>
<p>Finally, we can listen for the connection being closed by the server or network by listening for the <code>close</code> event. And we can initiate the close of a connection from the client by calling <code>socket.close()</code>.</p>
<p>The <code>dojox/socket</code> method can also be called with standard Dojo IO arguments to initiate the communication with the server. This makes it easy to provide any necessary headers for the requests. For example:</p>
<pre lang="javascript">
var socket = new Socket({
	url:"/comet",
	headers: {
		"Accept": "application/json",
		"Content-Type": "application/json"
	}});
</pre>
<p>This will automatically translate the relative URL path to a WebSocket URL (using <code>ws://</code> scheme) or an HTTP URL depending on the browser capability.</p>
<p>For some applications, the server may only support HTTP/long-polling (without real WebSocket support). We can also explicitly create a long-poll based connection:</p>
<pre lang="javascript">
var socket = new Socket.LongPoll({
	url:"/comet",
	headers: {
		"Accept": "application/json",
		"Content-Type": "application/json"
	}});
</pre>
<p>We can also provide alternate transports in the socket arguments object. This would allow us to use the <code>get()</code> method in <code>dojo/io/script</code> to connect to a server. However, a more robust solution is to use the <a href="http://www.sitepen.com/blog/2008/07/31/cross-site-xhr-plugin-registry/"><code>dojox/io/xhrPlugins</code></a> for cross-domain long-polling, which will work properly with <code>dojox/socket</code>.</p>
<h2>Auto-Reconnect</h2>
<p>In addition to <code>dojox/socket</code>, we have also added a <code>dojox/socket/Reconnect</code> module. This wraps a socket, adding auto-reconnection support. When a socket is closed by network or server problems, this module will automatically attempt to reconnect to the server on a periodic basis, with a back-off algorithm to minimize resource consumption. We can upgrade a socket to auto-reconnect by this simple code fragment:</p>
<pre lang="javascript">
require(["dojox/socket", "dojox/socket/Reconnect"], 
	function (Socket, Reconnect) {
	// Create socket instance
	var socket = new Reconnect(new Socket("/comet"));
});
</pre>
<h2>Using Dojo WebSocket with Object Stores</h2>
<p>One of the other big enhancements in Dojo is the <a href="http://dojotoolkit.org/reference-guide/1.8/dojo/store.html#dojo-store">Dojo object store API</a> (which supercedes the Dojo Data API), based on the HTML5 IndexedDB object store API. Dojo comes with several store wrappers, and the <code>Observable</code> store provides notification events that work very well with Comet driven updates. <code>Observable</code> is a store wrapper. To use it, we first create a store, and then wrap it with Observable:</p>
<pre lang="javascript">
require([
	"dojo/store/JsonRest",
	"dojo/store/Observable"
], function(JsonRest, Observable){
	var store = Observable(new JsonRest({data:myData}));
});
</pre>
<p>This store will now provide an <code>observe()</code> method on query results that widgets can use to react to changes in the data. We can notify the store of changes from the server by calling the <code>notify()</code> method on the store:</p>
<pre lang="javascript"> 
socket.on("message", function(event){
  var existingId = event.data.id;
  var object = event.data.object;
  store.notify(object, existingId);
});
</pre>
<p>We can signal a new object by calling <code>store.notify()</code> and omitting the id, and a deleted object by omitting the object (undefined). A changed/updated object should include both.</p>
<h3>Handling Long-Polling from your Server</h3>
<p>Long-polling style connection emulation can require some care on the server-side. For many applications, the server may have sufficient information from request cookies (or other ambient data) to determine what messages to send the browser. However, other applications may vary on what information should be sent to the browser during the life of the application. Different topics may be subscribed to and unsubscribed from. In these situations, the server may need to correlate different HTTP requests with a single connection and its associated state. While there are numerous protocols, one could do this very easily be defining a unique connection and adding that as a header for the socket (the headers are added to each request in the long-poll cycles). For example, we could do:</p>
<pre lang="javascript">
require([
	"dojox/socket"
], function(Socket){
	var socket = Socket.LongPoll({
		url:"/comet",
		headers: {
			"Accept": "application/json",
			"Content-Type": "application/json",
			"Client-Id": Math.random()
		}});
});
</pre>
<p>In addition, <code>dojox/socket</code> includes a <code>Pragma: long-poll</code> to indicate the first request in a series of long-poll requests to help a server ensure that the connection setup and timeout is properly handled.</p>
<p>We can easily use <code>dojox/socket</code> with other protocols as well:</p>
<h3>CometD</h3>
<p>To initiate a Comet connection with a <a href="http://cometd.org/">CometD</a> server, we can do a CometD handshake, connection, and subscription:</p>
<pre lang="javascript">
var socket = new Socket("/cometd");
function send(data){
  return socket.send(json.stringify(data));
}
socket.on("connect", function(){
  // send a handshake
  send([
    {
       "channel": "/meta/handshake",
       "version": "1.0",
       "minimumVersion": "1.0beta",
       "supportedConnectionTypes": ["long-polling"] // or ["callback-polling"] for x-domain
     }
  ])
  socket.on("message", function(data){
    // wait for the response so we can connect with the provided client id
    data = json.parse(data);
    if(data.error){
      throw new Error(error);
    }
    // get the client id for all future messages
    clientId = data.clientId;
    // send a connect message
    send([
      {
         "channel": "/meta/connect",
         "clientId": clientId,
         "connectionType": "long-polling"
       },
       {  // also send a subscription message
         "channel": "/meta/subscribe",
         "clientId": clientId,
         "subscription": "/foo/**"
       }
    ]);
    socket.on("message", function(){
      // handle messages from the server
    });
  });
});
</pre>
<h3>Socket.IO</h3>
<p><a href="http://socket.io/">Socket.IO</a> provides a lower-level interface like <code>dojox/socket</code>, providing simple text-based message passing. Here is an example of how to connect to a Socket.IO server:</p>
<pre lang="javascript">
require([
	"dojo/request", "dojox/socket"
], function(request, Socket){
	var
		args = {},
		ws = typeof WebSocket != "undefined",
		url =  ws ? "/socket.io/websocket" : "/socket.io/xhr-polling";
		
	var socket = new Socket(args = {
		url:url,
		headers:{
			"Content-Type":"application/x-www-urlencoded"
		},
		transport: function(args, message){
			args.data = message; // use URL-encoding to send the message instead of a raw body
			request.post(url, args);
		}
	});
	var sessionId;
	socket.on("message", function(){
		if (!sessionId){
			sessionId = message;
			url += '/' + sessionId;
		}else if(message.substr(0, 3) == '~h~'){
			// a heartbeat
		}
	});
});
</pre>
<h3>Comet Session Protocol</h3>
<p>And here is an example of connecting to a <a href="http://orbited.org/csp/">Comet Session Protocol</a> server (the following example was tested with <a href="http://orbited.org/">Orbited</a>, but could work with <a href="http://hookbox.org/">Hookbox</a>, APE, and others):</p>
<pre lang="javascript">
require([
	"dojo/json", "dojox/socket"
], function(json, Socket){
	var args, socket = new Socket(args = {
		url: "/csp/handshake"
	});
	function send(data){
		return socket.send(json.stringify(data));
	}
	var sessionId = Math.random().toString().substring(2);
	socket.on("connect", function(){
		send({session:sessionId});
		socket.on("message", function(){
			args.url = "/csp/comet";
			send({session:sessionId});
		});
	});
});
</pre>
<h3>Tunguska</h3>
<p><a href="http://www.sitepen.com/blog/2010/07/19/real-time-comet-applications-on-node-with-tunguska/">Tunguska</a> provides a Comet-based interface for subscribing to data changes. This is a very simple protocol which allows us to communicate with a Tunguska server:</p>
<pre lang="javascript">
var socket = new Socket({
	url:"/comet",
	headers: {
		"Accept": "application/json",
		"Content-Type": "application/json",
		"Client-Id": Math.random()
	}});  
function send(data){
	return socket.send(json.stringify(data));
}
socket.on("connect", function(){
	// now subscribe to all changes for MyTable
	send([{"to":"/MyTable/*", "method":"subscribe"}]);
});
</pre>
<h2>Conclusion</h2>
<p>Dojo&#8217;s socket API is a flexible simple module for connecting to a variety of servers and building powerful, efficient real-time applications without constraints. This adds to the array of awesome features in Dojo.</p>
<p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2012/11/05/dojo-websocket-with-amd/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Now Supporting all Major Toolkits!</title>
		<link>http://www.sitepen.com/blog/2012/07/19/now-supporting-all-major-toolkits/</link>
		<comments>http://www.sitepen.com/blog/2012/07/19/now-supporting-all-major-toolkits/#comments</comments>
		<pubDate>Thu, 19 Jul 2012 15:20:25 +0000</pubDate>
		<dc:creator>Dylan Schiemann</dc:creator>
				<category><![CDATA[ajax]]></category>
		<category><![CDATA[AMD]]></category>
		<category><![CDATA[Cometd]]></category>
		<category><![CDATA[CommonJS]]></category>
		<category><![CDATA[dgrid]]></category>
		<category><![CDATA[Dojo]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Node.js]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Persevere]]></category>
		<category><![CDATA[Support]]></category>
		<category><![CDATA[backbone]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[mootools]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[support]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/?p=4951</guid>
		<description><![CDATA[<p>We have been providing JavaScript and Dojo support to freelancers, start-ups and Fortune 500 companies for nearly a decade. As we intently watch enterprise organizations everywhere begin to roll out AMD (read about why AMD matters) and the associated code improvements, we are thrilled with the industry&#8217;s direction toward toolkit interoperability! Why? Because! Our masterful [...]</p><p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></description>
				<content:encoded><![CDATA[<p>We have been providing JavaScript and Dojo support to freelancers, start-ups and Fortune 500 companies for nearly a decade.  As we intently watch enterprise organizations everywhere begin to roll out AMD <a href="http://www.sitepen.com/blog/2012/07/10/amd-for-the-business-side/">(read about why AMD matters)</a> and the associated code improvements, we are thrilled with the industry&#8217;s direction toward toolkit interoperability!  Why?  Because! Our masterful engineering team, consisting of influential members of various open source communities, positions SitePen perfectly to offer full-on, front-end web development support to the world! </p>
<p>Getting right to the point, (<a href="http://www.prnewswire.com/news-releases/sitepen-expands-service-offering-to-popular-javascript-toolkits-163018596.html">The Official Point!</a>), we are pleased to announce the expansion of SitePen Support to officially include more than fifteen popular open-source JavaScript toolkits! </p>
<p><strong>Now supporting the following JavaScript toolkits:</strong></p>
<table style="width:600px;">
<tr>
<td>
<ul>
<li>Dojo</li>
<li>Persevere packages</li>
<li>dgrid</li>
<li>Curl.js</li>
<li>CometD</li>
<li>Twine</li>
</ul>
</td>
<td>
<ul>
<li>jQuery</li>
<li>Backbone</li>
<li>underscore</li>
<li>RequireJS</li>
<li>PhoneGap/Cordova</li>
<li>MooTools</li>
</ul>
</td>
<td>
<ul>
<li>jQueryUI</li>
<li>Wire</li>
<li>Socket.IO</li>
<li>Express</li>
</ul>
</td>
</tr>
</table>
<p>In addition to toolkits, we will continue to support your custom JavaScript source code, as well as key underlying technologies and formats, including JSON, HTML5, WebSockets, SVG/Canvas, Mobile Web, Server-Side JavaScript, AMD, Node.js and many more.</p>
<p>Our expertise with Dojo and advanced JavaScript is relevant for a wide-range of desktop and mobile web application projects and our approach to SitePen Support has always been flexible with the priority being to improve our customers&#8217; web apps.  We strive to support our customers in every way possible and we continue to be Dojo experts. In addition, we&#8217;re now committed to providing your organization with the front-end development expertise that will optimize your application regardless of which toolkits and technologies your company is comfortable using.  You have our word!</p>
<p>Learn More About <a href="http://www.sitepen.com/support/index.html">SitePen Support</a> or <a href="http://www.sitepen.com/site/contact.html">Contact Us </a>to get started today!</p>
<p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2012/07/19/now-supporting-all-major-toolkits/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Dojo WebSocket</title>
		<link>http://www.sitepen.com/blog/2010/10/31/dojo-websocket/</link>
		<comments>http://www.sitepen.com/blog/2010/10/31/dojo-websocket/#comments</comments>
		<pubDate>Mon, 01 Nov 2010 06:54:44 +0000</pubDate>
		<dc:creator>Kris Zyp</dc:creator>
				<category><![CDATA[Cometd]]></category>
		<category><![CDATA[Dojo]]></category>
		<category><![CDATA[Persevere]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/?p=1960</guid>
		<description><![CDATA[<p>NOTE: This post is out of date.Read our updated version of this post for more up to date information! Dojo 1.6 introduces a new API for Comet-style real-time communication based on the WebSocket API. WebSocket provides a bi-directional connection to servers that is ideal for pushing messages from a server to a client in real-time. [...]</p><p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></description>
				<content:encoded><![CDATA[<div style="background:#FFFFCC; padding: 1em; font-weight:bold; border:1px solid #FFCC99; margin-bottom:1em">NOTE: This post is out of date.<br /><a href="http://www.sitepen.com/blog/2012/11/05/dojo-websocket-with-amd/">Read our updated version of this post for more up to date information</a>!</div>
<p>Dojo 1.6 introduces a new API for Comet-style real-time communication based on the WebSocket API. WebSocket provides a bi-directional connection to servers that is ideal for pushing messages from a server to a client in real-time. Dojo&#8217;s new <code>dojox.socket</code> module provides access to this API with automated fallback to HTTP-based long-polling for browsers (or servers) that do not support the new WebSocket API. This allows you start using this API with Dojo now.</p>
<p><span id="more-1960"></span></p>
<p>The <code>dojox.socket</code> module is designed to be simple, lightweight, and protocol agnostic. In the past Dojo has provided protocol specific modules like CometD and RestChannels, but there are numerous other Comet protocols out there, and <code>dojox.socket</code> provides the flexibility to work with virtually any of them, with a simple foundational interface. The <code>dojox.socket</code> module simply passes strings over the HTTP or WebSocket connection, making it compatible with any system.</p>
<p>The simplest way to start a <code>dojox.socket</code> is to simply call it with a URL path:</p>
<pre lang="javascript">
var socket = dojox.socket("/comet");
</pre>
<p>We can now listen for message events from the server:</p>
<pre lang="javascript">
socket.on("message", function(event){
  var data = event.data;
  // do something with the data from the server
});
</pre>
<p>Here we use the <code>socket.on()</code> event registration method (inspired by <a href="http://github.com/LearnBoost/Socket.IO">socket.io</a> and NodeJS&#8217;s registration method) to listen to &#8220;message events&#8221; and retrieve data when they occur. This method is also aliased to the Dojo style <code>socket.connect()</code>.</p>
<p>We can also use <code>send()</code> to send data to the server. If you have just started the connection, you should wait for the <code>open</code> to ensure the connection is ready to send data:</p>
<pre lang="javascript">
socket.on("open", function(event){
  socket.send("hi server");
});
</pre>
<p>Finally, we can listen for the connection being closed by the server or network by listening for the &#8220;close&#8221; event. And we can initiate the close of a connection from the client by calling <code>socket.close()</code>.</p>
<p>The <code>dojox.socket</code> method can also be called with standard Dojo IO arguments to initiate the communication with the server. This makes it easy to provide any necessary headers for the requests. For example:</p>
<pre lang="javascript">
var socket = dojox.socket({
	url:"/comet",
	headers: {
		"Accept": "application/json",
		"Content-Type": "application/json"
	}});
</pre>
<p>This will automatically translate the relative URL path to a WebSocket URL (using <code>ws://</code> scheme) or an HTTP URL depending on the browser capability.</p>
<p>For some applications, the server may only support HTTP/long-polling (without real WebSocket support). We can also explicitly create a long-poll based connection:</p>
<pre lang="javascript">
var socket = dojox.socket.LongPoll({
	url:"/comet",
	headers: {
		"Accept": "application/json",
		"Content-Type": "application/json"
	}});
</pre>
<p>We can also provide alternate transports in the socket arguments object. This would allow us to use <code>dojo.io.script.get</code> to connect to a server. However, a more robust solution is to use the <a href="http://www.sitepen.com/blog/2008/07/31/cross-site-xhr-plugin-registry/"><code>dojox.io.xhrPlugins</code></a> for cross-domain long-polling, which will work properly with <code>dojox.socket</code>.</p>
<h2>Auto-Reconnect</h2>
<p>In addition to <code>dojox.socket</code>, we have also added a <code>dojox.socket.Reconnect</code> module. This wraps a socket, adding auto-reconnection support. When a socket is closed by network or server problems, this module will automatically attempt to reconnect to the server on a periodic basis, with a back-off algorithm to minimize resource consumption. We can upgrade a socket to auto-reconnect by this simple code fragment:</p>
<pre lang="javascript">
socket = dojox.socket.Reconnect(socket);
</pre>
<h2>Using Dojo WebSocket with Object Stores</h2>
<p>One of the other big enhancements in Dojo 1.6 is the <a href="http://www.dojotoolkit.org/reference-guide/dojo/store.html">new Dojo object store API</a> (supercedes the Dojo Data API), based on the HTML5 IndexedDB object store API. Dojo 1.6 comes with several store wrappers, and the <code>Observable</code> store provides notification events that work very well with Comet driven updates. <code>Observable</code> is a store wrapper. To use it, we first create a store, and then wrap it with Observable:</p>
<pre lang="javascript">
define("my-module", function(require){
  var JsonRest = require("dojo/store/JsonRest");
  var Observable = require("dojo/store/Observable");
  var store = new JsonRest({data:myData});
  store = Observable(store);
});
</pre>
<p>This store will now provide an <code>observe()</code> method on query results that widgets can use to react to changes in the data. We can notify the store of changes from the server by calling the <code>notify()</code> method on the store:</p>
<pre lang="javascript"> 
socket.on("message", function(event){
  var existingId = event.data.id;
  var object = event.data.object;
  store.notify(object, existingId);
});
</pre>
<p>We can signal a new object by calling <code>store.notify()</code> and omitting the id, and a deleted object by omitting the object (undefined). A changed/updated object should include both.</p>
<h3>Handling Long-Polling from your Server</h3>
<p>Long-polling style connection emulation can require some care on the server-side. For many applications, the server may have sufficient information from request cookies (or other ambient data) to determine what messages to send the browser. However, other applications may vary on what information should be sent to the browser during the life of the application. Different topics may be subscribed to and unsubscribed from. In these situations, the server may need to correlate different HTTP requests with a single connection and its associated state. While there are numerous protocols, one could do this very easily be defining a unique connection and adding that as a header for the socket (the headers are added to each request in the long-poll cycles). For example, we could do:</p>
<pre lang="javascript">
var socket = dojox.socket.LongPoll({
	url:"/comet",
	headers: {
		"Accept": "application/json",
		"Content-Type": "application/json",
		"Client-Id": Math.random()
	}});
</pre>
<p>In addition, <code>dojox.socket</code> includes a <code>Pragma: long-poll</code> to indicate the first request in a series of long-poll requests to help a server ensure that the connection setup and timeout is properly handled.</p>
<p>We can easily use <code>dojox.socket</code> with other protocols as well:</p>
<h3>CometD</h3>
<p>To initiate a Comet connection with a <a href="http://cometd.org/">CometD</a> server, we can do a CometD handshake, connection, and subscription:</p>
<pre lang="javascript">
var socket = dojox.socket("/cometd");
function send(data){
  return socket.send(dojo.toJson(data));
}
socket.on("connect", function(){
  // send a handshake
  send([
    {
       "channel": "/meta/handshake",
       "version": "1.0",
       "minimumVersion": "1.0beta",
       "supportedConnectionTypes": ["long-polling"] // or ["callback-polling"] for x-domain
     }
  ])
  socket.on("message", function(data){
    // wait for the response so we can connect with the provided client id
    data = dojo.fromJson(data);
    if(data.error){
      throw new Error(error);
    }
    // get the client id for all future messages
    clientId = data.clientId;
    // send a connect message
    send([
      {
         "channel": "/meta/connect",
         "clientId": clientId,
         "connectionType": "long-polling"
       },
       {  // also send a subscription message
         "channel": "/meta/subscribe",
         "clientId": clientId,
         "subscription": "/foo/**"
       }
    ]);
    socket.on("message", function(){
      // handle messages from the server
    });
  });
});
</pre>
<h3>Socket.IO</h3>
<p><a href="http://socket.io/">Socket.IO</a> provides a lower-level interface like dojox.socket, providing simple text-based message passing. Here is an example of how to connect to a Socket.IO server:</p>
<pre lang="javascript">
var args, ws = typeof WebSocket != "undefined";
var socket = dojox.socket(args = {
  url: ws ? "/socket.io/websocket" : "/socket.io/xhr-polling",
  headers:{
    "Content-Type":"application/x-www-urlencoded"
  },
  transport: function(args, message){
    args.content = message; // use URL-encoding to send the message instead of a raw body
    dojo.xhrPost(args);
  };
});
var sessionId;
socket.on("message", function(){
  if (!sessionId){
    sessionId = message;
    args.url += '/' + sessionId;
  }else if(message.substr(0, 3) == '~h~'){
    // a heartbeat
  }
});
</pre>
<h3>Comet Session Protocol</h3>
<p>And here is an example of connecting to a <a href="http://orbited.org/csp/">Comet Session Protocol</a> server (the following example was tested with <a href="http://orbited.org/">Orbited</a>, but could work with <a href="http://hookbox.org/">Hookbox</a>, APE, and others):</p>
<pre lang="javascript">
var args, socket = dojox.socket(args = {
  url: "/csp/handshake"
});
function send(data){
  return socket.send(dojo.toJson(data));
}
var sessionId = Math.random().toString().substring(2);
socket.on("connect", function(){
  send({session:sessionId});
  socket.on("message", function(){
    args.url = "/csp/comet";
    send({session:sessionId});
  });
});
</pre>
<h3>Tunguska</h3>
<p>Tunguska provides a Comet-based interface for subscribing to data changes. This is a very simple protocol which allows us to communicate with a Tunguska server:</p>
<pre lang="javascript">
var socket = dojox.socket({
	url:"/comet",
	headers: {
		"Accept": "application/json",
		"Content-Type": "application/json",
		"Client-Id": Math.random()
	}});  
function send(data){
  return socket.send(dojo.toJson(data));
}
socket.on("connect", function(){
  // now subscribe to all changes for MyTable
  send([{"to":"/MyTable/*", "method":"subscribe"}]);
});
</pre>
<h2>Conclusion</h2>
<p>Dojo&#8217;s socket API is a flexible simple module for connecting to a variety of servers and building powerful, efficient real-time applications without constraints. This adds to the array of awesome new features and improvements in Dojo 1.6.</p>
<p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2010/10/31/dojo-websocket/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Facebook and FriendFeed&#8217;s Tornado is now Open Source</title>
		<link>http://www.sitepen.com/blog/2009/09/11/facebook-and-friendfeeds-tornado-is-now-open-source/</link>
		<comments>http://www.sitepen.com/blog/2009/09/11/facebook-and-friendfeeds-tornado-is-now-open-source/#comments</comments>
		<pubDate>Fri, 11 Sep 2009 20:12:30 +0000</pubDate>
		<dc:creator>Dylan Schiemann</dc:creator>
				<category><![CDATA[Cometd]]></category>
		<category><![CDATA[Open Source]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/2009/09/11/facebook-and-friendfeeds-tornado-is-now-open-source/</guid>
		<description><![CDATA[<p>Orbited, cometD-python, and other Python Comet servers have new competition in the form of Facebook&#8217;s now open source Tornado web server. Tornado was part of the technology acquired by Facebook when they purchased FriendFeed last month, and Facebook has decided to open it up under the Apache version 2 license. Tornado supports long-polling and HTTP [...]</p><p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></description>
				<content:encoded><![CDATA[<p><a href="http://orbited.org/">Orbited</a>, <a href="http://cometd.org/">cometD-python</a>, and other Python Comet servers have new competition in the form of Facebook&#8217;s now open source <a href="http://www.tornadoweb.org/">Tornado web server</a>.  Tornado was part of the technology acquired by Facebook when they purchased FriendFeed last month, and Facebook has decided to open it up under the Apache version 2 license.</p>
<p>Tornado supports long-polling and HTTP streaming, but also includes many of the web site building blocks found in frameworks like <a href="http://www.djangoproject.com/">Django</a>.  This is a really exciting announcement as Facebook and Google (with their <a href="http://wave.google.com/">Wave</a> product) have both made major announcements around <a href="http://cometdaily.com/">Comet</a> technologies, bringing real-time capabilities to the mainstream, under open source licenses.</p>
<p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2009/09/11/facebook-and-friendfeeds-tornado-is-now-open-source/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using REST Channels with cometD</title>
		<link>http://www.sitepen.com/blog/2009/06/15/using-rest-channels-with-cometd/</link>
		<comments>http://www.sitepen.com/blog/2009/06/15/using-rest-channels-with-cometd/#comments</comments>
		<pubDate>Mon, 15 Jun 2009 08:02:43 +0000</pubDate>
		<dc:creator>Kris Zyp</dc:creator>
				<category><![CDATA[Bayeux]]></category>
		<category><![CDATA[Cometd]]></category>
		<category><![CDATA[Dojo]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/2009/06/15/using-rest-channels-with-cometd/</guid>
		<description><![CDATA[<p>REST Channels provides a mechanism for receiving notifications of data changes and integrates Comet-style asynchronous server sent messages with a RESTful data-oriented architecture. Dojo includes a REST Channels client module which integrates completely with Dojo&#8217;s JsonRestStore, allowing messages to be delivered through the Dojo Data API seamlessly to consuming widgets, with minimal effort. The REST [...]</p><p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></description>
				<content:encoded><![CDATA[<p><a href="http://cometdaily.com/2008/09/02/rest-channels-http-channels-with-json-support/">REST Channels</a> provides a mechanism for receiving notifications of data changes and integrates Comet-style asynchronous server sent messages with a RESTful data-oriented architecture. <a href="http://cometdaily.com/2008/11/12/using-rest-channels-in-dojo/">Dojo includes a REST Channels client module</a> which integrates completely with <a href="http://dojotoolkit.org/">Dojo&#8217;s</a> <a href="http://docs.dojocampus.org/dojox/data/JsonRestStore">JsonRestStore</a>, allowing messages to be delivered through the Dojo Data API seamlessly to consuming widgets, with minimal effort. The REST Channels module will automatically connect to a REST Channels server, like <a href="http://www.persvr.org/">Persevere</a> (which offers REST Channels out of the box). However, existing infrastructure may necessitate the use of an alternate Comet server like <a href="http://docs.codehaus.org/display/JETTY/Cometd+(aka+Bayeux)">Jetty&#8217;s cometD</a> server. REST Channels can be used on top of another Comet protocol like <a href="http://svn.xantus.org/shortbus/trunk/bayeux/bayeux.html">Bayeux&#8217;s</a> long-polling protocol and with a little bit of reconfiguration, you can use Dojo&#8217;s REST Channels with a cometD server to achieve Comet-REST integration.</p>
<p><span id="more-724"></span></p>
<h2>Receiving Data Notifications</h2>
<p>REST Channels is designed to unite the concept of topics with resource locators. Therefore, REST Channels can leverage Bayeux&#8217;s topic names to indicate the resource that is being targeted. We can then subscribe to Bayeux&#8217;s channels and then delegate all the data notification messages to the restListener which will delegate the proper data events through the data stores:</p>
<pre lang="javascript">
// first initialize cometD
dojo.require("dojox.cometd");
dojo.require("dojox.cometd.RestChannels");

dojox.cometd.init("/cometd");

dojo.subscribe("/cometd/**", function(msg){
   dojox.data.restListener({
      channel: msg.channel,
      event: msg.data.event,
      result: msg.data.result
   });
});
</pre>
<p>This could be used in conjunction with a JsonRestStore, and messages would be delegated to the store&#8217;s events:</p>
<pre lang="javascript">
weatherStore = new dojox.data.JsonRestStore({target:"/weather/"});
</pre>
<p>Now it is possible to publish data change notification messages such that clients will receive and interpret the messages properly. To publish a data notification message on Jetty&#8217;s cometD hub, we can call the <code>doPublish</code> with something like:</p>
<pre lang="java">
bayeux.doPublish("/weather/lax", null, laxWeatherUpdate, null);
</pre>
<p>Which should produce a Bayeux notification message like:</p>
<pre lang="javascript">
{
  "channel": "/weather/lax",
  "clientId": "23ab8a887baaa",
  "data": {
     "event":"PUT",
     "result":{
       "low": 65,
       "high": 78,
       "skies": "clear"
    }
  }
}
</pre>
<p>Now this message will be routed through the restListener and onSet events will be fired for any attributes that were updated in the local cache of the &#8220;/weather/lax&#8221; item. If the <i>lax</i> item was being displayed in a data-aware widget, it will automatically be updated. For example, the DataGrid supports data notification events, and if this item appears in a DataGrid, the corresponding row will automatically display the new value.</p>
<h2>Subscribing to Resources</h2>
<p>One of the key integration points that REST Channels provides between data access and notification routing is in auto-subscribing to resources when they are retrieved. The primary use case for REST Channels is in providing a real-time view of data, and therefore when data is retrieved from the server, REST Channels can automatically subscribe to the resource to receive all future notifications of changes to the object. With a true REST Channels implementation, subscription information is included in GET requests, so that a single request can be made to a server that both requests a resource and subscribes to it at the same time. If you are just using a cometD server, such an integration is not automatic. There are a couple of different approaches for subscribing to resources.</p>
<p>On the client-side, we can send subscription requests when we make GET requests. This can be done by intercepting the REST GET request handler, and creating subscriptions. </p>
<pre lang="javascript">
dojo.connect(dojo, "xhrGet", function(args){
  dojox.cometd.subscribe(args.url, function(){
    // nothing needed, handled by the catch-all subscription
  });
});
</pre>
<p>All GET requests will then trigger a subscription automatically. One could easily add some conditional logic that only subscribes on a subset of requests.</p>
<p>The biggest disadvantage of client generated subscription requests is that they generate two requests for each resource access, one GET and one subscription request (as a POST). If the REST handler for a server can be modified to understand the subscription header that REST Channels adds to GET requests, the server can subscribe the client without requiring additional requests. The key to making this work, is to be able to connect cometD&#8217;s client connections with the request handler. One way to do this is to define a Bayeux handler that will put the current client object in the HTTP session, and then retrieve it from the session in the REST handler. The REST handler can then subscribe the client to the resource locator topic.</p>
<p>One tricky aspect of this approach is that it is possible for multiple client connections to exist in a single session. Each page will have its own cometD client connection, but will be in the same HTTP session. Therefore, the client connections need to be stored and accessed by their client id. In order for the REST handler to determine the correct client id for a client, you can have the Client-Id header set on the  requests, and then this id can be used to find the correct Bayeux client connection. RestChannels automatically sets the Client-Id header, but the correct client id from the cometD handler must be assigned to the RestChannels clientId variable:</p>
<pre lang="javascript">
dojox.cometd.init("/cometd").addCallback(function(){
  dojox.rpc.Client.clientId = dojox.cometd.clientId;
});
</pre>
<p>Together these techniques can be used to combine a REST architecture with a cometD server for data notifications with Dojo&#8217;s REST capabilities in JsonRestStore, and complete integration into Dojo&#8217;s data event notification system.</p>
<p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2009/06/15/using-rest-channels-with-cometd/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Stocker: Advanced Dojo Made Easy</title>
		<link>http://www.sitepen.com/blog/2009/04/01/stocker-advanced-dojo-made-easy/</link>
		<comments>http://www.sitepen.com/blog/2009/04/01/stocker-advanced-dojo-made-easy/#comments</comments>
		<pubDate>Wed, 01 Apr 2009 23:41:02 +0000</pubDate>
		<dc:creator>Mike Wilcox</dc:creator>
				<category><![CDATA[ajax]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[Cometd]]></category>
		<category><![CDATA[Dojo]]></category>
		<category><![CDATA[Dojo Grid]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[Persevere]]></category>
		<category><![CDATA[Training]]></category>
		<category><![CDATA[Vector Graphics]]></category>
		<category><![CDATA[BorderContainer]]></category>
		<category><![CDATA[DataChart]]></category>
		<category><![CDATA[Stocker]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/2009/04/01/stocker-advanced-dojo-made-easy/</guid>
		<description><![CDATA[<p>SitePen is excited to announce Stocker, which demonstrates some of the more advanced capabilities of Dojo, including the newly released DataChart, the DataGrid, Data Store, Comet, Persevere, and BorderContainer. SitePen is also offering a one-day workshop where you will learn how to create Stocker yourself, but I&#8217;m here to give you a sneak peak of [...]</p><p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></description>
				<content:encoded><![CDATA[<p>SitePen is excited to announce <a href="http://persevere.sitepen.com/stocker.html">Stocker</a>, which demonstrates some of the more advanced capabilities of Dojo, including the newly released DataChart, the DataGrid, Data Store, Comet, Persevere, and BorderContainer. SitePen is also offering a one-day workshop where you will learn how to create Stocker yourself, but I&#8217;m here to give you a sneak peak of what Stocker is and how it works.</p>
<p>Stocker uses these technologies to emulate a stock monitoring application. We&#8217;re using made up data, but that&#8217;s actually more interesting. The Persevere server generates new stock items at certain intervals, and then pushes them to the browser with Comet. Then the Data Store updates its items and triggers an <code>onSet</code> notification. The DataGrid and DataChart are both connected to the same store, and are listening to that event. They then update their displays and show the stock items and their latest data.</p>
<p><img src='http://www.sitepen.com/blog/wp-content/uploads/2009/03/stocker.jpg' alt='Stocker' /></p>
<p><span id="more-704"></span></p>
<h2>Persevere</h2>
<p><a href="http://www.sitepen.com/labs/persevere.php/">Persevere</a>, which we chose to use inside the robust Jetty web server, allows us to quickly develop a data-driven web application that can directly interface with Dojo, without having to setup a relational database and create Ajax request handlers. It&#8217;s similar to Jaxer, in that it is a rich interactive server-side JavaScript environment (though Persevere uses Rhino), and is accessible via JSON-RPC, meaning Persevere is great for pure Ajax front-ends. SitePen&#8217;s Kris Zyp has a <a href="http://www.sitepen.com/blog/category/persevere/">large number of articles explaining how Persevere works</a>. </p>
<p>Persevere uses JSON Schema for defining the structure of class instances. Stocker uses one class schema definition that looks like this:</p>
<pre lang="JavaScript">
"name":"Stock",
"extends":"Object",
"schema":{
	"prototype":{},
	"instances":{"$ref":"../Stock/"},
	"extends":{"$ref":"../Class/Object"},
	"go":function(amount){
		startUpdateStock(amount);
	}
}
</pre>
<p>As you can see, you can even include methods in the schema, which can be used for a variety of things. The method <code>go()</code> shown here calls the server-side method <code>startUpdateStock()</code>. You can access this method from the command-line through this static class:</p>
<pre lang="bash">
JS> Stock.go();
</pre>
<p>In the server-side code, we start with a set of simple objects on which we base the Stock data. An example of one such object looks like this:</p>
<pre lang="JavaScript">
{ symbol:"ANDT", name:"Anduct", price:3.13 }
</pre>
<p><em>Note: Stocker uses more properties than this, but it is edited for clarity.</em></p>
<p>When <code>startUpdateStock()</code> is fired the first time, these objects are read in, randomized, and then saved as a Stock instance. When saved, the instance is written to a table and persisted. Basically it works like this: think of <em>Stock</em> as your SQL table, and each <em>instance</em> as a row of data. The columns in the table are represented by the <em>properties</em> that you see in the object above, such as symbol or price. And all you have to do to write to this table is:</p>
<pre lang="JavaScript">
new Stock( { symbol:"ANDT", name:"Anduct", price:3.13 } );
</pre>
<p>And modifying the data is just as easy. We loop through all of the instances in the Stock class (or table) and change the properties of the object. Persevere even automatically commits the changes for you, so this is all you need to do:</p>
<pre lang="JavaScript">
Stock.instances.forEach(function(instance){
	var m = randomizeStockData(instance);
	for(var nm in m){
		instance[nm] = m[nm];
	}
});
</pre>
<p>Notice we were able to use <code>forEach</code> on the instance array. We&#8217;re able to use all the functionality of <a href="https://developer.mozilla.org/en/New_in_JavaScript_1.7">Mozilla JavaScript 1.7</a>, like array functions or getters and setters, and don&#8217;t have to worry about cross-browser issues when writing server-side JavaScript in Persevere.</p>
<h2>Comet</h2>
<p>In Stocker, we created an arbitrary amount of six Stock instances. Once they are created, the client-side can now fetch them and access their properties using the <code>dojox.data.PersevereStore</code>. Of all the data stores available in Dojo, the PersevereStore is my favorite. You pretty much declare your store with a pointer to your class, do your fetch, and you&#8217;re done:</p>
<pre lang="JavaScript">
var store = new dojox.data.PersevereStore({target:"/Stock/"});
store.fetch({query:"[?symbol='*']", onComplete: function(_items){
	console.log("fetched:", items)
}});
</pre>
<p>PersevereStore provides you with a connection to the server via <a href="http://cometd.org/">Comet</a>. When we randomized our stock data on the Persevere server, this committed the change to the database. These changes are then pushed to the browser. You can listen for these changes in the <code>onSet</code> event of the PersevereStore:</p>
<pre lang="JavaScript">
dojo.connect(store, "onSet", function(data){
	console.log("onSet:", data);
});
</pre>
<h2>DataGrid</h2>
<p>Now it&#8217;s time to start wiring up the user interface, and believe it or not, things get easier here. The <a href="http://www.sitepen.com/blog/category/dojo-grid/">DataGrid</a> is largely the work of <a href="http://www.sitepen.com/blog/author/bforbes/">Bryan Forbes</a> and Nathan Toone, and is a first class user interface component. We started with the HTML structure that matched the properties we wanted to display from our Stock instances:</p>
<pre lang="html4strict">
<table dojoType="dojox.grid.DataGrid" >
    <thead>
        <tr>
            <th field="name">Stock Name</th>
            <th field="symbol">Symbol</th>
            <th field="price">Price</th>
        </tr>
    </thead>
</table>
</pre>
<p>You could also add a store and fetch attribute, but we opted to hook this up within the code:</p>
<pre lang="JavaScript">
dojo.addOnLoad(function(){
	grid.setStore(store, "[?symbol='*']");
});
</pre>
<p>The DataGrid has a built in fetch which grabs the current stock instances from Persevere, and then updates the items when the store&#8217;s onSet event is fired.</p>
<p>We did some CSS styling so the Grid would match our Stocker theme, and we were done with the Grid!</p>
<h2>DataChart</h2>
<p>The DataChart is brand new for Dojo 1.3, was created by yours truly, and was built specifically for Stocker, as it was obvious that charting was missing the ease of implementation that DataGrid provides. DojoX has an amazing vector graphics charting system written mainly by <a href="http://www.sitepen.com/blog/author/elazutkin/">Eugene Lazutkin</a>. It has a rich API that allows for maximum customization. However, DojoX charts didn&#8217;t support data stores, and while heavy customization is good in some cases, it can also create a barrier of entry for new developers. DataChart provides that interface between the two, all while supporting Dojo Data. I did a <a href="http://www.sitepen.com/blog/2009/03/30/introducing-dojox-datachart/">full write-up of DataChart</a> in a previous post. The intent was to make DataChart as easy to setup as the DataGrid:</p>
<pre lang="html4strict">
<div id="chartNode" style="width: 600px; height: 400px;"></div>
</pre>
<pre lang="JavaScript">
chart = new dojox.charting.DataChart("lines", chartDefault.chart);
chart.setStore(store, "[?symbol='*']", "price");
</pre>
<p>There is also some custom code that places chart legends inline with their respective items in the Grid. There&#8217;s also some code that handles switching between some of the chart types (just to be fancy). But other than that, we were done with charts!</p>
<h2>BorderContainer</h2>
<p>To get the BorderContainer to work for you, you have to understand that it supports subsets of two different designs, <em>headline</em> or <em>sidebar</em>. If you want the sidebar pane to extend from the top of the layout to the bottom, you&#8217;d naturally use <em>sidebar</em>. If you want the header and footer to extend the entire width, you use <em>headline</em>. Within either layout you have five regions: <em>top, bottom, left, right, and center</em>. The center pane stretches to fit, so you set the widths or heights of all panes but that one. Each region can either be a ContentPane or another BorderContainer. Stocker is slightly more complicated than standard layouts allow, so we use a nested BorderContainer.</p>
<p>What follows is the structure of the Stocker layout. For readability, dojoType is type, BorderContainer is BC and ContentPane is CP.  Stocker uses the <em>headline</em> design which is the default, so it need not be not set. Its center pane is another BorderContainer with a <em>top</em> and <em>center</em>.</p>
<pre lang="html4strict">
<div type="BC" gutters="false">                                     
    <div type="CP" region="top" splitter="false">
        Header
    </div>
    <div type="CP" gutters="true" region="left">
        Sidebar
    </div>
    <div type="BC"  gutters="false" region="center" liveSplitters="true">
        <div id="gridPane" type="CP" region="top" splitter="true">
            Grid
        </div>
        <div type="CP" region="center">
            Chart
        </div>
    </div>
    <div type="CP" region="bottom">
        Footer
    </div>
</div>
</pre>
<p>All children of a BorderContainer have an attribute region, which is the location in the design. BorderContainer&#8217;s have two other attributes: <code>liveSplitters</code> and <code>gutters</code>. Setting <code>gutters</code> to true puts a margin around it. The Stocker margins are handled in the CSS so these are set to false. The param <code>liveSplitters</code> indicates that one or more of the children will be resizable. A resizable pane acts much like the framesets of yesteryear, that had dividers between them that you could grab and drag to resize the frames.</p>
<p>Therefore, child panes can have the attribute <code>splitter=true</code>, which allows the user to resize it. It&#8217;s not obvious which child panes should get this attribute, since the splitter is shared amongst two panes. The trick to knowing is that the center pane, since it&#8217;s always stretchy, never gets this attribute&mdash;it is always applied to the pane that shares the splitter with it. </p>
<p>The DataGrid and DataChart were inserted in their proper ContentPane containers, the buttons for chart switching were placed in the sidebar, and the header and footer content was implemented. We launched the Persevere server, opened Stocker in our browser and watched the updates!</p>
<h2>Conclusion</h2>
<p><a href="http://persevere.sitepen.com/stocker.html">Stocker</a> was created to show the power of Dojo and some of it&#8217;s more advanced components, and how easily they can be implemented in your site or web application.  We&#8217;ll also be talking about Stocker and Dojo in a number of <a href="/events/">upcoming conference talks</a> this year.  If you&#8217;re interested in learning more about Stocker and how to put it together, <a href="/contact/">drop us a line</a>!</p>
<p>SitePen has workshops planned in various locations around world, and we&#8217;d love it if you could join us.  You&#8217;ll learn everything you need to build Stocker and more at the following one-day Intro to Dojo, Charts, Grids, and Comet workshops:</p>
<ul>
<li><a href="http://dojosydneyworkshop.eventbrite.com/">Sydney, Australia, April 23, 2009</a></li>
<li><a href="http://skillsmatter.com/event/ajax-ria/progressive-web-tutorials">London, England, May 13, 2009</a></li>
<li>Stockholm, Sweden, May 26, 2009</a></li>
<li>Milan, Italy, June 8, 2009</li>
<li>Paris, France, June 10, 2009</li>
</ul>
<p>Or, join us for a special <a href="http://www.sitepen.com/blog/2009/03/20/munich-dojo-workshop/">two-day Dojo Workshop in Munich, Germany, May 7-8, 2009</a> with the uxebu team.</p>
<p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2009/04/01/stocker-advanced-dojo-made-easy/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>A Tale of Two Panels</title>
		<link>http://www.sitepen.com/blog/2009/02/25/a-tale-of-two-panels/</link>
		<comments>http://www.sitepen.com/blog/2009/02/25/a-tale-of-two-panels/#comments</comments>
		<pubDate>Wed, 25 Feb 2009 08:02:24 +0000</pubDate>
		<dc:creator>Dylan Schiemann</dc:creator>
				<category><![CDATA[ajax]]></category>
		<category><![CDATA[Cometd]]></category>
		<category><![CDATA[Dojo]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/2009/02/25/a-tale-of-two-panels/</guid>
		<description><![CDATA[<p>Silicon Valley Web Builder has a series of monthly panels on topics of interest to web application developers. I had the opportunity to attend a pair of events recently, once as a speaker, once as an attendee, and the contrast between the two was intriguing. The first panel in November was focused on Comet, while [...]</p><p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></description>
				<content:encoded><![CDATA[<p><a href="http://www.svwebbuilder.com/">Silicon Valley Web Builder</a> has a series of monthly panels on topics of interest to web application developers.  I had the opportunity to attend a pair of events recently, once as a speaker, once as an attendee, and the contrast between the two was intriguing.  The first panel in November was focused on Comet, while the most recent panel was a comparison of Ajax toolkits.</p>
<p>As an attendee of the Comet panel, I found the discussion interesting, but was a bit disheartening and negative.  In retrospect, the negative tone reflects the pain and disappointment Comet engineers face in trying to come up with the perfect solution for low-latency data transit across the wire.  Michael Carter was the lone optimist, describing the work he has done to date with Orbited, and what the HTML5 WebSocket promises to bring us in the near future.  The other panelists were not as optimistic, having been burned by specifications not adopted and the ongoing frustrations with HTTP connection limits, proxy configurations, flaky internet connections, and more&mdash;all of which prevent many of the better approaches to Comet being viable.</p>
<p><span id="more-657"></span></p>
<p>There was also disagreement around the name Comet, what it encompasses, and whether it should be called WebSocket, Comet, Reverse Ajax, Ajax Push, etc.  Alex and I think of all of this as Comet, whereas some panelists believe that WebSocket is not part of the Comet moniker, which is silly.  One of the main reasons that Ajax took off is that people just agreed on the name (though I personally hated it for months), whereas in the Comet space there&#8217;s disagreement on just about everything, from the name to protocols to techniques.  In my opinion, a race to standardize and simplify are essential if this fledgling set of techniques is to become approachable to a wider range of developers.  An out of the box implementation with Google App Engine wouldn&#8217;t hurt either!</p>
<p>I&#8217;m optimistic because the work of Kris Zyp, Michael Carter, Andrew Betts, Greg Wilkins, Alessandro Alinone, and others is getting us closer to having ideal Comet solutions, but we have a lot of work to do before Comet is as approachable as Ajax.</p>
<p>The second panel, by contrast, was focused on Ajax toolkits. Dojo was represented by yours truly, with great representation by committers to GWT (Fred Sauer), jQuery (Yehuda Katz), MooTools (Tom Occhino), and YUI (Adam Moore), with Michael Carter moderating the panel.  In contrast with the Comet panel, we had a lot of optimism and laughs, the result of several years of seeing very impressive advances in what&#8217;s possible in the browser.  It&#8217;s been a great adventure from pre-Ajax to where we are today, and it showed with the sheer enthusiasm by everyone on the panel.  We had our differences of opinion and some very funny moments, but what I really took away from this panel is that we&#8217;re all learning from each other, have similar goals in helping developers create amazing user experiences, and that there is tremendous interest in the great work being done in creating Ajax toolkits.</p>
<p>Comet toolkit developers of today remind me of DHTML toolkit developers in the pre-Ajax days: a bunch of frustrated, grizzled engineers that wanted to do more, but didn&#8217;t yet have enough code, tools, browser support, and/or momentum to get where they needed to go.  Comet techniques are widely adopted in applications like the London Paper, Meebo, Gmail Chat, and Facebook Chat, as well as behind corporate firewalls in advanced financial applications, but the approach has not yet hit the developer tipping point like Ajax.</p>
<p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2009/02/25/a-tale-of-two-panels/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Tech of SitePen Support</title>
		<link>http://www.sitepen.com/blog/2008/08/19/the-tech-of-sitepen-support/</link>
		<comments>http://www.sitepen.com/blog/2008/08/19/the-tech-of-sitepen-support/#comments</comments>
		<pubDate>Tue, 19 Aug 2008 07:01:12 +0000</pubDate>
		<dc:creator>Kevin Dangoor</dc:creator>
				<category><![CDATA[ajax]]></category>
		<category><![CDATA[Cometd]]></category>
		<category><![CDATA[Dojo]]></category>
		<category><![CDATA[DWR]]></category>
		<category><![CDATA[Support]]></category>
		<category><![CDATA[helpspot]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/2008/08/19/the-tech-of-sitepen-support/</guid>
		<description><![CDATA[<p>SitePen&#8217;s Support service is built using a variety of interesting techniques and technologies. Read on to see how we built a system that treats the web browser as a real client tier and bridges the worlds of JavaScript, Python and PHP seamlessly to provide a great experience for our customers. Starting with the User Even [...]</p><p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></description>
				<content:encoded><![CDATA[<p><a href="http://www.sitepen.com/">SitePen&#8217;s</a> <a href="http://sitepen.com/services/support.php">Support</a> service is built using a variety of interesting techniques and technologies. Read on to see how we built a system that treats the web browser as a real client tier and bridges the worlds of JavaScript, Python and PHP seamlessly to provide a great experience for our customers.</p>
<p><span id="more-448"></span></p>
<h2>Starting with the User</h2>
<p>Even though this article is about the technology used to implement SitePen&#8217;s Support service, it doesn&#8217;t make any sense to talk about technology without talking about the user experience. The technology is there to <em>do</em> something. But, what?</p>
<p>With the <a href="http://sitepen.com/services/support.php">SitePen Support</a> service we provide support for the <a href="http://www.dojotoolkit.org/">Dojo Toolkit</a>, <a href="http://directwebremoting.org/">DWR</a> and <a href="http://cometd.com/">Cometd</a> open source projects. We&#8217;re out to provide customers with the help they need when they need it. At the highest level, we needed to:</p>
<ol>
<li>Collect support requests from our customers</li>
<li>Act on them</li>
<li>Keep the customer informed</li>
<li>Follow along with the terms of our support contracts</li>
</ol>
<p>Without those things, we wouldn&#8217;t have a service at all. In addition, there are other requirements for making it the kind of service we&#8217;d be proud of:</p>
<ol>
<li>The customer user interface should be very responsive</li>
<li>The user interface should be less like a content-oriented web site and more like an application</li>
<li>People in a company should be able to work together easily (data should be shared)</li>
<li>Customers should be able to bring themselves up-to-date on what&#8217;s happening in their account at any time</li>
<li>Email is still a super convenient user interface</li>
</ol>
<p>Note that our goals were all about providing a great support service, and not about creating software. If there was off-the-shelf software that would do all of the above for us, at the level of quality we expected, we would certainly have used it. But, there wasn&#8217;t. Which brings us to&#8230;</p>
<h2>The Tech of SitePen Support</h2>
<p>To realize those goals for the service, we employed a bunch of different tools and techniques:</p>
<ul>
<li>Dojo runs the client-side</li>
<li>The client drives the whole interaction</li>
<li>The browser speaks JSON-RPC with the server for most operations</li>
<li>The server is built on Python&#8217;s WSGI standard</li>
<li>Client-driven apps have very little &#8220;obscurity&#8221; to try to hide behind, so we needed to be sure we followed best practices</li>
<li>Off-the-shelf help desk software (<a href="http://www.userscape.com/products/helpspot/">HelpSpot</a>) handles part of the work for us</li>
</ul>
<h2>The Client-side Runs the App</h2>
<p>A typical web app today looks something like this:</p>
<p align="center"><img src='http://www.sitepen.com/blog/wp-content/uploads/2008/08/traditional.png' alt='Traditional Web 2.0 App Development' /><br />
Typical modern web app model</p>
<p><em>Most</em> interactions are decided by the server. The client makes a request, the server gathers data and uses some sort of template engine to format that data and present it. That cycle is repeated over and over again, with the server always deciding what comes next and how the next bit will be displayed. Many apps today add some Ajax to that (that little JavaScript box at the top of the diagram), but very often the formatting of data is handled by the server and the client just uses .innerHTML to drop the fresh content in place.</p>
<p>For our support application, the model looks more like:</p>
<p align="center"><img src='http://www.sitepen.com/blog/wp-content/uploads/2008/08/richclientapp.png' alt='Rich Client Application Model' /><br />
One model for rich client web apps</p>
<p>With this setup, the server is not responsible for the presentation layer <em>at all</em>. The server sends up static HTML files, and the browser does all of the work in displaying the data to the user. This approach was the topic of my <a href="http://us.pycon.org/">PyCon</a> 2008 talk: <a href="http://www.sitepen.com/blog/2008/03/31/rich-ui-webapps-with-turbogears-2-and-dojo-screencast/">Rich UI Webapps with TurboGears 2 and Dojo</a>.</p>
<p>If plain HTML is like the modern day equivalent of a <a href="http://en.wikipedia.org/wiki/Computer_terminal">green screen terminal</a>, this design approach helps make your browser usable as a real <a href="http://en.wikipedia.org/wiki/Thin_client#Advantages_of__thick_clients">thick client</a>.</p>
<h2>Dojo Runs the Client</h2>
<p>The entire user interaction in the Support application is driven by the JavaScript client-side code. Dojo is a natural fit for this style of working, with its built in <a href="http://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/modules-and-namespaces">module system</a>, <a href="http://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/ajax-transports/remote-procedure-call-rpc">RPC support</a>, <a href="http://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/data-retrieval-dojo-data-0">dojo.data</a> interfaces and powerful <a href="http://dojotoolkit.org/book/dojo-book-0-9/part-2-dijit-0">Dijits</a>. </p>
<p>We set up a very simple &#8220;PageModule&#8221; system where we use Dojo&#8217;s dynamic loading to load a new JavaScript module from the server and then call &#8220;initPage&#8221; on the code in that module. That will load up any HTML it needs to display and initialize everything for the user. A simple call to spsupport.core.loadContent is all we need to do to move the user onto the next piece of functionality:</p>
<pre lang="javascript">
loadContent: function(moduleName, params) {
	// Loads a new content section (if necessary).
	// A content section is defined by a Dojo module that
	// has an "initPage" function in it. The module is loaded
	// if need be and then initPage is called.
	
	if(spsupport.core.currentPage &#038;&#038; spsupport.core.currentPage.cleanupPage){
		spsupport.core.currentPage.cleanupPage();
	}
	
	var module = dojo.getObject(moduleName);
	
	spsupport.core.currentPage = module;
	
	if(module &#038;&#038; module.initPage){
		// initPage is like _Widget startup(), though you can safely
		// call it often. each "content" resource should implement it's
		// own _started mechanism in initPage, and treat initPage() as
		// if it were a "selectChild()" call
		 module.initPage(params)
	}else{
		var thedot	= moduleName.lastIndexOf(".");
		var packageName = moduleName.substring(0, thedot);
		var moduleRemainder = moduleName.substring(thedot + 1) + ".js";
		dojo.xhrGet({
			url: dojo.moduleUrl(packageName, moduleRemainder).uri,
			preventCache: true,
			handleAs:"javascript",
			load: function(js) {	
				if(js &#038;&#038; js.initPage){ js.initPage(params); }
			}
		})
	}
},
</pre>
<p>With this kind of modular architecture, we could have a <em>giant</em> application in which everything gets loaded on demand. Combining this setup with Dojo&#8217;s build system gives us quite a bit of control over exactly when things load, allowing us to balance initial load time with interactive responsiveness. Any significant &#8220;single page&#8221; application will need this. The Support application is by no measure a &#8220;giant&#8221; application, but using good application design techniques like this allows us to add whatever features we need to the application without impacting its load time or responsiveness.</p>
<h2>URL Dispatch: Not Just for Servers Anymore</h2>
<div style="float: right; width: 128px; margin: 1em"><img src='http://www.sitepen.com/blog/wp-content/uploads/2008/08/support_login.thumbnail.jpg' alt='Support Login' /><br />
<img src='http://www.sitepen.com/blog/wp-content/uploads/2008/08/support_signup.thumbnail.jpg' alt='Support Signup' /><br />The page content is decided by the JavaScript in the client, not by the server.
</div>
<p>URL dispatch is one of the core features of a server-side web framework. It turns out that putting the client in charge moved some of the burden of URL dispatch to the client! When you hit the front page of the Support site, the JavaScript figures out where you really want to go:</p>
<ul>
<li>/: send the user over to the support page on SitePen&#8217;s main site</li>
<li>/?login: give the user a chance to login</li>
<li>/?signup-(someplan): give the user a signup page with a plan selected</li>
</ul>
<p>When working with server-side frameworks, you get used to URLs being divided up by slashes and everything after the ? denoting extra query parameters. With the client in control, the slashes tell the server what static file to serve up, and everything after the ? tells the client what to display. Given that we only have three different possibilities there, we didn&#8217;t have to get fancy with our URL dispatch. You certainly could write a client-side framework that has many of the <a href="http://code.google.com/p/trimpath/wiki/TrimJunction">same features you get from a server-side framework</a>, if that&#8217;s what your application needs. The support application only needed to interpret a very small number of URLs.</p>
<h2>Full-stack Framework? Not Anymore!</h2>
<p>Our support application doesn&#8217;t use server-side templates for the user interface and doesn&#8217;t really do URL dispatch. The &#8220;full-stack&#8221; web frameworks in use today (Rails, Django, TurboGears, CakePHP, Grails, to name a few) are basically defined by their URL dispatch, templates and database support. Given that we didn&#8217;t need two of the three of those, we could go a lot simpler on the server than a full-stack framework.</p>
<p>Our server-side code is written in Python. Many components and libraries are now built around the <a href="http://www.python.org/dev/peps/pep-0333/">Web Server Gateway Interface (WSGI) specification</a>, making it easier than ever to put a collection of webapp components together. WSGI works well enough to have spawned <a href="http://smarkets.files.wordpress.com/2008/05/smarkets-web-framework.pdf">a version in Erlang</a>.</p>
<p>In our main web stack, we gathered up the following components:</p>
<ul>
<li><a href="http://www.cherrypy.org/">CherryPy&#8217;s</a> WSGI server, used both in development on its own and in production behind Apache</li>
<li>Luke Arno&#8217;s <a href="http://lukearno.com/projects/static/">Static</a> WSGI app, which serves up static files. This is used primarily in development, and Apache serves up our static files in production</li>
<li>Mikeal Rogers&#8217; <a href="http://code.google.com/p/wsgi-jsonrpc/">wsgi_jsonrpc</a> for responding to the RPC requests from the client</li>
<li>Ian Bicking&#8217;s <a href="http://pythonpaste.org/webob/">WebOb</a> for the small number of dynamic operations that couldn&#8217;t be JSON-RPC</li>
<li>Mike Bayer&#8217;s <a href="http://sqlalchemy.org/">SQLAlchemy</a> for database mapping</li>
</ul>
<h2>JSON-RPC</h2>
<p>In the past, I&#8217;ve often used plain old HTTP requests returning JSON results as a convenient and simple mechanism for requesting data and actions on the server. In fact, that was the approach I took in my PyCon talk. For the Support project, we decided to use <a href="http://json-rpc.org/">JSON-RPC</a> instead because it&#8217;s a little bit cleaner. In Dojo, making a JSON-RPC request is just like making a function call that returns a <a href="http://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/miscellaneous/communication-between-threads-do">Deferred</a>. So, the syntax for using our server-side API was very straightforward. Even better, parameters and return values automatically came across as the correct types (strings, numbers, arrays, etc). The server-side is also simplified, because it does not need to do much in the way of URL dispatch (JSON-RPC POSTs to a single URL) and the server doesn&#8217;t need to worry about converting incoming values from strings.</p>
<p>wsgi_jsonrpc is quite easy to work with. We subclassed it to handle our authentication easily and added a neat bit where making a GET request to the JSON-RPC URL would return the service description. That little change made it easy to wire up Dojo on the client:</p>
<pre lang="javascript">
dojo.xhrGet({
	url: "/jsonrpc",
	handleAs: 'json',
	load: function(response){
		spsupport.service = new dojo.rpc.JsonService({
			serviceType: 'JSON-RPC',
			serviceURL: "/jsonrpc",
			timeout: 6000,
			methods : response['procs']
		});		 
	},
	sync:true
});
</pre>
<p>This small snippet will synchronously load the RPC service description. It works synchronously because the UI can&#8217;t do much until it can make RPC calls for data. Then, it pulls the function names out of the response to create the JsonService. From that point onward, we just make calls to spsupport.service.<i>function_name</i> whenever we need to call the server.</p>
<p>Each available RPC call is simply a Python function in a module that has some extra metadata attached to it. For example, the request_details function is used to look up a support request by ID and return the detailed information about the request:</p>
<pre lang="python">
@auth
@params(dict(name='id', type='str'))
@returns('obj')
def request_details(user, id):
    """Returns the detailed information for a request.
    
    Params:
    
    * id: the request ID
    
    Returns:
    
    * object with the detailed information
    """
</pre>
<p>The @returns decorator is used to mark the function as one that should be available via JSON-RPC, and to also make note of the return type. The @params decorator, combined with the return type listed in @returns, are used when generating the service description for the client. @auth tells our JSONRPCDispatcher subclass that this function requires authentication. Whenever the @auth decorator is present, the first parameter passed to the function is always the user object. The function itself can then perform additional checks. For example, request_details makes sure that the request is from the same organization as the user.</p>
<p>This design makes it very easy for us to write automated tests for the server side code. I&#8217;m personally a fan of test driven development in general, and in the next section we&#8217;ll see why automated tests are particularly important for this kind of application.</p>
<h2>All Out in the Open</h2>
<p>When you provide a rich user interface, particularly using Open Web technologies, you cannot count on <a href="http://en.wikipedia.org/wiki/Security_through_obscurity">security through obscurity</a>. You have to assume that people will study your code and learn about all of your &#8220;hidden&#8221; URLs that make up sensitive APIs. You would never guess that Gmail doesn&#8217;t have a public API, given the number of add-ons people have made for it.</p>
<p>Never trust the client code and requests coming from the client. When creating new, authenticated APIs on the server, the <em>first</em> unit test I write is one that ensures that unauthorized users are given the boot. When working with WSGI and WebOb, writing tests that can run without a server is quite easy:</p>
<pre lang="python">
def test_bad_credentials():
    req = Request.blank('/lookup')
    req.headers['Authorization'] = 'Basic HiThere=='
    res = req.get_response(requests.lookup_customer)
    print res
    assert res.status == '401 Unauthorized'
</pre>
<p>webob.Request.blank gives you a new Request object that is properly populated to look like a real request. You can then make changes from there to set up your test conditions. In the example above, I&#8217;m passing along bad authentication information. At the end, I assert that the result of sending bad authentication information is the expected 401 response.</p>
<p>As easy as testing is using WebOb, unit testing the JSON-RPC calls is even more straightforward. We just call the function directly as we would any Python function that we are unit testing. This kind of application setup makes server-side testing a breeze.</p>
<p>Of course, there&#8217;s a lot more work required to ensure that you&#8217;re handling data securely than just authenticating the users. We confirm that the user is authorized to access the data they are trying to access (with unit tests, of course). Using SQLAlchemy, we are not vulnerable to SQL injection attacks. We also run all of the requests over SSL to make sure that customer data is not grabbed off of possibly insecure networks.</p>
<h2>HelpSpot: the Extra Layer in our Stack</h2>
<p>Once a user is logged in, they&#8217;re taken to the /dashboard/ page where they can review their requests and account information and create new requests. The support dashboard is built around everything I&#8217;ve discussed so far. Each &#8220;page&#8221; in the dashboard is a separate module loaded via the loadContent call, and those modules make JSON-RPC requests to retrieve and update data on the server.</p>
<p align="center"><img src='http://www.sitepen.com/blog/wp-content/uploads/2008/08/supportdashboard.jpg' alt='The Support Dashboard' /><br />When you first log in, you can see the recent support request activity.</p>
<p align="center"><img src='http://www.sitepen.com/blog/wp-content/uploads/2008/08/accountinformation.jpg' alt='Account information' /><br />All of the details of your current support plan are available on one screen.</p>
<p>The server-side software that we wrote is responsible for keeping track of support plans and gathering up support requests for a given organization so that they can be displayed together. The support requests themselves with their complete histories are all tracked by HelpSpot. Within SitePen, we use HelpSpot&#8217;s user interface to update requests, and HelpSpot manages all email interaction. This saved us a good deal of implementation work.</p>
<p>HelpSpot is written in PHP, so we can&#8217;t directly call its functions from our Python-based server. One reason we chose HelpSpot is that it offers a solid web API of its own. We make simple HTTP requests to HelpSpot and it returns JSON formatted data. All of those requests are between our support application and HelpSpot. There are some instances where we needed to look up or update data in bulk, and HelpSpot did not have APIs specifically for that. Luckily, HelpSpot&#8217;s database schema is nicely designed and easy to understand, so there are instances where we also collect data directly from HelpSpot&#8217;s database.</p>
<h2>Putting it all together</h2>
<p>Bringing new developers up to speed on our support project is simple, because we use <a href="http://pypi.python.org/pypi/zc.buildout">zc.buildout</a>. zc.buildout creates a sandbox on the developer&#8217;s system with all of the pieces they need to work on the project.</p>
<p>Once we&#8217;re ready to deploy, we use a <a href="http://www.blueskyonmars.com/projects/paver/">Paver</a> pavement file to describe how to package up the software. Our pavement runs the <a href="http://dojotoolkit.org/book/dojo-book-0-9/part-4-meta-dojo/package-system-and-custom-builds">Dojo build system</a> to combine and shrink the JavaScript files and then bundles everything up into an <a href="http://peak.telecommunity.com/DevCenter/PythonEggs">egg file</a>. The pavement also includes a task that will upload the egg to the server. Using zc.buildout also works great at deployment time, because we just have to run &#8220;bin/buildout&#8221; in the server&#8217;s deployment directory.</p>
<h2>Creating the Desired User Experience</h2>
<p>I think that the tools and techniques we used in building our support application were nifty and different from how most people are building webapps today. Our approach was all driven by a desire to provide a great user experience that meets our four original goals:</p>
<ol>
<li>Collect up support requests from our customers</li>
<li>Act on them</li>
<li>Keep the customer informed</li>
<li>Follow along with the terms of our support contracts</li>
</ol>
<p>The right tools helped us to reach these goals without a giant development budget.</p>
<p>Next month, I&#8217;ll be writing about the processes and tools we use to manage the support service within SitePen and ensure that we&#8217;re always on top of our customers&#8217; needs.</p>
<p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2008/08/19/the-tech-of-sitepen-support/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Client/Server Model on the Web</title>
		<link>http://www.sitepen.com/blog/2008/07/18/clientserver-model-on-the-web/</link>
		<comments>http://www.sitepen.com/blog/2008/07/18/clientserver-model-on-the-web/#comments</comments>
		<pubDate>Fri, 18 Jul 2008 14:48:55 +0000</pubDate>
		<dc:creator>Kris Zyp</dc:creator>
				<category><![CDATA[ajax]]></category>
		<category><![CDATA[Bayeux]]></category>
		<category><![CDATA[Cometd]]></category>
		<category><![CDATA[Dojo]]></category>
		<category><![CDATA[DWR]]></category>
		<category><![CDATA[client]]></category>
		<category><![CDATA[Persevere]]></category>
		<category><![CDATA[server]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/2008/07/18/clientserver-model-on-the-web/</guid>
		<description><![CDATA[<p>Prior to the popularity of the web, client/server applications often involved the creation of native applications which were deployed to clients. In this model, developers had a great deal of freedom in determining which parts of the entire client/server application would be in the client and which in the server. Consequently, very mature models for [...]</p><p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></description>
				<content:encoded><![CDATA[<p>Prior to the popularity of the web, client/server applications often involved the creation of native applications which were deployed to clients. In this model, developers had a great deal of freedom in determining which parts of the entire client/server application would be in the client and which in the server. Consequently, very mature models for client/server development emerged, and often well designed optimal distribution of processing and logic could be achieved. When the web took off, the client was no longer a viable application platform, it was really more of a document viewer. Consequently the user interface logic existed almost entirely on the server. However, the web has matured substantially and has proven itself to be a reasonable application platform. We can once again start utilizing more efficient and well-structured client/server model design. There are certainly still technical issues, but we are in a position to better to build true client/server applications now.</p>
<p><span id="more-301"></span></p>
<p>The client/server model can be categorized into <a href="http://www.faqs.org/faqs/client-server-faq/">three parts</a>:</p>
<ul>
<li>User Interface</li>
<li>Business or Application Logic</li>
<li>Data Management</li>
</ul>
<p>Traditional web application development has distributed the implementation of the user interface across the network, with much of the user interface logic and code executed on the server (thin client, fat server). This has several key problems:<img src="http://www.sitepen.com/blog/wp-content/uploads/2008/06/clientserver.png" style="float: right" alt="clientserver.png" /></p>
<ul>
<li>Poor distribution of processing &#8211; With a large number of clients, doing all the processing on the server is inefficient.</li>
<li>High user response latency &#8211; Traditional web applications are not responsive enough. High quality user interaction is very sensitive to latency, and very fast response is essential.</li>
<li>Difficult programming model &#8211; Programming a user interface across client/server is simply difficult. When every interaction with a user must involves a request/response, user interface design with this model is complicated and error prone. The vast number of web frameworks for simplifying web development testifies to this inherent difficulty. Some have mitigated this difficulty to some degree.</li>
<li>Increased vector of attack &#8211; Unorganized mingling of user interface code with business code can increase security risks. If access rules are distributed across user interface code, as user interface code grows and evolves, new vectors of attack emerge. With mixed code, new user interface features can easily create new security holes.</li>
<li>Heavy state management on the servers &#8211; When client user interface state information is maintained by the server, this requires a significant increase in resource utilization as server side sessions must be maintained with potentially large object structures within them. Usually these resources can&#8217;t be released until a session times out, which is often 30 minutes after a user actually leaves the web site. This can reduce performance and scalability.</li>
<li>Offline Difficulties &#8211; Adding offline capabilities to a web application can be a tremendous project when user interface code is predominantly on the server. The user interface code must be ported to run on the client in offline situations.</li>
<li>Reduced opportunity for interoperability &#8211; When client/server communication is composed of transferring internal parts of the user interface to the browser, it can be very difficult to understand this communication and utilize it for other applications.</li>
</ul>
<p>With the massive move of development to the web, developers have frequently complained of the idiosyncrasies of different browsers and demanded more standards compliance. However, the new major shift in development is towards interconnectivity of different services and mashups. We will once again feel the pain of programming against differing APIs. However, we won&#8217;t have browser vendors to point our fingers at. This will be the fault of web developers for creating web applications with proprietary communication techniques.</p>
<p>Much of the Ajax movement has been related to the move of user interface code to the client. The maturing of the browser platform and the availability of HTTP client capabilities in the XMLHttpRequest object, have allowed much more comprehensive client side user interface implementations. However, with these new found capabilities, it is important to understand how to build client/server applications.</p>
<p>So how do you decide what code should run on the client and what should the run on the server? I have mentioned the problems with user interface code running on the server. Conversely, running business logic and/or data management on the client is simply not acceptable for security reasons. Therefore, quite simply, user interface code is best run on the browser, and application/business logic and data management is best run on the server side. We can take a valuable lesson from object oriented programming to guide this model. Good OO design involves creating objects that encapsulate most of their behavior and have a minimal surface area. It should be intuitive and easy to interact with a well designed object interface. Likewise, client and server interaction should be built on a well-designed interface. Designing for a modular reusable remote interface is often called service oriented architecture (SOA); data is communicated with a defined API, rather than incoherent chunks of user interface. A high quality client/server implementation should have a simple interface between the client and server. The client side user interface should encapsulate as much of the presentation and user interaction code as possible, and the server side code should encapsulate the security, behavior rules, and data interaction. Web applications should be a cleanly divided into two basic elements, the user interface and the web service, with a strong emphasis on minimal surface area between them.<img src="http://www.sitepen.com/blog/wp-content/uploads/2008/06/clientserver2.png" style="float: right" alt="clientserver2.png" /></p>
<p>An excellent litmus test for a good client/server model is how easy is it to create a new user interface for the same application. A well designed client/server model should have clearly defined web services such that a new user interface could easily be designed without having to modify server side application logic. A new client could easily connect to the web services and utilize them. Communication should be primarily composed of data, not portions of user interface. The advantages of a clean client/server model where user interface logic and code is delegated to the browser:</p>
<ul>
<li>Scalability &#8211; It is quite easy to observe the significant scalability advantage of client side processing. The more clients that use an application, the more client machines that are available, whereas the server processing capabilities remain constant (until you buy more servers).</li>
<li>Immediate user response &#8211; Client side code can immediately react to user input, rather than waiting for network transfers.</li>
<li>Organized programming model &#8211; The user interface is properly segmented from application business logic. Such a model provides a cleaner approach to security. When all requests go through user interface code, data can flow through various interfaces before security checks take place. This can make security analysis more complicated, with complex flows to analyze. On the other hand, with a clean web service interface, there is well-defined gateway for security to work on and security analysis is more straightforward, holes can be quickly found and corrected.</li>
<li>Client side state management &#8211; Maintaining transient session state information on the client reduces the memory load on the server. This also allows clients to leverage more RESTful interaction which can further improve scalability and caching opportunities.</li>
<li>Offline applications &#8211; If much of the code for an application is already built to run on the client, creating an offline version of the application will almost certainly be easier.</li>
<li>Interoperability &#8211; By using structured data with minimal APIs for interaction, it is much easier to connect additional consumers and producers to interact with existing systems.</li>
</ul>
<h3>Difficulties with the Client Server Model on the Web</h3>
<p>There are certainly difficulties with applying the client/server model to the web. Accessibility and search engine optimization can certainly be particular challenges with the web services approach. Handling these issues may suggest a hybrid approach to web applications, some user interface generation may be done on the server to create search engine accessible pages. However, having a central architectural approach based around a client/server model, with extensions for handling search engines may be a more solid and future oriented technique for many complex web applications.</p>
<h3>Our Efforts to Facilitate the Client Server Model</h3>
<p>SitePen is certainly not alone in working to facilitate client/server architecture. However, since I am familiar with the projects we help create, I did want to mention our approaches to the client/server model:</p>
<p><a href="http://directwebremoting.org/">DWR</a> &#8211; From inception, DWR has provided an excellent framework for building client side user interfaces that can easily connect with server side business logic. DWR was years ahead of its time in establishing a framework that encouraged good client/server modeling. DWR has a solid structure for interacting with Java business logic objects. DWR has continued to progress, providing means for bi-directional Comet based communication (Reverse Ajax), and is adding more interoperability capabilities as well.</p>
<p><a href="http://dojotoolkit.org">Dojo Toolkit</a> &#8211; It should be obvious that building a good client-side user interface can benefit from a good toolkit, and Dojo has long provided just that. However, Dojo is more than just a library and set of widgets. Dojo provides real tools for building client/server applications. Dojo RPC can provides tools for connecting to web services, and can even auto-generate <a href="http://www.sitepen.com/blog/2008/03/19/pluggable-web-services-with-smd/">services based on SMD definitions</a>. Dojo Data provides a powerful API for interacting with a data model. Dojo has lead the way with Comet technology, creating standards around browser based two-way communication. Recently we have built the <a href="http://www.sitepen.com/blog/2008/06/13/restful-json-dojo-data/">JsonRestStore</a> which allows one to connect to a REST web service and interact with it using the Dojo Data read and write API. This greatly simplifies the construction of user interfaces by simplifying the user interface-business logic interaction, and encouraging standards-based communication that can easily be used by others. Furthermore, Dojo provides comprehensive tools for robust data-driven applications; even templating can be done on the client instead of the server with <a href="http://dojotoolkit.org/book/dojo-book-0-9/part-5-dojox/dojox-dtl">Dojo&#8217;s DTL support</a>.</p>
<p>The benefits of using standards-based client/server communication has facilitated integration with server frameworks like <a href="http://devzone.zend.com/article/3545-Dojo-and-Zend-Framework-Partnership-Announcement">Zend</a>, <a href="http://www.sitepen.com/blog/2008/06/18/dojo-jabsorb/">jabsorb</a>, <a href="http://sitepen.com/labs/persevere.php">Persevere</a>, and interoperability with other frameworks will be coming soon.</p>
<p><a href="http://www.cometd.com/">Cometd</a> &#8211; Cometd provides real-time duplex communication between clients and servers. However, the distinguishing characteristic of the Cometd project is the focus on not only achieving Comet-style duplex communication, but doing so with an interoperable standard protocol, <a href="http://www.cometd.com/bayeux">Bayeux</a>. Comet uses a quintessential client/server approach. Any Cometd (Bayeux implementing) server can interact with any Cometd/Bayeux client. One can easily connect various different client implementations to a single server, by using the Bayeux standard.</p>
<p><a href="http://sitepen.com/labs/persevere.php">Persevere</a> &#8211; Persevere is a recently launched project, built with this service oriented client/server approach. Persevere is a web object database and application server with RESTful HTTP/JSON interfaces, allowing applications to quickly be built with a database backend that can be directly and securely accessed through Ajax. Persevere is focused on provided a comprehensive set of web services interaction capabilities through standard interoperable communication. Data can be accessed and modified with basic RESTful JSON interaction, clients can invoke methods on the server with simple JSON-RPC, and data can be queried with <a href="https://www.sitepen.com/blog/?p=409">JSONQuery/JSONPath</a>. With Dojo&#8217;s new REST data store, and SMD driven RPC services, Dojo clients can seamlessly build applications and interact with Persevere services using the Dojo APIs. Complex application logic can be added to the persisted objects in Persevere to facilitate building service oriented applications with a straightforward interface to the user interface code on the browser. Persevere is integrated with Rhino, so model and application logic can be written in JavaScript, providing a consistent language and environment for distributing client and server roles.</p>
<p>For more information about any of these open source projects, visit the <a href="http://sitepen.com/labs/">SitePen Labs</a></p>
<h2>Summary</h2>
<p>As the web platform matures, as applications evolve to use more interactive and rich interfaces, and as web services increasingly interact, architecting web applications with an intelligent client/server model will become increasingly important. A properly designed client/server model will provide a foundation for modular, adaptable, and interoperable applications equipped for future growth.</p>
<p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2008/07/18/clientserver-model-on-the-web/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Comet and Java</title>
		<link>http://www.sitepen.com/blog/2008/05/22/comet-and-java/</link>
		<comments>http://www.sitepen.com/blog/2008/05/22/comet-and-java/#comments</comments>
		<pubDate>Thu, 22 May 2008 13:04:29 +0000</pubDate>
		<dc:creator>Joe Walker</dc:creator>
				<category><![CDATA[Cometd]]></category>
		<category><![CDATA[DWR]]></category>
		<category><![CDATA[Open Source]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/2008/05/22/comet-and-java/</guid>
		<description><![CDATA[<p>One of the difficulties implementing Comet on Java is the lack of any acknowledgement in the current Servlet spec (v2.5) that any HTTP connection may be anything other than short-lived. Unlike many of the other components in the JavaEE stack, servlets are ubiquitous so we don&#39;t really have a choice to use an alternative. Servlet [...]</p><p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></description>
				<content:encoded><![CDATA[<p>One of the difficulties implementing Comet on Java is the lack of any acknowledgement in the current Servlet spec (v2.5) that any HTTP connection may be anything other than short-lived. Unlike many of the other components in the JavaEE stack, servlets are ubiquitous so we don&#39;t really have a choice to use an alternative.</p>
<p>Servlet version 3.0 is in the works, several of the people that blog at <a href="http://cometdaily.com/">Comet Daily</a> are on the Servlet spec expert group and want to see this oversight fixed, but it will be a while before the spec is done, and even longer before we can rely on it&#8217;s support everywhere. </p>
<p><span id="more-359"></span></p>
<p>In an ideal world you&#8217;d do something like this: </p>
<pre lang="java">
public void doPost() {
  // Some setup stuff
  while (holdConnectionOpen) {
    while (nothingToOutput) {
      passThreadBackToOS();
      doOutput();
    }
  }
  // Any close down stuff
}
</pre>
<p>The <code>passThreadBackToOS()</code> is the bit where we need to hand wave a bit &#8211; &quot;this is not the thread you are looking for&quot;.</p>
<p>We need a way to get control back in several circumstances:</p>
<ul>
<li>There is output (some Comet techniques require re-connection on output)</li>
<li>We&#39;ve waited longer than 60 seconds (the &#39;why?&#39; will have to wait for another post)</li>
<li>Something has gone wrong with the connection and we need to reset</li>
<li>The container wants to shut down</li>
</ul>
<p>So we&#39;re going to have to register something to wake us up whenever we want to, but for now we&#39;re going to continue hand-waving.</p>
<p>This kind of code would be possible if we were to use full <a href="http://en.wikipedia.org/wiki/Continuation">continuations</a> &#8211; the kind that are <a href="http://rifers.org/wiki/display/RIFE/Web+continuations">available in RIFE</a>. However full continuations don&#8217;t mix well with Comet. The whole point of wanting to reduce thread usage is to reduce resource consumption, and full continuations are fairly heavy on resources. (Interestingly continuations have been available at a JVM level for a long time, and there is talk of them being opened up at an API level before too long, however I suspect they&#39;ll still be the wrong tool for the job)</p>
<p>So given that we can&#39;t do <code>passThreadBackToOS()</code>, what are the options for Comet?</p>
<h2>Just wait()</h2>
<p>If you are only allowed to use the Servlet spec then you have no option but to call <code>wait()</code> and arrange for something to <code>notify()</code> us when it&#39;s time to do something.</p>
<pre lang="java">
public void doPost() {
  // Some setup stuff
  while (holdConnectionOpen) {
    while (nothingToOutput) {
      wakeThreadUsingNotify(lock);
      lock.wait();
      doOutput();
    }
  }
  // Any close down stuff
}
</pre>
<p>Clearly this doesn&#39;t scale well. <a href="http://directwebremoting.org/">DWR</a> has a nice way to gradually fallback to polling if the server gets overloaded, but for many systems this won&#39;t be needed. What are the options if we can assume some support from the Servlet engine?</p>
<h2>Throw back to the start of Servlet.service()</h2>
<p>The expense with full continuations is in storing the stack. What if we drop the stack storage? We pass control back to the web container using a special exception (this is how continuations were implemented in RIFE under the covers), and then just re-call doPost() at a later date.</p>
<p>The API would then look something like this:</p>
<pre lang="java">
public void doPost() {
  if (!restartedConnection) {
    // Some setup stuff
  }
  while (holdConnectionOpen) {
    while (nothingToOutput) {
      continuation.suspend(); // throws an exception
      doOutput();
    }
  }
  // Any close down stuff
}
</pre>
<p>This is how Jetty supports asynchronous servlets in version 6.0. You can read about <a href="http://docs.codehaus.org/display/JETTY/Continuations">Ajax Continuations</a>, but note that they are different from full continuations because they&#39;re not saving the stack, just restarting the Servlet.service() method. Grizzly has a similar API to the Jetty one, however it&#39;s implementation is closer to the idea below.</p>
<p>While this was the first available way to do async servlets, the general consensus now is that the implementation (using Exceptions to restart the method) is a little hacky, and better options are available.</p>
<h2>Finish Servlet.service() and have something else signal end of the request</h2>
<p>The most common pattern, and the one being adopted in Servlet Spec v3.0 is to have a ServletRequest.suspend() method. This says to the container: &quot;When Servlet.service() ends, we&#39;re not done. Only end the request when something calls ServletRequest.complete() or ServletRequest.resume().</p>
<pre lang="java">
public void doPost() {
  if (!restartedConnection) {
    // Some setup stuff
  }
  while (holdConnectionOpen) {
    while (nothingToOutput) {
      if (outputPending) {
        doOutput();
      }
      request.suspend();
      return;
    }
  }
  // Any close down stuff
}
</pre>
<h2>Putting it all together</h2>
<p>&nbsp;The tricky thing is that these 3 models do radically different things in order to wait. The stack essentially travels in 3 different directions, throwing unwinds it backwards, return unwinds it forwards and wait freezes it.</p>
<p>It&#39;s tricky to come up with a model for a system that can use all of these systems. If you are trying to unify them, then you should take a look at the <a href="http://svn.directwebremoting.org/dwr/trunk/protocol/dwrp/main/java/org/directwebremoting/dwrp/PollHandler.java">PollHandler class</a> in DWR, and how it deals with the <a href="http://svn.directwebremoting.org/dwr/trunk/core/spi/main/java/org/directwebremoting/extend/Sleeper.java">Sleeper</a> and <a href="http://svn.directwebremoting.org/dwr/trunk/core/spi/main/java/org/directwebremoting/extend/Alarm.java">Alarm</a> interfaces.  There is also a <a href="http://directwebremoting.org/dwr/introduction/getting-started.html">Getting Started guide</a>.</p>
<p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2008/05/22/comet-and-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
