<?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/"
	>

<channel>
	<title>Beaver Creek Consulting &#187; Jaxer</title>
	<atom:link href="http://beavercreekconsulting.com/blog/category/jaxer/feed/" rel="self" type="application/rss+xml" />
	<link>http://beavercreekconsulting.com/blog</link>
	<description>Delivering Results in Application Development</description>
	<lastBuildDate>Sun, 03 Jul 2011 16:17:53 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>MapQuest Proxy for Jaxer</title>
		<link>http://beavercreekconsulting.com/blog/2009/01/mapquest-proxy-for-jaxer/</link>
		<comments>http://beavercreekconsulting.com/blog/2009/01/mapquest-proxy-for-jaxer/#comments</comments>
		<pubDate>Sat, 17 Jan 2009 01:19:06 +0000</pubDate>
		<dc:creator>martykube</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Jaxer]]></category>

		<guid isPermaLink="false">http://beavercreekconsulting.com/blog/?p=16</guid>
		<description><![CDATA[If you&#8217;re a MapQuest developer chances are you&#8217;re pretty handy with JavaScript on the client.  It&#8217;s been the sad case that you leave these skills behind when you switch over to server side programming.   Well, happy day, things are changing as support for Server Side JavaScript (SSJS) takes off.  With SSJS [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re a MapQuest developer chances are you&#8217;re pretty handy with JavaScript on the client.  It&#8217;s been the sad case that you leave these skills behind when you switch over to server side programming.   Well, happy day, things are changing as support for Server Side JavaScript (<a href="http://en.wikipedia.org/wiki/SSJS">SSJS</a>) takes off.  With SSJS you can  break out your JavaScript Ninja skills on the server side.  I&#8217;ve been looking at the <a href="http://www.aptana.com/jaxer">Jaxer</a> SSJS platform and worked up this example to show off some of the possibilities.</p>
<p>With the MapQuest JavaScript <a href="http://developer.mapquest.com/downloads">API</a> one can get tiled maps on a page with only client JavaScript.  As soon as you use other MapQuest Services such geocoding, routing, or search, you need to supply a proxy on the web server.  The proxy is need to allow the MapQuest client library to call home while avoiding the browser&#8217;s same-domain security policy.</p>
<p>The example I&#8217;m presenting here is an implementation of such a proxy for the Jaxer platform.  I think a SSJS proxy is an illuminating and useful example.  It&#8217;s a useful example since you need a proxy for putting MapQuest and Jaxer together.  Also, it&#8217;s an illuminating example since it is a typical server side task, fetching data from a different source.  The source could be files, in database, RSS feeds, or, as in this case, a server in a different domain.  MapQuest (MQ) supplies proxies in common languages such PHP, Java, etc., so this example will also allow comparison of the SSJS implementation to implementations in other languages.</p>
<p>The example consists of two HTML pages, one of which is served to the client and one which runs on the Jaxer server and acts as the proxy.</p>
<p><strong>The Client Side</strong></p>
<p>The client page is a hello world type of example for MapQuest – create a tiled map, geocode an address, and place a Point of Interest marker at the geocoded address. The complete source code for this example is available <a title="Source code for the example" href="http://beavercreekconsulting.com/downloads/jaxer-mapquest-proxy.zip">here</a>. Here&#8217;s a screenshot of the client page in action:</p>
<p><img src="http://beavercreekconsulting.com/img/mqproxy-screenshoot.png" alt="" /></p>
<p>The text boxes on the right are a debug log provided the MQ client library that shows interaction between the MQ client library and the proxy.   Specifically, the box labeled “Request URL” is address where the MapQuest client library is configured to find the proxy.  The Request XML box shows the data the client library is sending, which in this case is a request for geocoding per the MQ API (see the MQ XML Interface <a href="http://developer.mapquest.com/Library/SDK_Documentation/Protocols">Reference</a>).  The &#8220;Response XML&#8221; is the XML returned by the MapQuest geocoding service via the proxy.</p>
<p>Here&#8217;s the startMap() method that is called when the client page loads:</p>
<pre class="brush: html">
&lt;script src=&quot;http://btilelog.access.mapquest.com/tilelog/transaction?transaction=script&amp;amp;amp;amp;amp;amp;key=your-MQ-key=true&amp;amp;amp;amp;amp;amp;v=5.3.s&amp;amp;amp;amp;amp;amp;ipkg=controls1&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;lib/mapquest/mqcommon.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;lib/mapquest/mqutils.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;lib/mapquest/mqobjects.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;lib/mapquest/mqexec.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;
var g_proxyServerName = &#039;localhost&#039;;
var g_proxyServerPort = &#039;8000&#039;;
var g_proxyServerPath = &#039;jaxer-mapquest/proxy.html&#039;

var g_serverName = &#039;geocode.dev.mapquest.com&#039;;
var g_serverPort = &#039;80&#039;;
var g_serverPath = &#039;mq&#039;;

var g_geoExec = new MQExec(g_serverName, g_serverPath, g_serverPort, g_proxyServerName, g_proxyServerPath, g_proxyServerPort);

function startMap(){
var g_mqMap = new MQA.TileMap(document.getElementById(&#039;mapWindow&#039;), 2, new MQA.LatLng(40, -95), &quot;map&quot;);

var address = new MQAddress();
address.setCity(&#039;Gobles&#039;);
address.setState(&#039;MI&#039;);
address.setCountry(&#039;USA&#039;);

var gaCollection = new MQLocationCollection(&quot;MQGeoAddress&quot;);
g_geoExec.geocode(address, gaCollection);
var mqAddress = gaCollection.get(0);

var poi = new MQA.Poi(mqAddress.getMQLatLng());
poi.setInfoTitleHTML(&#039;Hello World&#039;);
poi.setInfoContentHTML(&#039;From Gobles, MI&#039;);
g_mqMap.addPoi(poi);
}
&lt;/script&gt;
</pre>
<p>The MQExec object interacts with the proxy.  The location of the proxy on localhost is specified as well as the details of the proxied MapQuest server (geocode.dev.mapquest.com).  When the MQ client library needs to call home for geocoding services (via <code>g_geoExec.geocode()</code>), it will form a GET or POST with the request details and send the request to <code>http://localhost:8000/jaxer-mapquest/proxy.html</code>.</p>
<p><strong>The Server Side</strong></p>
<p>The sever side proxy is implemented in a page named proxy.html.  The page receives the post from the MQ client library, extracts the data, forwards it along to the MQ server, and then returns the MQ response back to the client.</p>
<p>The HTML page, proxy.html, is processed by the Jaxer server.  We&#8217;ll use a slightly different processing model than the typical Jaxer page <a href="http://www.aptana.com/node/150">lifecycle</a>.  In the typical lifecycle a page is parsed on the Jaxer server into a DOM model, scripts that are tagged to be ran on the server are invoked, client side proxies are mixed-in for scripts that are tagged to be proxied, and then the page is serialized and sent off to the client.  In this case, we use server side scripts to overwrite the the DOM on the server side prior to the serialization for returning the page to the client.</p>
<p>This is a handy Jaxer technique.  Since you set the content type and the response content you can pull stunts like serializing arbitrary JavaScript objects and returning them as JSON to the client.  In this case, I&#8217;m overwriting the HTML page and returning the content and content type from the map quest server (XML).  To me, this technique is the more similar to a J2EE <a href="http://java.sun.com/products/servlet/">Servlet</a> than the typical Jaxer lifecycle, which feels more like a <a href="http://en.wikipedia.org/wiki/JavaServer_Pages">JSP</a>.</p>
<p>The proxy.html page consist primarily of JavaScript that get executes in the server context.  The server side script execution is triggered with a <code>onserverload</code> tag:</p>
<pre class="brush: html">
&lt;body onserverload=&quot;BCC.mqproxy.proxify();&quot;&gt;
</pre>
<p>The <code>proxify()</code> method shows the general steps that the proxy executes:</p>
<pre class="brush: javascript">
proxify: function(){
parseClientRequest();
makeMQRequest();
replyToClient();
}
</pre>
<p>In order to overwrite the page&#8217;s DOM with arbitrary content, one calls the <code>Jaxer.Response.setContent()</code> method.  In this case, we&#8217;ll overwrite the page&#8217;s entire DOM with the response and content type obtained from the MQ response.  The property <code>Jaxer.response</code> is an instance of <code>Jaxer.Response</code> that points to the current response:</p>
<pre class="brush: javascript">
var replyToClient = function(){
Jaxer.response.headers[&#039;Content-Type&#039;] = mqResponse.headers[&#039;Content-Type&#039;];
Jaxer.response.setContents(mqResponse.text);
}
</pre>
<p>And that&#8217;s all it takes to send back arbitrary content from a Jaxer HTML page.</p>
<p>Before we can reply to the client, this page has to parse the client request and call the server at MapQuest.  The following function reads the data posted by the client from Jaxer.request (an instance of Jaxer.Request):</p>
<pre class="brush: javascript">
var parseClientRequest = function(){
getMqServerUrlParams();
if (Jaxer.request.method == &#039;POST&#039;) {
getPostData();
}
else {
getUrlParms();
}
};
</pre>
<p>The MQ client sends the target server, port and path as URL parameters and the getMQServerUrlParams() method picks these off.   Jaxer makes the parsed URL available as a property of the request object:</p>
<pre class="brush: javascript">
var serverParams = {
sname: &#039;&#039;,
sport: &#039;&#039;,
spath: &#039;&#039;
};

var getMqServerUrlParams = function(){
logger.debug(&#039;getMqServerUrlParams&#039;);
for (param in serverParams) {
serverParams[param] = Jaxer.request.parsedUrl.queryParts[param];
logger.debug(&#039;getMqServerUrlParams: &#039; + param + &#039;: &#039; + serverParams[param]);
}
};
</pre>
<p>The remainder of the request data comes in as either other URL parameters or as POSTed XML.  In the case of XML data, the proxy needs to add a couple of XML elements for a client ID and password.  Here&#8217;s the routine to get the XML from the request, parse it, modify the DOM and serialize back to XML:</p>
<pre class="brush: javascript">

// Fetch the XML form data and add credentials
var getPostData = function(){
logger.debug(&#039;getPostData&#039;);
logger.debug(&#039;getPostData: postdata:          &#039; + Jaxer.request.postData);

var doc = new DOMParser().parseFromString(Jaxer.request.postData, &#039;text/xml&#039;);
if (doc.documentElement.nodeName == &quot;parsererror&quot;) {
throw new Error(&quot;People we have an issue: XML parse error&quot;);
}
var authenticalNodeList = doc.documentElement.getElementsByTagName(&quot;Authentication&quot;);
if (authenticalNodeList.length &gt; 0) {
authenticatedRequest = true;
var authenticalNode = authenticalNodeList[0];

// add password
var passwordEl = doc.createElement(&#039;Password&#039;);
var passwordTextEl = doc.createTextNode(mqPassword);
authenticalNode.appendChild(passwordEl).appendChild(passwordTextEl);

// add client ID
var clientIdEl = doc.createElement(&#039;ClientId&#039;);
var clientIdTextEl = doc.createTextNode(mqClientId);
authenticalNode.appendChild(clientIdEl).appendChild(clientIdTextEl);
}

// back to a string
postData = new XMLSerializer().serializeToString(doc);
logger.debug(&#039;getPostData: fixed up postdata: &#039; + postData);
};
</pre>
<p>Notice that there is no cross-browser monkey business to get a parser and serializer.  On the server side, Jaxer uses Mozilla so you can count the available features.   This example also makes use of the Jaxer.Log facility which lets you write to server side logs and specify the level of logging detail.</p>
<p>The last code snippet show how to place a synchronous server side HTTP request with Jaxer.Web.send().  The URL is assembled and a POST or GET is made per the client request:</p>
<pre class="brush: javascript">
var makeMQRequest = function(){
mqUrl = &#039;http://&#039; + serverParams.sname + &#039;:&#039; + serverParams.sport + &#039;/&#039; + serverParams.spath;
sendOptions.extendedResponse = true;
if (Jaxer.request.method == &#039;POST&#039;) {
if (authenticatedRequest == true) {
mqUrl += &#039;/mqserver.dll?e=5&#039;;
}
sendOptions.contentType = &#039;application/x-www-form-urlencoded&#039;;
}
else { // GET
var urlQParams = &#039;&#039;;
for (p in urlParams) {
urlQParams += p + &#039;=&#039; + urlParams[p];
}
if (urlParams.length &gt; 0) {
mqUrl += &#039;?&#039; + urlQParams;
}
}
// Call home
mqResponse = Jaxer.Web.send(mqUrl, Jaxer.request.method, postData, sendOptions);
};
</pre>
<p><strong>Wrap up</strong></p>
<p>This example shows how to proxy web content in other domains using Jaxer.  The same basic approach can be used to access other server side resources (files, database, etc).</p>
<p>I&#8217;m a big fan of scripting languages, and JavaScript is my current favorite.  I&#8217;ve been using it not only in web browsers but also as domain specific language in a Business Process Modeling application I&#8217;m working with.  I&#8217;m at the peak of my JavaScript skills, so, I&#8217;m really happy to be able to break out JavaScript on the server side.</p>
]]></content:encoded>
			<wfw:commentRss>http://beavercreekconsulting.com/blog/2009/01/mapquest-proxy-for-jaxer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Jaxer 1.0 RC Support for REST and RPC</title>
		<link>http://beavercreekconsulting.com/blog/2008/10/jaxer-10-rc-support-for-rest-and-rpc/</link>
		<comments>http://beavercreekconsulting.com/blog/2008/10/jaxer-10-rc-support-for-rest-and-rpc/#comments</comments>
		<pubDate>Fri, 10 Oct 2008 03:29:09 +0000</pubDate>
		<dc:creator>martykube</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Jaxer]]></category>

		<guid isPermaLink="false">http://beavercreekconsulting.com/blog/?p=12</guid>
		<description><![CDATA[Jaxer 1.0 RC is out and getting ready to go.  To me, the big news is that server side APIs such as REST and RPC protocols have been promoted to first class citizens.
Up to now, the Jaxer application server has been HTML template oriented.  Jaxer is a Server Side JavaScript (SSJS) port of [...]]]></description>
			<content:encoded><![CDATA[<p>Jaxer <a href="http://www.aptana.com/jaxer/download ">1.0 RC</a> is out and getting ready to go.  To me, the big news is that server side APIs such as <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer">REST</a> and <a href="http://en.wikipedia.org/wiki/Remote_procedure_call">RPC</a> protocols have been promoted to first class citizens.</p>
<p>Up to now, the Jaxer application server has been HTML template oriented.  Jaxer is a Server Side JavaScript (SSJS) port of <a href="http://www.mozilla.org/">Mozilla</a>, and of course, that&#8217;s a really cool thing.  If you&#8217;re a JavaScript Ninja, you finally have an application server which speaks your native language.</p>
<p>However, up to 1.0 RC, the server side <a href="http://www.aptana.com/node/275">processing model</a> has been page/template oriented.  On the server side, you&#8217;ve had to provide a concrete HTML page on the server to trigger Jaxer processing.   With the 1.0 RC, you can now map an URL to JavaScript files that provide the HTTP response.   This feature makes is easier to provide REST or RPC interfaces on top of server side JavaScript code.</p>
<p>The configuration I&#8217;ve been using is Apache and the standalone Jaxer server.    Jaxer comes bundled with Aptana&#8217;s <a href="http://aptana.com/studio">Studio</a> IDE which is the easiest configuration for getting started on Jaxer.   However, you&#8217;ll have to come to terms with deploying Jaxer under <a href="http://httpd.apache.org/">Apache</a> when you go to production (OK, sure, you can deploy to Aptana&#8217;s <a href="http://aptana.com/cloud">Cloud</a> which deploys direct from Studio, but that&#8217;s another beta topic).</p>
<p>Recent releases (prior to 1.0) have allowed you to interrupt the normal template processing of page and substitute arbitrary content and content types to be returned to the <a href="http://forums.aptana.com/viewtopic.php?t=5412&amp;highlight=content+type">client</a>.  In order to make this work, you&#8217;ve had to provide a file that Apache is configured to hand off to the Jaxer processor.</p>
<p>I&#8217;m working on an Jaxer application that responds to REST URLs.  Here is the approach I was using for releases prior to 1.0.  I wrote Apache <a href="http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html">mod_rewrite</a> rule to hit a front controller, where the front controller is an HTML page that Jaxer processes.  I added the following to my httpd.conf file:</p>
<pre class="brush: html">
RewriteEngine on
RewriteRule /world.* /world/index.html
</pre>
<p>My plan is that index.html will respond to REST URLs for POST, GET, PUT, and DELTE request such as :</p>
<p>http://&lt;host&gt;/world/&lt;entity&gt;/&lt;id&gt;</p>
<p>The one issue I ran into was that the Apache configuration that tells Apache to hand off a request to Jaxer for filtering needs a file extension and a content type.  The above URL has no file extension.  My solution was to place the font controller file in it&#8217;s own directory and set Jaxer filter handling to all content in the specified directory (in my httpd.conf file):</p>
<pre class="brush: html">
&lt;Directory &quot;c:/opt/xampp/htdocs/world&quot;&gt;
JaxerFilter *
JaxerFilterContentType text/html
Order Deny,Allow
Deny from all
Allow from all
&lt;/Directory&gt;
</pre>
<p>The good news is that the 1.0 RC allows direct <a href="http://www.aptana.com/docs/index.php/Migrating_from_Jaxer_beta">specification </a>of JavaScript files to handle REST type URLs<a href="http://www.aptana.com/docs/index.php/Migrating_from_Jaxer_beta"></a>.  Tricks like the  above rewrite rules won&#8217;t be need for REST.  This is a big change as server side code stands alone, without a HTML page template.  To me, this is the difference between a <a href="http://www.devx.com/tips/Tip/25217">Servlet and a JSP</a>.</p>
<p>With the 1.0 RC it appears that you can match URLs to execution of server side JavaScript files, which feels much more like a J2EE web.xml file which matches URLs to invocation of server side code (servlets).</p>
<p>I&#8217;m working up some examples of all this with 1.0 RC which aren&#8217;t quite baked yet.  If you&#8217;re in a hurry to make REST work with 1.0, here are the files to look at from the standalone <a href="http://www.aptana.com/jaxer/download">release</a>:</p>
<pre>
jaxer\confs\jaxer-*.httpd.conf
jaxer\default_local_jaxer\conf\configApps.js
jaxer\framework\extensions\serviceDispatcher.js
</pre>
]]></content:encoded>
			<wfw:commentRss>http://beavercreekconsulting.com/blog/2008/10/jaxer-10-rc-support-for-rest-and-rpc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Jaxer, E4X and Prototype</title>
		<link>http://beavercreekconsulting.com/blog/2008/08/jaxer-e4x-and-prototype/</link>
		<comments>http://beavercreekconsulting.com/blog/2008/08/jaxer-e4x-and-prototype/#comments</comments>
		<pubDate>Mon, 04 Aug 2008 13:50:00 +0000</pubDate>
		<dc:creator>martykube</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Jaxer]]></category>

		<guid isPermaLink="false">http://beavercreekconsulting.com/blog/?p=10</guid>
		<description><![CDATA[The ECMAScript for XML standard a.k.a “E4X” is a cool addition to JavaScript that provides for native support of XML.  E4X adds nifty features such as simplified XML traversal and XML literals to the language.  E4X is supported in Mozilla and Adobe JavaScript implementations.  The lack of support in IE hinders the [...]]]></description>
			<content:encoded><![CDATA[<p>The ECMAScript for XML standard a.k.a “<span style="color: #000080;"><span style="text-decoration: underline;"><a href="http://www.ecma-international.org/publications/standards/Ecma-357.htm">E4X”</a></span></span> is a cool addition to JavaScript that provides for native support of XML.  E4X adds nifty features such as simplified XML traversal and XML literals to the language.  E4X is supported in Mozilla and Adobe JavaScript <span style="color: #000080;"><span style="text-decoration: underline;"><a href="http://en.wikipedia.org/wiki/E4x#Implementations">implementations</a></span></span>.  The lack of support in <span style="color: #000080;"><span style="text-decoration: underline;"><a href="http://www.w3schools.com/e4x/e4x_browsers.asp">IE</a></span></span> hinders the widespread adoption of E4X.  However, E4x is supported on Aptana <a href="http://aptana.com/jaxer">Jaxer</a>.</p>
<p>I&#8217;ve been using Jaxer for web development lately.  Jaxer is a web application server which uses JavaScript on the server side.  The server-side JavaScript implementation is based on Mozilla, and E4X is supported.  So, if you&#8217;re using Jaxer, there is nothing holding you back from using E4X on the server side.</p>
<p>With this in mind, I&#8217;ve cooked up an example intended to whet your appetite for E4X.  The source code is shown below.  The example executes a query against a database and renders each returned row as a HTML table.  I&#8217;m using E4X for two tasks: storing configuration data and filling in a HTML template.</p>
<p>Note how various scripts or functions are tagged with <code>runat='server'</code>. This is how Jaxer knows which scripts to process on the server and which not to.  All of the scripts in this example run on the server.  The execution of the scripts is started by the <code>onserverload</code> attribute of the body tag.  This is the server-side equivalent to the <code>onload</code> attribute in the browser context.</p>
<p>For the configuration example, I stored SQL statements in an XML document.  I needed a select query to execute against the database, and then of course I realized I needed some DDL to create the table and some more SQL to insert records.  I decided to store all of my queries as E4X XML literals in JavaScript embedded in my HTML page.  The embedded XML is seen only on the Jaxer Server, and not in the client browser.  On lines 12-37 I used an <span style="color: #000080;"><span style="text-decoration: underline;"><a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Processing_XML_with_E4X#Creating_an_XML_object">XML literal</a></span></span> to declare an XML document containing 3 SQL statements.</p>
<p>A couple of points to note.  First I embedded this configuration into a HTML page.  With the Jaxer server-side facilities for accessing the file system, one could store the XML in a file and share the configuration across HTML pages.  Second, with a CDATA section (lines 27-29), I don&#8217;t have to worry about escaping my SQL to make valid XML.</p>
<p>IMHO, the coolest E4X feature is simplified DOM access.  The code to pull out a particular SQL statement by id is:</p>
<pre class="brush: javascript">
var sqlToRun = sqlStatements.sql.(@id == &#039;select-persons-no-heavier-than&#039;);
</pre>
<p>After executing the select query, I render each row as a little HTML table.  On line 50 I access each record via the <span style="color: #000080;"><span style="text-decoration: underline;"><a href="http://www.aptana.com/reference/jaxer/api/Jaxer.DB.ResultSet.html">Jaxer.DB.ResultSet</a></span></span> API.  I create a table for each record with an XML literal on lines 52-69.  One nice feature of E4X is the ability to execute arbitrary JavaScript code within the XML literal.  For example, line 67:</p>
<pre class="brush: javascript">
&lt;td&gt;{(dbRecord.weight_kg / 0.454).toFixed(2)}&lt;/td&gt;
</pre>
<p>reads a JavaScript object property, divides by .45, renders the number with 2 decimal places, and then places that value in the <code>td</code> tag.  Finally on line 74, I insert the table into the page&#8217;s DOM tree.  The insert is done with Prototype’s <code>Element.insert</code> method which takes a string or DOM Node as an argument and inserts the content into the page&#8217;s DOM tree.</p>
<p>Don&#8217;t forget, that all of the scripts tags (for prototype.js as well) have a <code>runat=”server”</code> attribute, so all of this action happens on the Jaxer server before the page is render as text and sent to the client.</p>
<p>One interesting point is that I used Prototype on the server side.  My usage was pretty modest here; I take it as a good sign that the server side JavaScript environment closely matches the JavaScript environment in a browser.</p>
<p>I’m pretty happy with this example code.  I think the templating of HTML turned out to be very transparent and easy to understand code.  Several factors contribute to clean code: XML literals avoid cluttering the code with quoted string and also allow value interpolation, and insertion of the XML strings into the DOM tree with Prototype.  This is a nice illustration of the handy features that are available in the Jaxer server side programming environment.</p>
<pre class="brush: javascript">
 &lt;html&gt;
     &lt;head&gt;
   &lt;title&gt;Jaxer E4X Example&lt;/title&gt;

     /*
    * All of the JavaScript is running on the server due to the
    * runat=&quot;server&quot; attribute of the script tags
    */
     &lt;script runat=&quot;server&quot; src=&quot;lib/prototype/prototype.js&quot;&gt;&lt;/script&gt;
     &lt;script runat=&quot;server&quot;&gt;

   // An XML literal holding template SQL
     var sqlStatements =
       &lt;sql-statements&gt;
         &lt;sql id=&#039;create-table&#039;&gt;
           create table if not exists person (
             id      integer,
             first_name  varchar(20),
             last_name   varchar(20),
             birth_date  datetime,
             weight_kg   decimal(5,2),
             height_m    decimal(5,2),
             constraint person_pk primary key(id)
           );
         &lt;/sql&gt;
         &lt;sql id=&#039;insert-person&#039;&gt;
           insert into person
             (id, first_name, last_name, birth_date, weight_kg, height_m)
           values
             (?, ?, ?, ?, ?, ?)
         &lt;/sql&gt;
         &lt;sql id=&#039;select-persons-no-heavier-than&#039;&gt;
           &lt;![CDATA[
             select * from person where weight_kg &lt;= ?
           ]]&gt;
         &lt;/sql&gt;
       &lt;/sql-statements&gt;;

     // Called on server side page load.
     // Triggered by the onserverload attribute of the body tag
       function showPersonDetails() {

     // Find a SQL statement by name
         var sqlToRun = sqlStatements.sql.(@id == &#039;select-persons-no-heavier-than&#039;);

     // Execute the SQL with the Jaxer.DB API
         var resultSet = Jaxer.DB.execute(sqlToRun, 200);

     // For each record returned from the DB...
     resultSet.rows.forEach(function(dbRecord, index) {
       // Create some markup using a XML Literal and value interpolation
           var tbl =
           &lt;table border=&#039;1&#039;&gt;
             &lt;tr&gt;
               &lt;td colspan=&quot;2&quot;&gt;Person Detail&lt;/td&gt;
             &lt;/tr&gt;
             &lt;tr&gt;
               &lt;td&gt;First name:&lt;/td&gt;
               &lt;td&gt;{dbRecord.first_name}&lt;/td&gt;
             &lt;/tr&gt;
             &lt;tr&gt;
               &lt;td&gt;First name:&lt;/td&gt;
               &lt;td&gt;{dbRecord.last_name}&lt;/td&gt;
             &lt;/tr&gt;
             &lt;tr&gt;
               &lt;td&gt;Weight in pounds:&lt;/td&gt;
               &lt;td&gt;{(dbRecord.weight_kg / 0.454).toFixed(2)}&lt;/td&gt;
             &lt;/tr&gt;
           &lt;/table&gt;;

           tbl += &lt;br/&gt;;

       // add the new markup to the page DOM
           $(&#039;person-details&#039;).insert(tbl.toXMLString());
     });
       }

     &lt;/script&gt;
   &lt;/head&gt;
   &lt;body onserverload=&quot;showPersonDetails();&quot;&gt;
       &lt;div id=&#039;person-details&#039;&gt;
       &lt;/div&gt;
   &lt;/body&gt;
 &lt;/html&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://beavercreekconsulting.com/blog/2008/08/jaxer-e4x-and-prototype/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Jaxer CRUD</title>
		<link>http://beavercreekconsulting.com/blog/2008/08/jaxer-crud/</link>
		<comments>http://beavercreekconsulting.com/blog/2008/08/jaxer-crud/#comments</comments>
		<pubDate>Mon, 04 Aug 2008 01:18:48 +0000</pubDate>
		<dc:creator>martykube</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Jaxer]]></category>

		<guid isPermaLink="false">http://beavercreekconsulting.com/blog/?p=9</guid>
		<description><![CDATA[Aptana&#8217;s Jaxer is a Web Application platform that uses JavaScript on the server side.  I&#8217;m starting to develop a real taste for the JavaScript language, so Jaxer is a nice place to try out new modes of JavaScript programming.
Server side programming for Web Applications typically involves a good bit of interaction with a database. [...]]]></description>
			<content:encoded><![CDATA[<p><span style="color: #000080;"><span style="text-decoration: underline;"><a href="http://aptana.com/">Aptana&#8217;s</a></span></span> <span style="color: #000080;"><span style="text-decoration: underline;"><a href="http://aptana.com/jaxer">Jaxer</a></span></span> is a Web Application platform that uses JavaScript on the server side.  I&#8217;m starting to develop a real taste for the JavaScript language, so Jaxer is a nice place to try out new modes of JavaScript programming.</p>
<p>Server side programming for Web Applications typically involves a good bit of interaction with a database.  As a Java developer, I typically use <span style="color: #000080;"><span style="text-decoration: underline;"><a href="http://java.sun.com/javase/technologies/database/">JDBC</a></span></span> or an Object Relational Mapping (ORM) framework such as <span style="color: #000080;"><span style="text-decoration: underline;"><a href="http://www.hibernate.org/">Hibernate</a></span></span> for database interaction.  If you look around, you&#8217;ll find JavaScript lacks such established API/Frameworks for DB interaction  (though it looks like some JavaScript ORMs are being actively <a title="JavaScript ORM" href="http://forums.aptana.com/viewforum.php?f=42">developed</a>).   At this point in time, things are pretty much DIY.</p>
<p>With this in mind, I&#8217;ve worked up some code example for <span style="color: #000080;"><span style="text-decoration: underline;"><a href="http://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a></span></span> operations using the Jaxer database API.  This is a simple example, intended to help folks climb up the Jaxer learning curve.  The complete source code for the example is at the bottom of this post.</p>
<p>The example reads and writes from elements on a HTML page and also a database table.  In the example, there are HTML tables which describe a person, and likewise, I&#8217;ve created a table in the database that has the same attributes (with slightly different names, just to keep this real.  The table DDL is in the example code).  Here&#8217;s a screen shot of the example:</p>
<p><img src="http://beavercreekconsulting.com/img/jaxer-crud-screenshot.png" alt="Jaxer CRUD Example screenshoot" width="489" height="526" /></p>
<p>The flow of the example is:</p>
<p>1) Read attributes from the first (from the top) HTML table and then create a corresponding record in the database.</p>
<p>2) Read the same attributes back from the database and then populate the next HTML table</p>
<p>3) Read attributes from the third HTML table and update the database</p>
<p>4) Delete the record from the database.</p>
<p>Line 108 also shows an interesting capability of Jaxer:  The script block there is set to runat=”server-proxy”. This tells Jaxer to run these scripts at the server, but let them be callable from the browser.  So when I click the CRUD button on the client, it calls runExample on line 14, which in turn calls the four CRUD functions which run at the server.  I&#8217;m actually calling a function on the server directly from the client!  Note too that this example uses blocking calls from the browser to the Jaxer server.  It is very easy to change this code to the Jaxer asynchronous API, which is likely topic for my next post.</p>
<p>Without further ado &#8211; the code:</p>
<pre class="brush: javascript">
 &lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot; &quot;http://www.w3.org/TR/html4/strict.dtd&quot;&gt;
 &lt;html&gt;
   &lt;head&gt;
     &lt;title&gt;Jaxer CRUD&lt;/title&gt;
     &lt;script type=&quot;text/javascript&quot; src=&quot;prototype.js&quot;&gt;&lt;/script&gt;

     /*
      *  Scripts that run in the client browser
      */
     &lt;script runat=&#039;client&#039;&gt;
       //
       //  Run the example on button click
       //
       function runExample() {
         // server side method that creates a table if needed
         createTable();
         // Do the CRUD operations
         createPerson();
         readPerson();
         updatePerson();
         deletePerson();
       }

       // Create a person in the DB based on properties read from a HTML table
       function createPerson() {
         // pull properties from HTML table
         var p = objectFromTable(&#039;create-table&#039;);
         // write to DB via server proxy call
         createPerson_Server(p);
       }

       // Read a person from the DB and write to a HTML table
       function readPerson() {
         // read the person from the DB via a server proxy method
         var p = readPerson_Server(1);
         // populate the HTML table
         tableFromObject(&#039;read-table&#039;, p);
       }

       // Update a person in the DB based on properties read from an HTML table
       function updatePerson() {
         // read the person properties from an HTML table
         var p = objectFromTable(&#039;update-table&#039;);
         // update the DB via a server proxy call
         updatePerson_Server(p);
       }

       // Delete a person in the DB
       function deletePerson() {
         // Server call to delete in the DB
         deletePerson_Server(1);
       }

       //
       // Utility functions
       //

       // populate an object from values in a HTML table
       function objectFromTable(tableId) {
         var o = {};
         var propNames = $$(&#039;#&#039; + tableId + &#039; th&#039;);
         var props = $$(&#039;#&#039; + tableId + &#039; td&#039;);
         var propNum = 0;
         propNames.each(function(item) {
           o[item.innerHTML] = props[propNum++].innerHTML;
         });
         o.birthDate = dateFromStr(o.birthDate);
         return o;
       }

       // populate a HTML table from values in an object
       function tableFromObject(tableId, anObject) {
         anObject.birthDate = strFromDate(anObject.birthDate);
         var propNames = $$(&#039;#&#039; + tableId + &#039; th&#039;);
         var props = $$(&#039;#&#039; + tableId + &#039; td&#039;);
         var propNum = 0;
         propNames.each(function(item) {
           props[propNum++].innerHTML = anObject[item.innerHTML];
         });
       }

       // convert from string &#039;yyyy-mm-dd&#039; to JS Date
       function dateFromStr(dateStr) {
         if(dateStr) {
           var dateParts = dateStr.split(&#039;-&#039;);
           var date = new Date();
           date.setFullYear(dateParts[0]);
           date.setMonth(dateParts[1] - 1);
           date.setDate(dateParts[2]);
         }
         return date;
       }

       // convert from JS Date to string &#039;yyyy-mm-dd&#039;
       function strFromDate(aDate) {
         var str = &#039;&#039;;
         if(aDate) {
           str +=  (aDate.getFullYear() +  (aDate.getMonth() + 1) + aDate.getDate());
         }
         return str;
       }
     &lt;/script&gt;

     /*
      *  Scripts that run on the server.
      *  Jaxer generated stubs are used to call these from the client.
      */
     &lt;script runat=&#039;server-proxy&#039;&gt;

       //
       // Server side persistence functions
       //

       // Write a new object to the DB
       function createPerson_Server(person) {
         // execute insert statement, binding to properties of passed in person
         Jaxer.DB.execute(
           &#039;insert into person ( &#039;+
             &#039;  id, first_name, last_name, birth_date, weight_kg, height_m &#039; +
           &#039; ) values (?, ?, ?, ?, ?, ?);&#039;,
           person.id, person.firstName,
           person.lastName, person.birthDate,
           person.weightInKilograms, person.heightInMeters
         );
       }

       // Read an existing record and return a JavaScript object
       function readPerson_Server(id) {
         // execute query and receive returned a Jaxer.DB.ResultSet
         var resultSet = Jaxer.DB.execute(&#039;select * from person where id = ?;&#039;, id);
         // select the first row since weonly care about 1 person
         var aRow = resultSet.rows[0];
         // map DB column names to front end column names
         var person = {
           id: aRow.id,
           firstName: aRow.first_name,
           lastName: aRow.last_name,
           birthDate: aRow.birth_date,
           weightInKilograms: aRow.weight_kg,
           heightInMeters: aRow.height_m
         };
         // return to client for display
         return person;
       }

       // From a JS Object, update a row in the DB
       function updatePerson_Server(person) {
         // Update all fields for the given primary key value
         Jaxer.DB.execute(
           &#039;update person set  &#039;+
             &#039;  first_name = ?, last_name = ?, birth_date = ?, weight_kg = ?, height_m = ? &#039; +
           &#039; where id = ?;&#039;,
           person.firstName, person.lastName, person.birthDate,
           person.weightInKilograms, person.heightInMeters,
           person.id
         );
       }

       // Delete a record in the DB
       function deletePerson_Server(id) {
         Jaxer.DB.execute(&#039;delete from person where id = ?;&#039;, id);
       }

       //  Create a table if the table is not already in the DB
       function createTable(){
         Jaxer.DB.execute(
           &#039;create table if not exists person (   &#039; +
           &#039; id      integer,   &#039; +
           &#039; first_name  varchar(20),   &#039; +
           &#039; last_name   varchar(20),   &#039; +
           &#039; birth_date  datetime,   &#039; +
           &#039; weight_kg   decimal(5,2),   &#039; +
           &#039; height_m    decimal(5,2),   &#039; +
           &#039; constraint person_pk primary key(id)); &#039;
         );
       }
     &lt;/script&gt;
     &lt;style&gt;
       .big-cap {
         color: blue;
         font-size:larger;
         font-style:italic;
       }
       body {
         font-family:Arial;
         font-size: 10pt;
       }
     &lt;/style&gt;
   &lt;/head&gt;
   &lt;body&gt;
     &lt;h3&gt;&lt;span class=&quot;big-cap&quot;&gt;C&lt;/span&gt;reate a person from this table&lt;/h3&gt;
     &lt;table border=&quot;1&quot; style=&quot;text-align: center&quot; id=&quot;create-table&quot;&gt;
       &lt;tr&gt;
         &lt;th&gt;id&lt;/th&gt;
         &lt;th&gt;firstName&lt;/th&gt;
         &lt;th&gt;lastName&lt;/th&gt;
         &lt;th&gt;birthDate&lt;/th&gt;
         &lt;th&gt;weightInKilograms&lt;/th&gt;
         &lt;th&gt;heightInMeters&lt;/th&gt;
       &lt;/tr&gt;
       &lt;tr&gt;
         &lt;td&gt;1&lt;/td&gt;
         &lt;td&gt;John&lt;/td&gt;
         &lt;td&gt;Doe&lt;/td&gt;
         &lt;td&gt;1975-11-20&lt;/td&gt;
         &lt;td&gt;90.7&lt;/td&gt;
         &lt;td&gt;1.82&lt;/td&gt;
       &lt;/tr&gt;
     &lt;/table&gt;
     &lt;hr/&gt;
     &lt;h3&gt;&lt;span class=&quot;big-cap&quot;&gt;R&lt;/span&gt;ead a person and populate this table&lt;/h3&gt;
     &lt;table border=&quot;1&quot; style=&quot;text-align: center&quot; id=&quot;read-table&quot;&gt;
       &lt;tr&gt;
         &lt;th&gt;id&lt;/th&gt;
         &lt;th&gt;firstName&lt;/th&gt;
         &lt;th&gt;lastName&lt;/th&gt;
         &lt;th&gt;birthDate&lt;/th&gt;
         &lt;th&gt;weightInKilograms&lt;/th&gt;
         &lt;th&gt;heightInMeters&lt;/th&gt;
       &lt;/tr&gt;
       &lt;tr&gt;
         &lt;td&gt;&lt;/td&gt;
         &lt;td&gt;&lt;/td&gt;
         &lt;td&gt;&lt;/td&gt;
         &lt;td&gt;&lt;/td&gt;
         &lt;td&gt;&lt;/td&gt;
         &lt;td&gt;&lt;/td&gt;
       &lt;/tr&gt;
     &lt;/table&gt;
     &lt;hr/&gt;
     &lt;h3&gt;&lt;span class=&quot;big-cap&quot;&gt;U&lt;/span&gt;pdate a person from this table&lt;/h3&gt;
     &lt;table border=&quot;1&quot; style=&quot;text-align: center&quot; id=&quot;update-table&quot;&gt;
       &lt;tr&gt;
         &lt;th&gt;id&lt;/th&gt;
         &lt;th&gt;firstName&lt;/th&gt;
         &lt;th&gt;lastName&lt;/th&gt;
         &lt;th&gt;birthDate&lt;/th&gt;
         &lt;th&gt;weightInKilograms&lt;/th&gt;
         &lt;th&gt;heightInMeters&lt;/th&gt;
       &lt;/tr&gt;
       &lt;tr&gt;
         &lt;td&gt;1&lt;/td&gt;
         &lt;td&gt;Jane&lt;/td&gt;
         &lt;td&gt;Smith&lt;/td&gt;
         &lt;td&gt;1978-1-1&lt;/td&gt;
         &lt;td&gt;89.2&lt;/td&gt;
         &lt;td&gt;1.76&lt;/td&gt;
       &lt;/tr&gt;
     &lt;/table&gt;
     &lt;hr/&gt;
     &lt;h3&gt;&lt;span class=&quot;big-cap&quot;&gt;D&lt;/span&gt;elete person with id = 1&lt;/h3&gt;
     &lt;hr/&gt;
     &lt;button onclick=&quot;runExample();&quot;&gt;Crud&lt;/button&gt;
   &lt;/body&gt;
 &lt;/html&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://beavercreekconsulting.com/blog/2008/08/jaxer-crud/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

