<?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:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Dan Haywood</title>
	<atom:link href="http://danhaywood.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://danhaywood.com</link>
	<description>domain driven design, restful objects, apache isis, the naked objects pattern, agile and more</description>
	<lastBuildDate>Fri, 10 Feb 2012 22:25:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='danhaywood.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://1.gravatar.com/blavatar/b1eb53d82980ace193f5d50c92bc059d?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Dan Haywood</title>
		<link>http://danhaywood.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://danhaywood.com/osd.xml" title="Dan Haywood" />
	<atom:link rel='hub' href='http://danhaywood.com/?pushpress=hub'/>
		<item>
		<title>Filters don&#8217;t fire when bouncing off web.xml for error handling</title>
		<link>http://danhaywood.com/2012/02/10/filters-dont-fire-when-bouncing-off-web-xml-for-error-handling/</link>
		<comments>http://danhaywood.com/2012/02/10/filters-dont-fire-when-bouncing-off-web-xml-for-error-handling/#comments</comments>
		<pubDate>Fri, 10 Feb 2012 22:25:36 +0000</pubDate>
		<dc:creator>danhaywood</dc:creator>
				<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://danhaywood.com/?p=917</guid>
		<description><![CDATA[Here&#8217;s a nice little gotcha for ya! A fairly common pattern is to use a filter that wraps the (Http)ServletRequest and (Http)ServletResponse in an app-specific wrapper; this can be used to hold user credentials and state etc. In essence it is: where and AppResponse similarly subclasses from HttpServletResponseWrapper. But let&#8217;s now look at the following [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=danhaywood.com&amp;blog=25721749&amp;post=917&amp;subd=danhaywood&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a nice little gotcha for ya!</p>
<p>
A fairly common pattern is to use a filter that wraps the <tt>(Http)ServletRequest</tt> and <tt>(Http)ServletResponse</tt> in an app-specific wrapper; this can be used to hold user credentials and state etc.  In essence it is:<br />
<span id="more-917"></span><br />
<pre class="brush: java;">
@WebFilter(&quot;*&quot;)
public class AppRequestResponseFilter implements Filter {
  public void init(FilterConfig fConfig) throws ServletException { }
  public void destroy() {}
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    chain.doFilter(new AppRequest(request), new AppResponse(response));
  }
}
</pre></p>
<p>
where<br />
<pre class="brush: java;">
public class AppRequest extends HttpServletRequestWrapper {
  public AppRequest(ServletRequest request) {
    super((HttpServletRequest) request);
  }
}
</pre></p>
<p>
and <tt>AppResponse</tt> similarly subclasses from <tt>HttpServletResponseWrapper</tt>.</p>
<p>
But let&#8217;s now look at the following servlet that simply returns an error:</p>
<p><pre class="brush: java;">
@WebServlet(&quot;/sendsAnError&quot;)
public class SendsAnErrorServlet extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // safe to downcast here...
    // AppRequest appRequest = (AppRequest)request;
    response.sendError(401);
  }
}
</pre></p>
<p>
As the comments note, this servlet could downcast <tt>HttpServletRequest</tt> to <tt>AppRequest</tt> if it so desired.  Indeed, any filter or servlet could do perform this downcast.  And you can see this in the stacktrace when I put a breakpoint in the servlet:<br />
<a href="http://danhaywood.files.wordpress.com/2012/02/sendsanerror.png"><img src="http://danhaywood.files.wordpress.com/2012/02/sendsanerror.png?w=300&#038;h=196" alt="" title="Regular servlet gets the application-specific request/response objects" width="300" height="196" class="aligncenter size-medium wp-image-918" /></a></p>
<p>
Or could it?  Well, no, not always.  Because in <tt>web.xml</tt> we have the following entry:<br />
<pre class="brush: xml;">
&lt;error-page&gt;
  &lt;error-code&gt;401&lt;/error-code&gt;
  &lt;location&gt;/catchAnError&lt;/location&gt;
&lt;/error-page&gt;
</pre></p>
<p>
This instructs the servlet container that if a servlet returns a 401, then to redirect to the resource at the <tt>/catchAnError</tt> mapping.  In our case, this corresponds to the following servlet:</p>
<p><pre class="brush: java;">
@WebServlet(&quot;/catchAnError&quot;)
public class CatchAnErrorServlet extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // ... but not safe to downcast here
    // AppRequest appRequest = (AppRequest)request;
    response.getWriter().println(&quot;&lt;p&gt;an error occurred&lt;/p&gt;&quot;);
  }
}
</pre></p>
<p>
And so here&#8217;s the catch: when the servlet container invokes this servlet to handle the error, any filters are NOT called.  And you can see this in the stacktrace when I break in this second servlet; the implementation that is provided is that of the servlet container, not of the filter:<br />
<a href="http://danhaywood.files.wordpress.com/2012/02/catchanerror.png"><img src="http://danhaywood.files.wordpress.com/2012/02/catchanerror.png?w=300&#038;h=195" alt="" title="Error handling servlet gets only the servlet container&#039;s impl of HttpServletRequest etc." width="300" height="195" class="aligncenter size-medium wp-image-919" /></a></p>
<p>
What would happen, do you think, if you were to blindly downcast to <tt>AppRequest</tt> in this second servlet?  Well, it&#8217;d be a <tt>ClassCastException</tt>, of course, which the servlet container will deal with by just rendering its default error page (for a 401, in this case).  Meanwhile you&#8217;ll be stuck there wondering why your error handling servlet didn&#8217;t (seem to) fire.</p>
<p>
I guess this is in the servlet spec somewhere, but it&#8217;s surprising behaviour.  And it had us stumped for a little while.</p>
<p>
As ever, comments welcome.</p>
<br />Filed under: <a href='http://danhaywood.com/category/random/java/'>java</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/danhaywood.wordpress.com/917/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/danhaywood.wordpress.com/917/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/danhaywood.wordpress.com/917/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/danhaywood.wordpress.com/917/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/danhaywood.wordpress.com/917/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/danhaywood.wordpress.com/917/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/danhaywood.wordpress.com/917/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/danhaywood.wordpress.com/917/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/danhaywood.wordpress.com/917/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/danhaywood.wordpress.com/917/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/danhaywood.wordpress.com/917/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/danhaywood.wordpress.com/917/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/danhaywood.wordpress.com/917/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/danhaywood.wordpress.com/917/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=danhaywood.com&amp;blog=25721749&amp;post=917&amp;subd=danhaywood&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://danhaywood.com/2012/02/10/filters-dont-fire-when-bouncing-off-web-xml-for-error-handling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/204ef8a2259ebe0716f985f96c1c350d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">danhaywood</media:title>
		</media:content>

		<media:content url="http://danhaywood.files.wordpress.com/2012/02/sendsanerror.png?w=300" medium="image">
			<media:title type="html">Regular servlet gets the application-specific request/response objects</media:title>
		</media:content>

		<media:content url="http://danhaywood.files.wordpress.com/2012/02/catchanerror.png?w=300" medium="image">
			<media:title type="html">Error handling servlet gets only the servlet container&#039;s impl of HttpServletRequest etc.</media:title>
		</media:content>
	</item>
		<item>
		<title>JQueryMobile demo app walk-thru</title>
		<link>http://danhaywood.com/2012/02/01/jquerymobile-demo-app-walkthr/</link>
		<comments>http://danhaywood.com/2012/02/01/jquerymobile-demo-app-walkthr/#comments</comments>
		<pubDate>Wed, 01 Feb 2012 23:29:59 +0000</pubDate>
		<dc:creator>danhaywood</dc:creator>
				<category><![CDATA[apache isis]]></category>
		<category><![CDATA[jquerymobile]]></category>
		<category><![CDATA[restful objects]]></category>

		<guid isPermaLink="false">http://danhaywood.com/?p=900</guid>
		<description><![CDATA[In the previous post I showed some screenshots of the simple JQueryMobile app that is hosted by the Apache Isis&#8216; online demo app, demonstrating one way of using the built-in Restful API. In this post, I want to look at the JQueryMobile code in a little more detail. The app consists of a single html [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=danhaywood.com&amp;blog=25721749&amp;post=900&amp;subd=danhaywood&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In the <a title="JQueryMobile on the Apache Isis’ REST API" href="http://danhaywood.com/2012/01/20/jquerymobile-on-apache-isis-rest-api/">previous post</a> I showed some screenshots of the simple <a title="JQueryMobile" href="http://jquerymobile.com" target="_blank">JQueryMobile</a> app that is hosted by the <a href="http://incubator.apache.org/isis" title="Apache Isis" target="_blank">Apache Isis</a>&#8216; <a href="http://mmyco.co.uk:8180/isis-onlinedemo" title="Apache Isis online demo app" target="_blank">online demo</a> app, demonstrating one way of using the built-in <a title="Restful Objects" href="http://restfulobjects.org" target="_blank">Restful API</a>. In this post, I want to look at the JQueryMobile code in a little more detail.</p>
<p>The app consists of a single html page, index.html, along with a number of supporting Javascript files.  We start by bring in the Javascript libraries, most notably JQueryMobile and JQuery:<br />
<span id="more-900"></span><br />
<pre class="brush: xml;">
&lt;link rel=&quot;stylesheet&quot; href=&quot;../jquery.mobile/jquery.mobile-1.0.min.css&quot; /&gt;
&lt;script src=&quot;../jquery/jquery-1.6.4.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;../jquery.mobile/jquery.mobile-1.0.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;../jquery.tmpl/jquery.tmpl-vBeta1.0.0.min.js&quot;&gt;&lt;/script&gt;
</pre></p>
<p>You&#8217;ll note that I&#8217;ve also brought in the JQuery.tmpl library for templating.  This has actually been discontinued by the JQuery team, but its replacement isn&#8217;t yet available.  Since one templating solution is very much like another, I decided to carry on using it for this demo.</p>
<p>In addition to the third-party libraries, the app itself is broken up into a number of Javascript files:</p>
<p><pre class="brush: xml;">
&lt;script type=&quot;text/javascript&quot; src=&quot;namespace.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;util.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;generic.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;app.js&quot;&gt;&lt;/script&gt;
</pre></p>
<p>The namespace.js just defines a namespace() function in order that the other stuff can be namespaced properly:</p>
<p><pre class="brush: jscript;">
namespace = function(namespaceString) {
  var parts = namespaceString.split('.'),
  parent = window,
  currentPart = '';

  for(var i = 0, length = parts.length; i &lt; length; i++) {
    currentPart = parts[i];
    parent[currentPart] = parent[currentPart] || {};
    parent = parent[currentPart];
  }
  return parent;
}
</pre></p>
<p>Using this, the other script files define &#8220;util&#8221; and &#8220;generic&#8221; as aliases for a fully-qualified hierarchy:</p>
<p><pre class="brush: jscript;">
var util = namespace('org.apache.isis.viewer.json.jqmobile.util');
var generic = namespace('org.apache.isis.viewer.json.jqmobile.generic');
</pre></p>
<p>We&#8217;ll dig into the Javascript some more in a moment, but the next thing we should look at is the index.html.  JQueryMobile works by serving a single div&#8217;s at a time, and does all the animation between those div&#8217;s.  In some apps those div&#8217;s could be pulled down from a server dynamically; in the case of this app, though, all the div&#8217;s we need are already within the index.html:</p>
<p><pre class="brush: xml;">
&lt;body id=&quot;pageHolder&quot;&gt;
  &lt;div data-role=&quot;page&quot; id=&quot;home&quot;&gt; ... &lt;/div&gt;
  &lt;div data-role=&quot;page&quot; id=&quot;genericListView&quot;&gt; ... &lt;/div&gt;
  &lt;div data-role=&quot;page&quot; id=&quot;genericDomainObjectView&quot;&gt; ... &lt;/div&gt;
  &lt;div data-role=&quot;page&quot; id=&quot;genericObjectCollectionView&quot;&gt; ... &lt;/div&gt;
&lt;/body&gt;
</pre></p>
<p>When we load the index.html initially into the browser, JQuery automatically shows the first div.  In our case this is the home div:</p>
<p><pre class="brush: xml;">
&lt;div data-role=&quot;page&quot; id=&quot;home&quot;&gt;

  &lt;div data-role=&quot;header&quot;&gt;
    &lt;h1&gt;Home&lt;/h1&gt;
  &lt;/div&gt;

  &lt;div data-role=&quot;content&quot;&gt;
    &lt;br/&gt;
    &lt;button&gt;Todays Tasks&lt;/button&gt;
    &lt;ul data-role=&quot;listview&quot; class=&quot;tasks&quot;&gt;&lt;/ul&gt;
  &lt;/div&gt;

  &lt;script class=&quot;tmpl&quot; type=&quot;text/x-jquery-tmpl&quot;&gt;
    &lt;li&gt;
      &lt;a href=&quot;${href}&quot;&gt;${title}&lt;/a&gt;
    &lt;/li&gt;
  &lt;/script&gt;

  &lt;script type=&quot;text/javascript&quot;&gt;
    $(&quot;#home button&quot;).click(function(){
      $.mobile.changePage(&quot;../services/toDoItems/actions/toDosForToday/invoke&quot;, &quot;pop&quot;)
    });
  &lt;/script&gt;
&lt;/div&gt;
</pre></p>
<p>This renders a single button on the page.  The inline Javascript binds that to a JQueryMobile function to change page to the provided URL.  </p>
<p>As you can probably guess, that URL actually corresponds to the &#8220;toDosForToday&#8221;  action provided by the ToDoItems domain service.  In the normal scheme of things, if that URL served up a div, then JQueryMobile would automatically bring that div into the browser&#8217;s DOM, and render it.  For our app, though, things are a little more complex, because invoking that URL will retrieve JSON.  What we need to do is to use that JSON to generate a div and then transition to it. </p>
<p>The hook for doing this lives within app.js:</p>
<p><pre class="brush: jscript;">
  $(document).bind(&quot;pagebeforechange&quot;, generic.submitRenderAndNavigate);
</pre></p>
<p>This will cause the page transition ($.mobile.changePage) that we requested in the Javascript earlier to actually call the generic.submitRenderAndNavigate() function.  You can find this function in generic.js:</p>
<p><pre class="brush: jscript;">
generic.submitRenderAndNavigate = function(e, pageChangeData) {
  if (typeof pageChangeData.toPage !== &quot;string&quot;) {
    return;
  }

  var url = $.mobile.path.parseUrl(pageChangeData.toPage)
  var urlHref = generic.extract(url.href)
  if(!urlHref) {
    return;
  }

  generic.submitAndRender(urlHref, pageChangeData);
  e.preventDefault();
}
</pre></p>
<p>The function can be called by JQueryMobile in two different ways: either the pageChangeData.toPage is a string, or it is an in-memory page object.  We intercept the former case (checking that the URL is parseable), and then delegate off to generic.submitAndRender() to do the ajax etc.  The call to e.preventDefault() suppresses JQueryMobile&#8217;s usual page handling.</p>
<p>We&#8217;re going to look at generic.submitAndRender() in a second, but for now it&#8217;s worth understanding that the end result of that processing is a page object.  This is given back to JQueryMobile, which then calls back into this function.  The second time around the function just returns; because in this flow the e.preventDefault() is not called, JQueryMobile does its usual page transitions.</p>
<p>But, let&#8217;s look to see how generic.submitAndRender() function ends up generating the page.  For a start, this is the method where the ajax call gets made:</p>
<p><pre class="brush: jscript;">
generic.submitAndRender = function(urlHref, pageChangeData) {
  $.ajax({
    url : urlHref,
    dataType : 'json',
    success : function(json, str, xhr) {
      var contentType = xhr.getResponseHeader(&quot;Content-Type&quot;);
      var handler = generic.handlers[contentType];
      if(!handler) {
        alert(&quot;unable to handle response&quot;)
        return;
      }
      var pageAndOptions = handler(urlHref, pageChangeData, json, xhr)
     $.mobile.changePage(pageAndOptions.page, pageAndOptions.options);
   }
 })
}
</pre></p>
<p>The example given here is only a demo, so there&#8217;s no sad-case failure handling.  But assuming that the ajax call completes, the success callback looks up a<br />
handler function based on the returned &#8220;Content-Type&#8221;.  Here&#8217;s the lookup table:</p>
<p><pre class="brush: jscript;">
generic.handlers = {
  &quot;application/json;profile=\&quot;urn:org.restfulobjects/domainobject\&quot;&quot;: generic.handleDomainObjectRepresentation,
  &quot;application/json;profile=\&quot;urn:org.restfulobjects/list\&quot;&quot;: generic.handleListRepresentation,
  &quot;application/json;profile=\&quot;urn:org.restfulobjects/objectcollection\&quot;&quot;: generic.handleObjectCollectionRepresentation,
  &quot;application/json;profile=\&quot;urn:org.restfulobjects/actionresult\&quot;&quot;: generic.handleActionResultRepresentation
}
</pre></p>
<p>This looking up of the relevant handler is the heart of the app; using it we can handle representations of domain objects, a list, or a domain object collection, or an action result.</p>
<p>Since the demo app initially starts by invoking an action, let&#8217;s look at the generic.handleActionResultRepresentation():</p>
<p><pre class="brush: jscript;">
generic.handleActionResultRepresentation = function(urlHref, pageChangeData, json, xhr) {
  var resultType = json.resulttype
  var handler = generic.actionResultHandlers[resultType];
  if(!handler) {
    alert(&quot;unable to handle result type&quot;)
    return;
  } 
  return handler(urlHref, pageChangeData, json.result, xhr)
}
</pre></p>
<p>As you can see, this also looks up a handler, this time based on the json.resultType of the returned json.result:</p>
<p><pre class="brush: jscript;">
generic.actionResultHandlers = {
  &quot;object&quot;: generic.handleDomainObjectRepresentation,
  &quot;list&quot;: generic.handleListRepresentation
}
</pre></p>
<p>Perhaps no surprise, the handler functions that the action result handler delegates to one-and-the-same as those we noted earlier.  So let&#8217;s look at generic.handleListRepresentation in more detail (starting there simply because that&#8217;s what the demo app does when you invoke the &#8220;todaysTasks&#8221; service action):</p>
<p><pre class="brush: jscript;">
generic.handleListRepresentation = function(urlHref, pageChangeData, json, xhr) {

  var page = $(&quot;#genericListView&quot;);
  var header = page.children(&quot;:jqmData(role=header)&quot;);
  var content = page.children(&quot;:jqmData(role=content)&quot;);

  var items = generic.itemLinks(json.value)

  header.find(&quot;h1&quot;).html(&quot;Objects&quot;);

  var div = page.find(&quot;ul&quot;);
  var templateDiv = page.find(&quot;.tmpl&quot;);

  util.applyTemplateDiv(items, div, templateDiv);

  page.page();
  content.find( &quot;:jqmData(role=listview)&quot; ).listview(&quot;refresh&quot;);
  page.trigger(&quot;create&quot;);

  return generic.pageAndOptions(page, &quot;genericListView&quot;, urlHref)
}
</pre></p>
<p>The function uses a helper function generic.itemLinks to build a list of link objects.  Then, we identify the template script $(&#8220;#genericListView .tmpl&#8221;), and pass both to the util.applyTemplateDiv helper function.  This in turn calls the jQuery.tmpl library to do the heavy lifting.  </p>
<p>Here&#8217;s the HTML div that it works against:</p>
<p><pre class="brush: xml;">
&lt;div data-role=&quot;page&quot; id=&quot;genericListView&quot;&gt;

  &lt;div data-role=&quot;header&quot;&gt;
    &lt;a data-icon=&quot;back&quot; data-rel=&quot;back&quot;&gt;Back&lt;/a&gt;
    &lt;h1&gt;List&lt;/h1&gt;
  &lt;/div&gt;

  &lt;div data-role=&quot;content&quot;&gt;
    &lt;br/&gt;
    &lt;ul data-filter=&quot;true&quot; data-role=&quot;listview&quot;&gt;&lt;/ul&gt;
  &lt;/div&gt;

  &lt;script class=&quot;tmpl&quot; type=&quot;text/x-jquery-tmpl&quot;&gt;
    &lt;li&gt;
      &lt;a href=&quot;${href}&quot;&gt;${title}&lt;/a&gt;
    &lt;/li&gt;
  &lt;/script&gt;
&lt;/div&gt;
</pre></p>
<p>The href&#8217;s of the link objects are formulated such that, when followed, they will again trigger the generic.submitRenderAndNavigate() function.  In this way, we are able to walk between (the representations of) connected domain objects.</p>
<p>Once the content has been generated, we call a bunch of JQueryMobile functions (page.page() and so on) to tell the framework to &#8220;enhance&#8221; the generated page.   And once that has been done, we call the generic.pageAndOptions() function to create the in-memory page.  We&#8217;ll drill into that helper shortly.</p>
<p>Let&#8217;s now have a look at the biggest of the handlers, the generic.handleDomainObjectRepresentation:</p>
<p><pre class="brush: jscript;">
generic.handleDomainObjectRepresentation = function(urlHref, pageChangeData, json, xhr) {

  var page = $(&quot;#genericDomainObjectView&quot;);
  var header = page.children(&quot;:jqmData(role=header)&quot;);
  var content = page.children(&quot;:jqmData(role=content)&quot;);

  header.find(&quot;h1&quot;).html(json.title);

  // value properties
  var valueProperties = json.members.filter(function(item) {
    return item.memberType === &quot;property&quot; &amp;&amp; !item.value.href;
  });

  valueProperties = $.map( valueProperties, function(value, i) {
    var dataType = generic.dataTypeFor(value)
    return {
      &quot;id&quot;: value.id,
      &quot;value&quot;: value.value,
      &quot;dataTypeIsString&quot;: dataType === &quot;string&quot;,
      &quot;dataTypeIsBoolean&quot;: dataType === &quot;boolean&quot;
    }
  });

  var valuePropertiesDiv = page.children(&quot;:jqmData(role=content)&quot;).find(&quot;.valueProperties&quot;);
  var valuePropertiesTemplateDiv = page.children(&quot;.valueProperties-tmpl&quot;);
  util.applyTemplateDiv(valueProperties, valuePropertiesDiv, valuePropertiesTemplateDiv);

  // reference properties
  var referenceProperties = json.members.filter(function(item) {
    return item.memberType === &quot;property&quot; &amp;&amp; item.value.href;
  });

  var referencePropertiesList = page.children(&quot;:jqmData(role=content)&quot;).find(&quot;.referenceProperties&quot;);
  var referencePropertiesTemplateDiv = page.children(&quot;.referenceProperties-tmpl&quot;);
  util.applyTemplateDiv(referenceProperties, referencePropertiesList, referencePropertiesTemplateDiv);

  var collections = json.members.filter(function(item) {
    return item.memberType === &quot;collection&quot;;
  }).map(function(value, i) {
    var href = util.grepLink(value.links, &quot;details&quot;).href
    return {
      &quot;hrefUrlEncoded&quot; : util.urlencode(value.links[0].href),
      &quot;id&quot; : value.id,
      &quot;href&quot; : value.links[0].href
    }
  });

  // collections
  var collectionsList = page.children(&quot;:jqmData(role=content)&quot;).find(&quot;.collections&quot;);
  var collectionsTemplateDiv = page.children(&quot;.collections-tmpl&quot;);
  util.applyTemplateDiv(collections, collectionsList, collectionsTemplateDiv);

  page.page();
  content.find( &quot;:jqmData(role=listview)&quot; ).listview(&quot;refresh&quot;);
  page.trigger(&quot;create&quot;);

  return generic.pageAndOptions(page, &quot;genericDomainObjectView&quot;, urlHref)
}
</pre></p>
<p>Although this handler is longer, it&#8217;s doing much the same thing as the list handler.  Specifically, it processes the JSON into three lists, one for value properties, one for references properties, and one for collections.  For each, it uses the util.applyTemplateDiv function again in order to render against the corresponding templates, $(&#8220;#genericDomainObjectView .valueProperties-tmpl&#8221;) and so forth.</p>
<p>The corresponding div in the HTML is:</p>
<p><pre class="brush: xml;">
&lt;div data-role=&quot;page&quot; id=&quot;genericDomainObjectView&quot;&gt;

  &lt;div data-role=&quot;header&quot;&gt;
    &lt;a data-icon=&quot;back&quot; data-rel=&quot;back&quot;&gt;Back&lt;/a&gt;
    &lt;h1&gt;Object&lt;/h1&gt;
  &lt;/div&gt;

  &lt;div data-role=&quot;content&quot;&gt;
    &lt;div class=&quot;valueProperties&quot;&gt;&lt;/div&gt;
    &lt;br/&gt;
    &lt;p&gt;References&lt;/p&gt;
    &lt;ul data-role=&quot;listview&quot; data-inset=&quot;true&quot; class=&quot;referenceProperties&quot;&gt;&lt;/ul&gt;
    &lt;br/&gt;
    &lt;p&gt;Collections&lt;/p&gt;
    &lt;ul data-role=&quot;listview&quot; data-inset=&quot;true&quot; class=&quot;collections&quot;&gt;&lt;/ul&gt;
  &lt;/div&gt;

  &lt;script class=&quot;valueProperties-tmpl&quot; type=&quot;text/x-jquery-tmpl&quot;&gt;
  {{if dataTypeIsString}}
    &lt;label for=&quot;${id}&quot;&gt;${id}:&lt;/label&gt;
    &lt;input type=&quot;text&quot; name=&quot;${id}&quot; id=&quot;${id}&quot; value=&quot;${value}&quot; placeholder=&quot;${id}&quot; class=&quot;required&quot;/&gt;
  {{/if}}
  {{if dataTypeIsBoolean}}
    &lt;div data-role=&quot;fieldcontain&quot;&gt;
      &lt;fieldset data-role=&quot;controlgroup&quot;&gt;
        &lt;legend&gt;${id}?&lt;/legend&gt;
        &lt;input type=&quot;checkbox&quot; name=&quot;${id}&quot; id=&quot;${id}&quot; value=&quot;${value}&quot; class=&quot;required&quot;/&gt;
        &lt;label for=&quot;${id}&quot;&gt;${id}&lt;/label&gt;
      &lt;/fieldset&gt;
    &lt;/div&gt;
  {{/if}}
  &lt;/script&gt;

  &lt;script class=&quot;referenceProperties-tmpl&quot; type=&quot;text/x-jquery-tmpl&quot;&gt;
    &lt;li&gt;
      &lt;a data-transition=&quot;slide&quot; href=&quot;${value.href}&quot;&gt;
        &lt;p&gt;${id}&lt;/p&gt;
        &lt;p&gt;&lt;b&gt;${value.title}&lt;/b&gt;&lt;/p&gt;
      &lt;/a&gt;
    &lt;/li&gt;
  &lt;/script&gt;

  &lt;script class=&quot;collections-tmpl&quot; type=&quot;text/x-jquery-tmpl&quot;&gt;
    &lt;li&gt;
      &lt;a data-transition=&quot;slideup&quot; href=&quot;${href}&quot;&gt;${id}&lt;/a&gt;
    &lt;/li&gt;
  &lt;/script&gt;
&lt;/div&gt;
</pre></p>
<p>The template for value properties is, admittedly, a little ugly: it uses the {{if}} template in order to bring in either a checkbox or a textbox widget dependent on the value&#8217;s type.  A more fully-featured application would probably generalize this to use subtemplates (and might even be extensible) to allow richer value types such as images or maps to be rendered accordingly.</p>
<p>The last of our handlers, generic.handleObjectCollectionRepresentation, is very similar to the generic.handleListRepresentation:</p>
<p><pre class="brush: jscript;">
generic.handleObjectCollectionRepresentation = function(urlHref, pageChangeData, json, xhr) {
  var page = $(&quot;#genericObjectCollectionView&quot;);
  var header = page.children(&quot;:jqmData(role=header)&quot;);
  var content = page.children(&quot;:jqmData(role=content)&quot;);

  var items = generic.itemLinks(json.value)

  var parentTitle = util.grepLink(json.links, &quot;up&quot;).title

  var collectionId = json.id;
  header.find(&quot;h1&quot;).html(collectionId + &quot; for &quot; + parentTitle);

  var div = page.find(&quot;ul&quot;);
  var templateDiv = page.find(&quot;.tmpl&quot;);
  util.applyTemplateDiv(items, div, templateDiv);

  page.page();
  content.find( &quot;:jqmData(role=listview)&quot; ).listview(&quot;refresh&quot;);
  page.trigger(&quot;create&quot;);

  return generic.pageAndOptions(page, &quot;genericObjectCollectionView&quot;, urlHref, &quot;slideup&quot;)
}
</pre></p>
<p>It&#8217;s corresponding div in the HTML is: </p>
<p><pre class="brush: xml;">
&lt;div data-role=&quot;page&quot; id=&quot;genericObjectCollectionView&quot;&gt;

  &lt;div data-role=&quot;header&quot;&gt;
    &lt;a data-icon=&quot;back&quot; data-rel=&quot;back&quot;&gt;Back&lt;/a&gt;
    &lt;h1&gt;Collection&lt;/h1&gt;
  &lt;/div&gt;

  &lt;div data-role=&quot;content&quot;&gt;
    &lt;br/&gt;
    &lt;ul data-filter=&quot;true&quot; data-role=&quot;listview&quot;&gt;&lt;/ul&gt;
  &lt;/div&gt;

  &lt;script class=&quot;tmpl&quot; type=&quot;text/x-jquery-tmpl&quot;&gt;
    &lt;li&gt;
      &lt;a href=&quot;${href}&quot;&gt;${title}&lt;/a&gt;
    &lt;/li&gt;
  &lt;/script&gt;
&lt;/div&gt;
</pre></p>
<p>There&#8217;s just a couple more functions I want to go through.  The first is generic.pageAndOptions(); this is the function, if you recall, that creates and hands back the in-memory page option:</p>
<p><pre class="brush: jscript;">
generic.pageAndOptions = function(page, view, dataUrl, transition) {
  var pageAndOptions = {
    &quot;page&quot;: page,
    &quot;options&quot;: {
      &quot;dataUrl&quot;: &quot;#&quot; + view + &quot;?dataUrl=&quot; + util.urlencode(dataUrl),
      &quot;allowSamePageTransition&quot;: true,
      &quot;transition&quot;: transition
    }
  }
  return pageAndOptions
}
</pre></p>
<p>This little function returns a tuple consisting of the newly created page, along with an options object that has a dataUrl.  This options.dataUrl property that is important, because it is what appears in the browser&#8217;s address bar.  </p>
<p>As you can see, I&#8217;ve designed it to include both the view name (as an anchor), along with a ?dataUrl query param.  Why so?  Well, it allows the page to be bookmarked, so that the user can come back to any domain object rather than starting from home.  The little bit of processing to do this is in app.js:</p>
<p><pre class="brush: jscript;">
// if user manually refreshes page for domain object, then re-retrieve
var locationHref = location.href;
if(locationHref.indexOf(&quot;genericDomainObjectView&quot;) != -1) {
  var urlHref = generic.extract(locationHref);
  generic.submitAndRender(urlHref, &quot;pop&quot;);
} else {
  $.mobile.changePage($(&quot;#home&quot;))
}
</pre></p>
<p>Here we try to extract the dataUrl from the locationHref, in other words the dataUrl query param.  If successful, we call generic.submitAndRender(), as described above.  Or, if the dataUrl cannot be interpreted, then we just revert back to the home page.</p>
<p>I hope the above run-thru has been useful.  Bear in mind that this is far from production quality, and there could be bugs in it (in fact, I&#8217;m pretty sure that there are&#8230;).  And there are, of course, plenty of things that this demo doesn&#8217;t yet support &#8211; invoking actions, for one.  </p>
<p>In the future we expect that there&#8217;ll be a fully fledged generic REST client.  In the meantime, though, hopefully this is a good demonstrator for the potential of the <a href="http://restfulobjects.org" title="Restful Objects" target="_blank">Rest API</a> that ships with Isis.</p>
<p>PS: If you&#8217;re interested in the source code, you can either just save the files from the online demo (index.html, app.js, generic.js, util.js, namespace.js), or you can browse to the <a href="http://svn.apache.org/repos/asf/incubator/isis/trunk/examples/onlinedemo/webapp/src/main/webapp/mobile/" title="Apache Isis subversion repo" target="_blank">Isis subversion repository</a>.</p>
<br />Filed under: <a href='http://danhaywood.com/category/naked-objects-pattern/apache-isis/'>apache isis</a>, <a href='http://danhaywood.com/category/javascript/jquerymobile/'>jquerymobile</a>, <a href='http://danhaywood.com/category/restful-objects/'>restful objects</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/danhaywood.wordpress.com/900/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/danhaywood.wordpress.com/900/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/danhaywood.wordpress.com/900/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/danhaywood.wordpress.com/900/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/danhaywood.wordpress.com/900/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/danhaywood.wordpress.com/900/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/danhaywood.wordpress.com/900/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/danhaywood.wordpress.com/900/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/danhaywood.wordpress.com/900/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/danhaywood.wordpress.com/900/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/danhaywood.wordpress.com/900/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/danhaywood.wordpress.com/900/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/danhaywood.wordpress.com/900/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/danhaywood.wordpress.com/900/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=danhaywood.com&amp;blog=25721749&amp;post=900&amp;subd=danhaywood&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://danhaywood.com/2012/02/01/jquerymobile-demo-app-walkthr/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/204ef8a2259ebe0716f985f96c1c350d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">danhaywood</media:title>
		</media:content>
	</item>
		<item>
		<title>JQueryMobile on the Apache Isis&#8217;REST API</title>
		<link>http://danhaywood.com/2012/01/20/jquerymobile-on-apache-isis-rest-api/</link>
		<comments>http://danhaywood.com/2012/01/20/jquerymobile-on-apache-isis-rest-api/#comments</comments>
		<pubDate>Fri, 20 Jan 2012 19:58:57 +0000</pubDate>
		<dc:creator>danhaywood</dc:creator>
				<category><![CDATA[apache isis]]></category>
		<category><![CDATA[jquerymobile]]></category>
		<category><![CDATA[restful objects]]></category>

		<guid isPermaLink="false">http://danhaywood.com/?p=888</guid>
		<description><![CDATA[We&#8217;re currently working towards 0.2.0 of Apache Isis (incubating), and one of the most significant new areas of functionality is the REST API that it automatically provides through the json-viewer component.  As you can probably guess from the name, this viewer provides a REST interface which exposes JSON representations of the domain object models. However, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=danhaywood.com&amp;blog=25721749&amp;post=888&amp;subd=danhaywood&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>We&#8217;re currently working towards 0.2.0 of <a title="Apache Isis (incubating)" href="http://incubator.apache.org/isis" target="_blank">Apache Isis</a> (incubating), and one of the most significant new areas of functionality is the REST API that it automatically provides through the json-viewer component.  As you can probably guess from the name, this viewer provides a REST interface which exposes JSON representations of the domain object models.</p>
<p>However, JSON representations do not a user interface make; instead the idea is that the developer will write either custom or generic UIs to consume those representations.  As an example of such an app (and by way of learning a little more Javascript) I&#8217;ve put together a very simple mobile app using the recently-released <a title="JQueryMobile" href="http://jquerymobile.com" target="_blank">JQueryMobile</a> framework.</p>
<p><span id="more-888"></span></p>
<p>For now, this mobile app is part of the Apache Isis online demo, which you can download as a <a title="Isis online demo WAR" href="https://sites.google.com/a/haywood-associates.co.uk/restfulobjects/files/onlinedemo-webapp-0.2.0-incubating-SNAPSHOT.war" target="_blank">WAR</a> or as a <a title="Isis online demo WAR (self-hosting)" href="https://sites.google.com/a/haywood-associates.co.uk/restfulobjects/files/onlinedemo-webapp-0.2.0-incubating-SNAPSHOT-jetty-console.war" target="_blank">self-hosted WAR</a> (run using java -jar &#8230;).  By the time you read this it may well also be available online <a title="Apache Isis online demo" href="http://mmyco.co.uk:8180/isis-onlinedemo/" target="_blank">here</a>.</p>
<p>To try out the demo, the first thing you&#8217;ll need to do is to register a user through the HTML viewer, and then reset the demo fixtures to create some initial data for your newly-created user.  The demo has full documentation on how to do this, so I won&#8217;t repeat it here.</p>
<p>Once you&#8217;ve done that, you&#8217;ll be able to browse to the home page for the mobile app (under mobile/index.html); you should see a home page showing just a single button:</p>
<p><a href="http://danhaywood.files.wordpress.com/2012/01/jqm-home.png"><img class="aligncenter size-medium wp-image-893" title="jqm-home" src="http://danhaywood.files.wordpress.com/2012/01/jqm-home.png?w=173&#038;h=300" alt="" width="173" height="300" /></a></p>
<p>When you press that button, you&#8217;ll find that your prompted for a username/password; this is the Basic Authentication that is used to secure the demo app.  Enter the username/password that you just entered.</p>
<p>With the username/password successfully entered, you should see a list of todo-items; these are the result of a domain service action ( ToDoItems#todaysTasks(), to be exact):</p>
<p><a href="http://danhaywood.files.wordpress.com/2012/01/jqm-list.png"><img class="aligncenter size-medium wp-image-894" title="jqm-list" src="http://danhaywood.files.wordpress.com/2012/01/jqm-list.png?w=173&#038;h=300" alt="" width="173" height="300" /></a></p>
<p>Thereafter everything in the app is generic; in other words it is able to display any domain object that is in the model.  For example, click on a link and you&#8217;ll find yourself viewing one of the ToDoItems:</p>
<p><a href="http://danhaywood.files.wordpress.com/2012/01/jqm-object.png"><img class="aligncenter size-medium wp-image-895" title="jqm-object" src="http://danhaywood.files.wordpress.com/2012/01/jqm-object.png?w=173&#038;h=300" alt="" width="173" height="300" /></a></p>
<p>Similarly, you can look at the contents of the &#8216;similarItems&#8217;collection:</p>
<p><a href="http://danhaywood.files.wordpress.com/2012/01/jqm-collection.png"><img class="aligncenter size-medium wp-image-892" title="jqm-collection" src="http://danhaywood.files.wordpress.com/2012/01/jqm-collection.png?w=173&#038;h=300" alt="" width="173" height="300" /></a></p>
<p>And, from there, you can navigate to other domain objects, and so on.</p>
<p>This little webapp consists of ~200 lines of HTML (mobile/index.html), about ~300 lines of custom Javascript (mobile/app.js, mobile/generic.js, mobile/util.js and mobile/namespace.js).  The rest of the Javascript magic is JQuery, JQueryMobile and JQuery-tmpl.</p>
<p>In the <a href="http://danhaywood.com/2012/02/01/jquerymobile-demo-app-walkthr/" title="JQueryMobile demo app walk-thru" target="_blank">next post</a> I&#8217;ll go through the source code and dissect it a little; in the meantime though you&#8217;re welcome to reverse-engineer it yourself.</p>
<p>As ever, comments welcome.</p>
<br />Filed under: <a href='http://danhaywood.com/category/naked-objects-pattern/apache-isis/'>apache isis</a>, <a href='http://danhaywood.com/category/javascript/jquerymobile/'>jquerymobile</a>, <a href='http://danhaywood.com/category/restful-objects/'>restful objects</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/danhaywood.wordpress.com/888/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/danhaywood.wordpress.com/888/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/danhaywood.wordpress.com/888/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/danhaywood.wordpress.com/888/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/danhaywood.wordpress.com/888/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/danhaywood.wordpress.com/888/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/danhaywood.wordpress.com/888/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/danhaywood.wordpress.com/888/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/danhaywood.wordpress.com/888/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/danhaywood.wordpress.com/888/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/danhaywood.wordpress.com/888/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/danhaywood.wordpress.com/888/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/danhaywood.wordpress.com/888/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/danhaywood.wordpress.com/888/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=danhaywood.com&amp;blog=25721749&amp;post=888&amp;subd=danhaywood&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://danhaywood.com/2012/01/20/jquerymobile-on-apache-isis-rest-api/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/204ef8a2259ebe0716f985f96c1c350d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">danhaywood</media:title>
		</media:content>

		<media:content url="http://danhaywood.files.wordpress.com/2012/01/jqm-home.png?w=173" medium="image">
			<media:title type="html">jqm-home</media:title>
		</media:content>

		<media:content url="http://danhaywood.files.wordpress.com/2012/01/jqm-list.png?w=173" medium="image">
			<media:title type="html">jqm-list</media:title>
		</media:content>

		<media:content url="http://danhaywood.files.wordpress.com/2012/01/jqm-object.png?w=173" medium="image">
			<media:title type="html">jqm-object</media:title>
		</media:content>

		<media:content url="http://danhaywood.files.wordpress.com/2012/01/jqm-collection.png?w=173" medium="image">
			<media:title type="html">jqm-collection</media:title>
		</media:content>
	</item>
		<item>
		<title>Updating Visual Studio project references from NuGet packages.config</title>
		<link>http://danhaywood.com/2012/01/04/updating-visual-studio-project-references-from-nuget-packages-config/</link>
		<comments>http://danhaywood.com/2012/01/04/updating-visual-studio-project-references-from-nuget-packages-config/#comments</comments>
		<pubDate>Wed, 04 Jan 2012 11:04:25 +0000</pubDate>
		<dc:creator>danhaywood</dc:creator>
				<category><![CDATA[powershell]]></category>

		<guid isPermaLink="false">http://danhaywood.com/?p=878</guid>
		<description><![CDATA[(Among other things), NuGet offers an alternative way of managing project references in Visual Studio. The usual flow is to right-click on References, and choose &#8220;Manage NuGet Packages&#8221;.  The NuGet dialog then pops up, showing available packages.  Once you&#8217;ve selected a package, NuGet will: download the package to your repository (if required) update the VS [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=danhaywood.com&amp;blog=25721749&amp;post=878&amp;subd=danhaywood&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>(Among other things), NuGet offers an alternative way of managing project references in Visual Studio.</p>
<p>The usual flow is to right-click on References, and choose &#8220;Manage NuGet Packages&#8221;.  The NuGet dialog then pops up, showing available packages.  Once you&#8217;ve selected a package, NuGet will:</p>
<ul>
<li>download the package to your repository (if required)</li>
<li>update the VS project file (.csproj or .vbproj etc)</li>
<li>update its own packages.config file.</li>
</ul>
<p>What if things get out-of-sync, though, eg you&#8217;ve moved your repository so that all the reference hints in the .csproj file are wrong?  It&#8217;d be nice to be able to use the info in the packages.config to automatically resync the .csproj file.</p>
<p>Here&#8217;s one brute-force way to do this (from within the Package Manager console in VS):</p>
<p><span id="more-878"></span></p>
<p><pre class="brush: powershell;">
get-project -all | %{
  $proj = $_ ;
  get-package -project $proj.name | %{
    uninstall-package -projectname $proj.name -id $_.id -version $_.version -RemoveDependencies -force ;
   install-package -projectname $proj.name -id $_.id -version $_.version
  }
}
</pre></p>
<p>Actually, I have a suspicion there&#8217;s a flag for one of the NuGet commands to do this much more simply; but my google-fu failed me on this occasion.  If you know of a better way, please comment below.</p>
<br />Filed under: <a href='http://danhaywood.com/category/random/powershell/'>powershell</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/danhaywood.wordpress.com/878/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/danhaywood.wordpress.com/878/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/danhaywood.wordpress.com/878/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/danhaywood.wordpress.com/878/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/danhaywood.wordpress.com/878/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/danhaywood.wordpress.com/878/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/danhaywood.wordpress.com/878/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/danhaywood.wordpress.com/878/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/danhaywood.wordpress.com/878/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/danhaywood.wordpress.com/878/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/danhaywood.wordpress.com/878/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/danhaywood.wordpress.com/878/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/danhaywood.wordpress.com/878/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/danhaywood.wordpress.com/878/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=danhaywood.com&amp;blog=25721749&amp;post=878&amp;subd=danhaywood&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://danhaywood.com/2012/01/04/updating-visual-studio-project-references-from-nuget-packages-config/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/204ef8a2259ebe0716f985f96c1c350d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">danhaywood</media:title>
		</media:content>
	</item>
		<item>
		<title>DB unit testing with dbUnit, JSON, HSQLDB and JUnit Rules</title>
		<link>http://danhaywood.com/2011/12/20/db-unit-testing-with-dbunit-json-hsqldb-and-junit-rules/</link>
		<comments>http://danhaywood.com/2011/12/20/db-unit-testing-with-dbunit-json-hsqldb-and-junit-rules/#comments</comments>
		<pubDate>Tue, 20 Dec 2011 18:06:53 +0000</pubDate>
		<dc:creator>danhaywood</dc:creator>
				<category><![CDATA[tdd]]></category>

		<guid isPermaLink="false">http://danhaywood.com/?p=867</guid>
		<description><![CDATA[In this week&#8217;s run of my TDD course, I thought it would be interesting to write a little fixture to make it easier to use dbUnit.  My original thought was just to teach dbUnit about JSON, but it turns out that Lieven Doclo has done that already.  So I decided to go a step further [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=danhaywood.com&amp;blog=25721749&amp;post=867&amp;subd=danhaywood&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this week&#8217;s run of my TDD course, I thought it would be interesting to write a little fixture to make it easier to use <a href="http://www.dbunit.org/" target="_blank">dbUnit</a>.  My original thought was just to teach dbUnit about JSON, but it turns out that <a href="http://www.insaneprogramming.be/?p=105" target="_blank">Lieven Doclo</a> has done that already.  So I decided to go a step further and also combine dbUnit with <a href="http://kentbeck.github.com/junit/javadoc/latest/org/junit/rules/MethodRule.html" target="_blank">JUnit Rules</a>, and provide automatic bootstrapping of an <a href="http://hsqldb.org/" target="_blank">HSQLDB</a> in-memory object store.</p>
<p><span id="more-867"></span></p>
<p>The following test shows what I ended up with:</p>
<p><pre class="brush: java;">
package com.danhaywood.tdd.dbunit.test;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

import java.sql.ResultSet;
import java.sql.Statement;

import org.dbunit.Assertion;
import org.dbunit.dataset.ITable;
import org.hsqldb.jdbcDriver;
import org.junit.Rule;
import org.junit.Test;

import com.danhaywood.tdd.dbunit.DbUnitRule;
import com.danhaywood.tdd.dbunit.DbUnitRule.Ddl;
import com.danhaywood.tdd.dbunit.DbUnitRule.JsonData;

public class DbUnitRuleExample {

    @Rule
    public DbUnitRule dbUnit = new DbUnitRule(
            DbUnitRuleExample.class, jdbcDriver.class,
            &quot;jdbc:hsqldb:file:src/test/resources/testdb&quot;, &quot;SA&quot;, &quot;&quot;);

@Ddl(&quot;customer.ddl&quot;)
    @JsonData(&quot;customer.json&quot;)
    @Test
    public void update_lastName() throws Exception {

        // when
        Statement statement = dbUnit.getConnection().createStatement();
        statement.executeUpdate(&quot;update customer set last_name='Bloggs' where id=2&quot;);

        // then (verify directly)
        ResultSet rs2 = dbUnit.executeQuery(&quot;select last_name from customer where id = 2&quot;);
        assertThat(rs2.next(), is(true));
        assertThat(rs2.getString(&quot;last_name&quot;), equalTo(&quot;Bloggs&quot;));

        // then (verify using datasets)
        ITable actualTable = dbUnit.createQueryTable(&quot;customer&quot;, &quot;select * from customer order by id&quot;);
        ITable expectedTable = dbUnit.jsonDataSet(&quot;customer-updated.json&quot;).getTable(&quot;customer&quot;);

        Assertion.assertEquals(expectedTable, actualTable);
    }
}
</pre></p>
<p>where <tt>customer.ddl</tt> is:</p>
<p><pre class="brush: sql;">
drop table customer if exists;
create table customer (
	id         int         not null primary key
   ,first_name varchar(30) not null
   ,initial    varchar(1)  null
   ,last_name  varchar(30) not null
)
</pre></p>
<p>and <tt>customer.json</tt> (the initial data set) is:</p>
<p><pre class="brush: jscript;">
{
  &quot;customer&quot;:
	  [
	    {
	      &quot;id&quot;: 1,
	      &quot;first_name&quot;: &quot;John&quot;,
	      &quot;initial&quot;: &quot;K&quot;,
	      &quot;last_name&quot;: &quot;Smith&quot;
	    },
	    {
	      &quot;id&quot;: 2,
	      &quot;first_name&quot;: &quot;Mary&quot;,
	      &quot;last_name&quot;: &quot;Jones&quot;
	    }
	  ]
}
</pre></p>
<p>and <tt>customer-updated.json</tt> (the final data set) is:</p>
<p><pre class="brush: jscript;">
{
  &quot;customer&quot;:
	  [
	    {
	      &quot;id&quot;: 1,
	      &quot;first_name&quot;: &quot;John&quot;,
	      &quot;initial&quot;: &quot;K&quot;,
	      &quot;last_name&quot;: &quot;Smith&quot;
	    },
	    {
	      &quot;id&quot;: 2,
	      &quot;first_name&quot;: &quot;Mary&quot;,
	      &quot;last_name&quot;: &quot;Bloggs&quot;
	    }
	  ]
}
</pre></p>
<p>As you&#8217;ve probably figured out, the <tt>@Ddl</tt> annotation optionally specifies DDL script(s) to run against the database, while the <tt>@JsonData</tt> defines a JSON-formatted dataset.</p>
<p>The actual implementation of the <tt>DbUnitRule</tt> class is:</p>
<p><pre class="brush: java;">
package com.danhaywood.tdd.dbunit;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.dbunit.IDatabaseTester;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITable;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;

import com.google.common.io.Resources;

public class DbUnitRule implements MethodRule {

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.METHOD })
    public static @interface Ddl {
        String[] value();
    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.METHOD })
    public static @interface JsonData {
        String value();
    }

    private final Class&lt;?&gt; resourceBase;

    private IDatabaseTester databaseTester;
    private IDatabaseConnection dbUnitConnection;

    private Connection connection;
    private java.sql.Statement statement;

    public DbUnitRule(Class&lt;?&gt; resourceBase, Class&lt;?&gt; driver, String url, String user, String password) {
        this.resourceBase = resourceBase;
        try {
            databaseTester = new JdbcDatabaseTester(driver.getName(), url, user, password);
            dbUnitConnection = databaseTester.getConnection();
            connection = dbUnitConnection.getConnection();
            statement = connection.createStatement();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {

        return new Statement() {

            @Override
            public void evaluate() throws Throwable {

                try {
                    Ddl ddl = method.getAnnotation(Ddl.class);
                    if (ddl != null) {
                        String[] values = ddl.value();
                        for (String value : values) {
                            executeUpdate(Resources.toString(
                                resourceBase.getResource(value), Charset.defaultCharset()));
                        }
                    }

                    JsonData data = method.getAnnotation(JsonData.class);
                    if (data != null) {
                        IDataSet ds = new JSONDataSet(resourceBase.getResourceAsStream(data.value()));
                        databaseTester.setDataSet(ds);
                    }

                    databaseTester.onSetup();

                    base.evaluate();
                } finally {
                    databaseTester.onTearDown();
                }
            }
        };
    }

    public java.sql.Connection getConnection() {
        return connection;
    }

    public void executeUpdate(String sql) throws SQLException {
        statement.executeUpdate(sql);
    }

    public ResultSet executeQuery(String sql) throws SQLException {
        return statement.executeQuery(sql);
    }

    public IDataSet jsonDataSet(String datasetResource) {
        return new JSONDataSet(resourceBase.getResourceAsStream(datasetResource));
    }

    public ITable createQueryTable(String string, String string2) throws DataSetException, SQLException {
        return dbUnitConnection.createQueryTable(string, string2);
    }
}
</pre></p>
<p>This uses Lieven Doclo&#8217;s JSONDataSet (copied here for your convenience):</p>
<p><pre class="brush: java;">
import org.codehaus.jackson.map.ObjectMapper;
import org.dbunit.dataset.*;
import org.dbunit.dataset.datatype.DataType;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * DBUnit DataSet format for JSON based datasets. It is similar to the flat XML layout,
 * but has some improvements (columns are calculated by parsing the entire dataset, not just
 * the first row). It uses Jackson, a fast JSON processor.
 * &lt;br/&gt;&lt;br/&gt;
 * The format looks like this:
 * &lt;br/&gt;
 * &lt;pre&gt;
 * {
 *    &quot;&amp;lt;table_name&amp;gt;&quot;: [
 *        {
 *             &quot;&amp;lt;column&amp;gt;&quot;:&amp;lt;value&amp;gt;,
 *             ...
 *        },
 *        ...
 *    ],
 *    ...
 * }
 * &lt;/pre&gt;
 * &lt;br/&gt;
 * I.e.:
 * &lt;br/&gt;
 * &lt;pre&gt;
 * {
 *    &quot;test_table&quot;: [
 *        {
 *             &quot;id&quot;:1,
 *             &quot;code&quot;:&quot;JSON dataset&quot;,
 *        },
 *        {
 *             &quot;id&quot;:2,
 *             &quot;code&quot;:&quot;Another row&quot;,
 *        }
 *    ],
 *    &quot;another_table&quot;: [
 *        {
 *             &quot;id&quot;:1,
 *             &quot;description&quot;:&quot;Foo&quot;,
 *        },
 *        {
 *             &quot;id&quot;:2,
 *             &quot;description&quot;:&quot;Bar&quot;,
 *        }
 *    ],
 *    ...
 * }
 * &lt;/pre&gt;
 *
 * @author Lieven DOCLO
 */
public class JSONDataSet extends AbstractDataSet {
    // The parser for the dataset JSON file
    private JSONITableParser tableParser = new JSONITableParser();

    // The tables after parsing
    private List&lt;ITable&gt; tables;

    /**
     * Creates a JSON dataset based on a file
     * @param file A JSON dataset file
     */
    public JSONDataSet(File file) {
        tables = tableParser.getTables(file);
    }

    /**
     * Creates a JSON dataset based on an inputstream
     * @param is An inputstream pointing to a JSON dataset
     */
    public JSONDataSet(InputStream is) {
        tables = tableParser.getTables(is);
    }

    @Override
    protected ITableIterator createIterator(boolean reverse) throws DataSetException {
        return new DefaultTableIterator(tables.toArray(new ITable[tables.size()]));
    }

    private class JSONITableParser {

        private ObjectMapper mapper = new ObjectMapper();

        /**
         * Parses a JSON dataset file and returns the list of DBUnit tables contained in
         * that file
         * @param jsonFile A JSON dataset file
         * @return A list of DBUnit tables
         */
        public List&lt;ITable&gt; getTables(File jsonFile) {
            try {
                return getTables(new FileInputStream(jsonFile));
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }

        /**
         * Parses a JSON dataset input stream and returns the list of DBUnit tables contained in
         * that input stream
         * @param jsonStream A JSON dataset input stream
         * @return A list of DBUnit tables
         */
        @SuppressWarnings(&quot;unchecked&quot;)
        public List&lt;ITable&gt; getTables(InputStream jsonStream) {
            List&lt;ITable&gt; tables = new ArrayList&lt;ITable&gt;();
            try {
                // get the base object tree from the JSON stream
                Map&lt;String, Object&gt; dataset = mapper.readValue(jsonStream, Map.class);
                // iterate over the tables in the object tree
                for (Map.Entry&lt;String, Object&gt; entry : dataset.entrySet()) {
                    // get the rows for the table
                    List&lt;Map&lt;String, Object&gt;&gt; rows = (List&lt;Map&lt;String, Object&gt;&gt;) entry.getValue();
                    ITableMetaData meta = getMetaData(entry.getKey(), rows);
                    // create a table based on the metadata
                    DefaultTable table = new DefaultTable(meta);
                    int rowIndex = 0;
                    // iterate through the rows and fill the table
                    for (Map&lt;String, Object&gt; row : rows) {
                        fillRow(table, row, rowIndex++);
                    }
                    // add the table to the list of DBUnit tables
                    tables.add(table);
                }

            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
            return tables;
        }

        /**
         * Gets the table meta data based on the rows for a table
         * @param tableName The name of the table
         * @param rows The rows of the table
         * @return The table metadata for the table
         */
        private ITableMetaData getMetaData(String tableName, List&lt;Map&lt;String, Object&gt;&gt; rows) {
            Set&lt;String&gt; columns = new LinkedHashSet&lt;String&gt;();
            // iterate through the dataset and add the column names to a set
            for (Map&lt;String, Object&gt; row : rows) {
                for (Map.Entry&lt;String, Object&gt; column : row.entrySet()) {
                    columns.add(column.getKey());
                }
            }
            List&lt;Column&gt; list = new ArrayList&lt;Column&gt;(columns.size());
            // create a list of DBUnit columns based on the column name set
            for (String s : columns) {
                list.add(new Column(s, DataType.UNKNOWN));
            }
            return new DefaultTableMetaData(tableName, list.toArray(new Column[list.size()]));
        }

        /**
         * Fill a table row
         * @param table The table to be filled
         * @param row A map containing the column values
         * @param rowIndex The index of the row to te filled
         */
        private void fillRow(DefaultTable table, Map&lt;String, Object&gt; row, int rowIndex) {
            try {
                table.addRow();
                // set the column values for the current row
                for (Map.Entry&lt;String, Object&gt; column : row.entrySet()) {
                    table.setValue(rowIndex, column.getKey(), column.getValue());

                }
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
}
</pre></p>
<p>The libraries I used for this (ie are dependencies) are:</p>
<ul>
<li>hsqldb 2.2.6</li>
<li>dbunit 2.4.8</li>
<li>jackson 1.9.3</li>
<li>slf4j-api-1.6.4, slf4j-nop-1.6.4</li>
<li>google-guava 10.0.1</li>
<li>junit 4.8</li>
</ul>
<p>As ever, comments welcome.</p>
<br />Filed under: <a href='http://danhaywood.com/category/random/tdd/'>tdd</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/danhaywood.wordpress.com/867/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/danhaywood.wordpress.com/867/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/danhaywood.wordpress.com/867/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/danhaywood.wordpress.com/867/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/danhaywood.wordpress.com/867/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/danhaywood.wordpress.com/867/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/danhaywood.wordpress.com/867/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/danhaywood.wordpress.com/867/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/danhaywood.wordpress.com/867/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/danhaywood.wordpress.com/867/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/danhaywood.wordpress.com/867/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/danhaywood.wordpress.com/867/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/danhaywood.wordpress.com/867/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/danhaywood.wordpress.com/867/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=danhaywood.com&amp;blog=25721749&amp;post=867&amp;subd=danhaywood&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://danhaywood.com/2011/12/20/db-unit-testing-with-dbunit-json-hsqldb-and-junit-rules/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/204ef8a2259ebe0716f985f96c1c350d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">danhaywood</media:title>
		</media:content>
	</item>
		<item>
		<title>JMock 2.6 &#8211; JUnit Rules and automocking using an @Mock annotation</title>
		<link>http://danhaywood.com/2011/12/17/jmock-2-6-junit-rules-and-automocking-using-an-mock-annotation/</link>
		<comments>http://danhaywood.com/2011/12/17/jmock-2-6-junit-rules-and-automocking-using-an-mock-annotation/#comments</comments>
		<pubDate>Sat, 17 Dec 2011 11:35:36 +0000</pubDate>
		<dc:creator>danhaywood</dc:creator>
				<category><![CDATA[tdd]]></category>

		<guid isPermaLink="false">http://danhaywood.com/?p=861</guid>
		<description><![CDATA[I&#8217;ve been using Mockito a lot this year at work, but I still prefer JMock.  However, JMock could do with trimming some of its boilerplate, and I also thought it would be a good idea to use JUnit 4.7&#8242;s org.junit.rules.MethodRule. I was about to go implement something to support Mockito&#8217;s @Mock annotation, but thought I&#8217;d browse [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=danhaywood.com&amp;blog=25721749&amp;post=861&amp;subd=danhaywood&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been using <a href="http://mockito.googlecode.com">Mockito</a> a lot this year at work, but I still prefer <a href="http://jmock.org">JMock</a>.  However, JMock could do with trimming some of its boilerplate, and I also thought it would be a good idea to use JUnit 4.7&#8242;s <a href="http://kentbeck.github.com/junit/javadoc/latest/org/junit/rules/MethodRule.html">org.junit.rules.MethodRule</a>.</p>
<p>I was about to go implement something to support Mockito&#8217;s <a href="http://mockito.googlecode.com/svn/branches/1.6/javadoc/org/mockito/Mock.html">@Mock</a> annotation, but thought I&#8217;d browse the jmock.org website first.  It looks like Steve and Nat are ahead of me, and that JMock 2.6 will have the sort of support I need.</p>
<p><span id="more-861"></span></p>
<p>As I write this, they haven&#8217;t released that version yet, but the actual code that&#8217;s needed isn&#8217;t much.   So I thought I&#8217;d copy-n-paste for your delectation:</p>
<p><pre class="brush: java;">
package org.jmock.integration.junit4;

import org.jmock.auto.internal.Mockomatic;
import org.jmock.internal.AllDeclaredFields;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;

import java.lang.reflect.Field;
import java.util.List;

import static org.junit.Assert.fail;

public class JUnitRuleMockery extends JUnit4Mockery implements MethodRule {
    private final Mockomatic mockomatic = new Mockomatic(this);

    @Override
    public Statement apply(final Statement base, FrameworkMethod method, final Object target) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                prepare(target);
                base.evaluate();
                assertIsSatisfied();
            }

            private void prepare(final Object target) {
                List&lt;Field&gt; allFields = AllDeclaredFields.in(target.getClass());
                assertOnlyOneJMockContextIn(allFields);
                fillInAutoMocks(target, allFields);
            }

            private void assertOnlyOneJMockContextIn(List&lt;Field&gt; allFields) {
                Field contextField = null;
                for (Field field : allFields) {
                    if (JUnitRuleMockery.class.isAssignableFrom(field.getType())) {
                        if (null != contextField) {
                            fail(&quot;Test class should only have one JUnitRuleMockery field, found &quot;
                                  + contextField.getName() + &quot; and &quot; + field.getName());
                        }
                        contextField = field;
                    }
                }
            }

            private void fillInAutoMocks(final Object target, List&lt;Field&gt; allFields) {
                mockomatic.fillIn(target, allFields);
            }
        };
    }
}
</pre></p>
<p>A typical class to use this would use this as follows:</p>
<p><pre class="brush: java;">
public class ATestWithSatisfiedExpectations {
    @Rule
    public final JUnitRuleMockery context = new JUnitRuleMockery();
    @Mock
    private Runnable runnable;
    @Test
    public void doesSatisfyExpectations() {
        context.checking(new Expectations() {{
            oneOf (runnable).run();
        }});
        runnable.run();
    }
}
</pre></p>
<p>As you can see, this supports @Mock very much the same way as Mockito.  The @Mock annotation itself is simply:</p>
<p><pre class="brush: java;">
package org.jmock.auto;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(RUNTIME)
@Target(FIELD)
public @interface Mock {
}
</pre></p>
<p>There is also an @Auto annotation which can be used to automatically instantiate States and Sequences:</p>
<p><pre class="brush: java;">
package org.jmock.auto;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(RUNTIME)
@Target(FIELD)
public @interface Auto {
}
</pre></p>
<p>Meanwhile, there are two internal class to do some of the reflection stuff. First, Mockomatic:</p>
<p><pre class="brush: java;">
package org.jmock.auto.internal;

import java.lang.reflect.Field;
import java.util.List;

import org.jmock.Mockery;
import org.jmock.Sequence;
import org.jmock.States;
import org.jmock.auto.Auto;
import org.jmock.auto.Mock;
import org.jmock.internal.AllDeclaredFields;

public class Mockomatic {
    private final Mockery mockery;

    public Mockomatic(Mockery mockery) {
        this.mockery = mockery;
    }

    public void fillIn(Object object) {
        fillIn(object, AllDeclaredFields.in(object.getClass()));
    }

    public void fillIn(Object object, final List&lt;Field&gt; knownFields) {
        for (Field field : knownFields) {
            if (field.isAnnotationPresent(Mock.class)) {
                autoMock(object, field);
            }
            else if (field.isAnnotationPresent(Auto.class)) {
                autoInstantiate(object, field);
            }
        }
    }

    private void autoMock(Object object, Field field) {
        setAutoField(field, object,
                     mockery.mock(field.getType(), field.getName()),
                     &quot;auto-mock field &quot; + field.getName());
    }

    private void autoInstantiate(Object object, Field field) {
        final Class&lt;?&gt; type = field.getType();
        if (type == States.class) {
            autoInstantiateStates(field, object);
        }
        else if (type == Sequence.class) {
            autoInstantiateSequence(field, object);
        }
        else {
            throw new IllegalStateException(&quot;cannot auto-instantiate field of type &quot; + type.getName());
        }
    }

    private void autoInstantiateStates(Field field, Object object) {
        setAutoField(field, object,
                     mockery.states(field.getName()),
                     &quot;auto-instantiate States field &quot; + field.getName());
    }

    private void autoInstantiateSequence(Field field, Object object) {
        setAutoField(field, object,
                     mockery.sequence(field.getName()),
                     &quot;auto-instantiate Sequence field &quot; + field.getName());
    }

    private void setAutoField(Field field, Object object, Object value, String description) {
        try {
            field.setAccessible(true);
            field.set(object, value);
        }
        catch (IllegalAccessException e) {
            throw new IllegalStateException(&quot;cannot &quot; + description, e);
        }
    }
}
</pre></p>
<p>and second, AllDeclaredFields:</p>
<p><pre class="brush: java;">&lt;/pre&gt;
package org.jmock.auto.internal;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import static java.util.Arrays.asList;

public class AllDeclaredFields {
    public static List&lt;Field&gt; in(Class&lt;?&gt; clazz) {
        final ArrayList&lt;Field&gt; fields = new ArrayList&lt;Field&gt;();
        for (Class&lt;?&gt; c = clazz; c != Object.class; c = c.getSuperclass()) {
            fields.addAll(asList(c.getDeclaredFields()));
        }
        return fields;
    }
}
</pre></p>
<p>The above is a great improvement; my own small extension is to add some convenience methods, and to introduce a factory method to replace the rather obscure way that JMock has for mocking classes:</p>
<p><pre class="brush: java;">
package org.apache.isis.core.testsupport.jmock;

import org.jmock.Expectations;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;

public class JUnitRuleMockery2 extends JUnitRuleMockery {

    public static enum Mode {
        INTERFACES_ONLY,
        INTERFACES_AND_CLASSES;
    }

    public static JUnitRuleMockery2 createFor(Mode mode) {
        JUnitRuleMockery2 jUnitRuleMockery2 = new JUnitRuleMockery2();
        if(mode == Mode.INTERFACES_AND_CLASSES) {
            jUnitRuleMockery2.setImposteriser(ClassImposteriser.INSTANCE);
        }
        return jUnitRuleMockery2;
    }

    public &lt;T&gt; T ignoring(final T mock) {
        checking(new Expectations() { { ignoring(mock); } });
        return mock;
    }

    public &lt;T&gt; T allowing(final T mock) {
        checking(new Expectations() { { allowing(mock); } });
        return mock;
    }

    public &lt;T&gt; T never(final T mock) {
        checking(new Expectations() { { never(mock); } });
        return mock;
    }

    public &lt;T&gt; T mockAndIgnoring(final Class&lt;T&gt; typeToMock) {
        return ignoring(mock(typeToMock));
    }

    public &lt;T&gt; T mockAndIgnoring(final Class&lt;T&gt; typeToMock, final String name) {
        return ignoring(mock(typeToMock, name));
    }

    public &lt;T&gt; T mockAndAllowing(final Class&lt;T&gt; typeToMock) {
        return allowing(mock(typeToMock));
    }

    public &lt;T&gt; T mockAndAllowing(final Class&lt;T&gt; typeToMock, final String name) {
        return allowing(mock(typeToMock, name));
    }

    public &lt;T&gt; T mockAndNever(final Class&lt;T&gt; typeToMock) {
        return never(mock(typeToMock));
    }

    public &lt;T&gt; T mockAndNever(final Class&lt;T&gt; typeToMock, final String name) {
        return never(mock(typeToMock, name));
    }
}
</pre></p>
<p>This can be used as follows:</p>
<p><pre class="brush: java;">
public class MyTest {

  @Rule
  public final Junit4Mockery2 context = Junit4Mockery2.createFor(Mode.INTERFACES);
  ...
}
</pre></p>
<p>Comments always welcome.</p>
<br />Filed under: <a href='http://danhaywood.com/category/random/tdd/'>tdd</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/danhaywood.wordpress.com/861/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/danhaywood.wordpress.com/861/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/danhaywood.wordpress.com/861/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/danhaywood.wordpress.com/861/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/danhaywood.wordpress.com/861/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/danhaywood.wordpress.com/861/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/danhaywood.wordpress.com/861/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/danhaywood.wordpress.com/861/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/danhaywood.wordpress.com/861/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/danhaywood.wordpress.com/861/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/danhaywood.wordpress.com/861/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/danhaywood.wordpress.com/861/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/danhaywood.wordpress.com/861/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/danhaywood.wordpress.com/861/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=danhaywood.com&amp;blog=25721749&amp;post=861&amp;subd=danhaywood&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://danhaywood.com/2011/12/17/jmock-2-6-junit-rules-and-automocking-using-an-mock-annotation/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/204ef8a2259ebe0716f985f96c1c350d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">danhaywood</media:title>
		</media:content>
	</item>
		<item>
		<title>Updated Apache Isis Presentations</title>
		<link>http://danhaywood.com/2011/12/16/updated-apache-isis-presentations/</link>
		<comments>http://danhaywood.com/2011/12/16/updated-apache-isis-presentations/#comments</comments>
		<pubDate>Fri, 16 Dec 2011 07:22:10 +0000</pubDate>
		<dc:creator>danhaywood</dc:creator>
				<category><![CDATA[apache isis]]></category>

		<guid isPermaLink="false">http://danhaywood.com/?p=852</guid>
		<description><![CDATA[If you&#8217;re thinking of introducing Apache Isis to your co-workers, you might be interested to know that Isis already has an &#8220;Introducing Apache Isis&#8221; presentation slide deck (in ODP,  PPTX or PPT, PDF slides or notes).  You are free to use this as you will. I&#8217;ve just updated the deck in line with the forthcoming v0.2.0 release; the most [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=danhaywood.com&amp;blog=25721749&amp;post=852&amp;subd=danhaywood&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re thinking of introducing <a title="Apache Isis" href="http://incubator.apache.org/isis" target="_blank">Apache Isis</a> to your co-workers, you might be interested to know that Isis already has an &#8220;Introducing Apache Isis&#8221; presentation slide deck (in <a href="http://incubator.apache.org/isis/presentations/IntroducingApacheIsis.odp" target="_blank">ODP</a>,  <a href="http://incubator.apache.org/isis/presentations/IntroducingApacheIsis.pptx" target="_blank">PPTX</a> or <a href="http://incubator.apache.org/isis/presentations/IntroducingApacheIsis.ppt" target="_blank">PPT</a>, PDF <a href="http://incubator.apache.org/isis/presentations/IntroducingApacheIsis-slides.pdf" target="_blank">slides</a> or <a href="http://incubator.apache.org/isis/presentations/IntroducingApacheIsis-notes.pdf" target="_blank">notes</a>).  You are free to use this as you will.</p>
<p><span id="more-852"></span></p>
<p>I&#8217;ve just updated the deck in line with the forthcoming v0.2.0 release; the most significant new content includes an overview of the main use cases for Apache Isis.  The <a title="Apache Isis Online Demo" href="http://mmyco.co.uk:8180/isis-onlinedemo" target="_blank">online demo</a> for Isis also gets a link.</p>
<p><a href="http://danhaywood.files.wordpress.com/2011/12/isisusecases.png"><img class=" wp-image-853 alignnone" title="IsisUseCases" src="http://danhaywood.files.wordpress.com/2011/12/isisusecases.png?w=450&#038;h=177" alt="" width="450" height="177" /></a></p>
<p>As ever, feedback welcome!</p>
<br />Filed under: <a href='http://danhaywood.com/category/naked-objects-pattern/apache-isis/'>apache isis</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/danhaywood.wordpress.com/852/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/danhaywood.wordpress.com/852/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/danhaywood.wordpress.com/852/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/danhaywood.wordpress.com/852/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/danhaywood.wordpress.com/852/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/danhaywood.wordpress.com/852/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/danhaywood.wordpress.com/852/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/danhaywood.wordpress.com/852/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/danhaywood.wordpress.com/852/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/danhaywood.wordpress.com/852/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/danhaywood.wordpress.com/852/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/danhaywood.wordpress.com/852/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/danhaywood.wordpress.com/852/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/danhaywood.wordpress.com/852/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=danhaywood.com&amp;blog=25721749&amp;post=852&amp;subd=danhaywood&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://danhaywood.com/2011/12/16/updated-apache-isis-presentations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/204ef8a2259ebe0716f985f96c1c350d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">danhaywood</media:title>
		</media:content>

		<media:content url="http://danhaywood.files.wordpress.com/2011/12/isisusecases.png?w=300" medium="image">
			<media:title type="html">IsisUseCases</media:title>
		</media:content>
	</item>
		<item>
		<title>Apache Isis Online Demo</title>
		<link>http://danhaywood.com/2011/12/08/apache-isis-online-demo/</link>
		<comments>http://danhaywood.com/2011/12/08/apache-isis-online-demo/#comments</comments>
		<pubDate>Thu, 08 Dec 2011 18:31:46 +0000</pubDate>
		<dc:creator>danhaywood</dc:creator>
				<category><![CDATA[apache isis]]></category>
		<category><![CDATA[restful objects]]></category>

		<guid isPermaLink="false">http://danhaywood.com/?p=841</guid>
		<description><![CDATA[We&#8217;ve finally got around to putting together an online demo of Apache Isis for would-be users to quickly grok what Isis is all about. If you don&#8217;t fancy reading any further but just want to play, you can find it here. If you&#8217;re still with me, you&#8217;ll find that the online demo shows how Isis can dynamically [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=danhaywood.com&amp;blog=25721749&amp;post=841&amp;subd=danhaywood&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a title="Apache Isis Online Demo" href="http://mmyco.co.uk:8180/isis-onlinedemo/" target="_blank"><img class="size-thumbnail wp-image-843 alignright" title="Apache Isis Online Demo screenshot" src="http://danhaywood.files.wordpress.com/2011/12/apacheisisonlinedemoscreenshot.png?w=150&#038;h=89" alt="Apache Isis Online Demo screenshot" width="150" height="89" /></a>We&#8217;ve finally got around to putting together an online demo of <a title="Apache Isis" href="http://incubator.apache.org/isis" target="_blank">Apache Isis</a> for would-be users to quickly grok what Isis is all about. If you don&#8217;t fancy reading any further but just want to play, you can find it <a title="here" href="http://mmyco.co.uk:8180/isis-onlinedemo/" target="_blank">here</a>.<br />
<span id="more-841"></span></p>
<p>If you&#8217;re still with me, you&#8217;ll find that the online demo shows how Isis can dynamically generate a (human-usable) webapp and a (machine-usable) RESTful API from the same domain object model. The REST API is that<br />
defined by the <a title="Restful Objects" href="http://restfulobjects.org" target="_blank">Restful Objects</a> spec.</p>
<p>The online demo bundles its own documentation, which shows the full source code for the domain model (all 3 classes) along with guidance on how to use Chrome (or similar) extensions to play with the REST API directly from your browser.</p>
<p>Feedback very welcome on the <a title="isis-dev" href="mailto:isis-dev@incubator.apache.org" target="_blank">isis-dev</a> mailing list.</p>
<br />Filed under: <a href='http://danhaywood.com/category/naked-objects-pattern/apache-isis/'>apache isis</a>, <a href='http://danhaywood.com/category/restful-objects/'>restful objects</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/danhaywood.wordpress.com/841/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/danhaywood.wordpress.com/841/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/danhaywood.wordpress.com/841/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/danhaywood.wordpress.com/841/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/danhaywood.wordpress.com/841/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/danhaywood.wordpress.com/841/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/danhaywood.wordpress.com/841/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/danhaywood.wordpress.com/841/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/danhaywood.wordpress.com/841/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/danhaywood.wordpress.com/841/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/danhaywood.wordpress.com/841/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/danhaywood.wordpress.com/841/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/danhaywood.wordpress.com/841/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/danhaywood.wordpress.com/841/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=danhaywood.com&amp;blog=25721749&amp;post=841&amp;subd=danhaywood&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://danhaywood.com/2011/12/08/apache-isis-online-demo/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/204ef8a2259ebe0716f985f96c1c350d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">danhaywood</media:title>
		</media:content>

		<media:content url="http://danhaywood.files.wordpress.com/2011/12/apacheisisonlinedemoscreenshot.png?w=150" medium="image">
			<media:title type="html">Apache Isis Online Demo screenshot</media:title>
		</media:content>
	</item>
		<item>
		<title>jQTouch and Restful Objects (Apache Isis)</title>
		<link>http://danhaywood.com/2011/11/23/jqtouch-and-restful-objects-apache-isis/</link>
		<comments>http://danhaywood.com/2011/11/23/jqtouch-and-restful-objects-apache-isis/#comments</comments>
		<pubDate>Wed, 23 Nov 2011 00:33:15 +0000</pubDate>
		<dc:creator>danhaywood</dc:creator>
				<category><![CDATA[jqtouch]]></category>
		<category><![CDATA[restful objects]]></category>

		<guid isPermaLink="false">http://danhaywood.com/?p=833</guid>
		<description><![CDATA[I&#8217;ve started looking into using jQTouch to build a custom UI against a Restful Objects back-end hosted in UI.  These are my own notes; apologies but I haven&#8217;t annotated them&#8230; The domain object model you need to understand for this example is really simple; just a finder on a repository: And as you can probably [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=danhaywood.com&amp;blog=25721749&amp;post=833&amp;subd=danhaywood&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve started looking into using jQTouch to build a custom UI against a Restful Objects back-end hosted in UI.  These are my own notes; apologies but I haven&#8217;t annotated them&#8230;</p>
<p><span id="more-833"></span></p>
<p>The domain object model you need to understand for this example is really simple; just a finder on a repository:</p>
<p><pre class="brush: java;">
@Named(&quot;Customers&quot;)
public interface Customers {

    @QueryOnly
    public Customer findByEmail(
        @Named(&quot;Email&quot;)
        String email);
    ...
}
</pre></p>
<p>And as you can probably imagine, one of the properties of Customer is an email address:</p>
<p><pre class="brush: java;">
public class Customer extends AbstractDomainObject {
    ...
    // {{ Email (property)
    private String email;

    @MemberOrder(sequence = &quot;4.0&quot;)
    public String getEmail() {
        return email;
    }

    public void setEmail(final String email) {
        this.email = email;
    }
    // }}
    ...
}
</pre></p>
<p>Next, I downloaded the jQTouch and unzipped into src/main/webapp of my viewer-json module (as generated by the Isis archetype).</p>
<p>Hopping into src/main/webapp/demo, I copied &#8220;skel&#8221; to a new directory, &#8220;webshop&#8221;.</p>
<p>The top of src/main/webapp/demo/webshop/index.html is all boilerplate:</p>
<p><pre class="brush: xml;">
&lt;!doctype html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta charset=&quot;UTF-8&quot; /&gt;

        &lt;title&gt;Webshop on Isis&lt;/title&gt;
        &lt;style type=&quot;text/css&quot; media=&quot;screen&quot;&gt;@import &quot;../../jqtouch/jqtouch.css&quot;;&lt;/style&gt;
        &lt;style type=&quot;text/css&quot; media=&quot;screen&quot;&gt;@import &quot;../../themes/jqt/theme.css&quot;;&lt;/style&gt;
        &lt;script src=&quot;../../jqtouch/jquery-1.4.2.min.js&quot; type=&quot;text/javascript&quot; charset=&quot;utf-8&quot;&gt;&lt;/script&gt;
        &lt;script src=&quot;../../jqtouch/jqtouch.js&quot; type=&quot;application/x-javascript&quot; charset=&quot;utf-8&quot;&gt;&lt;/script&gt;
        &lt;script type=&quot;text/javascript&quot; charset=&quot;utf-8&quot;&gt;
            var jQT = new $.jQTouch({
                icon: 'jqtouch.png',
                addGlossToIcon: false,
                startupScreen: 'jqt_startup.png',
                statusBar: 'black'
            });

            $(function(){
                // Custom Javascript (onReady)
            });
        &lt;/script&gt;
        &lt;style type=&quot;text/css&quot; media=&quot;screen&quot;&gt;
        &lt;/style&gt;

        &lt;script src=&quot;webshop.js&quot; type=&quot;application/x-javascript&quot; charset=&quot;utf-8&quot;&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;div id=&quot;jqt&quot;&gt;
        &lt;/div&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre></p>
<p>This is pretty much what the same as skel/index.html; the only addition is that script include of webshop.js.</p>
<p>The skeleton for the webshop.js script itself is:</p>
<p><pre class="brush: jscript;">
(function($){

$(function(){
    ... this is where our functions go ...
});

})(jQuery);
</pre></p>
<p>I broke the app itself down into two pages. The first shows the finders for Customer:</p>
<p><pre class="brush: xml;">
        &lt;div id=&quot;jqt&quot;&gt;
            &lt;div id=&quot;customers&quot; class=&quot;current&quot;&gt;
                &lt;div class=&quot;toolbar&quot;&gt;
                    &lt;h1&gt;Customers&lt;/h1&gt;
                    &lt;a href=&quot;#&quot; class=&quot;back&quot;&gt;Back&lt;/a&gt;
                &lt;/div&gt;
                &lt;h2&gt;Find by Email&lt;/h2&gt;
                &lt;div class=&quot;findByEmail&quot;&gt;
                    &lt;form&gt;
                        &lt;ul class=&quot;edit rounded&quot;&gt;
                            &lt;li class=&quot;email&quot;&gt;
                                &lt;input type=&quot;email&quot; name=&quot;email&quot; placeholder=&quot;email@address.com&quot;&gt;&lt;/input&gt;
                                &lt;span style=&quot;display: inline; font-size: 75%; color:rgb(255,127,0)&quot;/&gt;
                            &lt;/li&gt;
                        &lt;/ul&gt;
                        &lt;a style=&quot;margin:0 10px;color:rgba(0,0,0,.9)&quot; href=&quot;#&quot; class=&quot;submit whiteButton&quot;&gt;Submit&lt;/a&gt;
                        &lt;a style=&quot;display:none&quot; href=&quot;#customer&quot; class=&quot;onsuccess&quot;&gt;dummy text&lt;/a&gt;
                    &lt;/form&gt;
                &lt;/div&gt;
            &lt;/div&gt;
            ...
        &lt;/div&gt;
</pre></p>
<p>In webshop.js I then have a binding onto this form:</p>
<p><pre class="brush: jscript;">
     $(&quot;#customers .findByEmail form&quot;).submit(function() {
         var email = $(&quot;#customers .findByEmail .email input&quot;).val()
         if (!email) {
             $(&quot;#customers .findByEmail .email span&quot;).text(&quot;Enter email address&quot;).show().fadeOut(1000);
             return false;
         }

         $.get(&quot;/services/customers/actions/findByEmail/invoke?email=&quot; + email,
            function(data) {
                $(&quot;#customer&quot;).data(&quot;object&quot;, data.result)
                $(&quot;#customers .findByEmail .onsuccess&quot;).click();
            }
        );

         return false;
    });
    ...
</pre></p>
<p>When the user submits the form, we validate the email address and then call the REST API to get the customer. This is the bound to the target #customer div as a data element &#8220;object&#8221;.</p>
<p>The #customer div, which will show the customer, looks like this:</p>
<p><pre class="brush: xml;">
        &lt;div id=&quot;jqt&quot;&gt;
            ...
            &lt;div id=&quot;customer&quot;&gt;
                &lt;div class=&quot;toolbar&quot;&gt;
                    &lt;h1&gt;No Customer&lt;/h1&gt;
                    &lt;a href=&quot;#&quot; class=&quot;back&quot;&gt;Back&lt;/a&gt;
                &lt;/div&gt;
                &lt;ul class=&quot;rounded members&quot;&gt;

                &lt;/ul&gt;
            &lt;/div&gt;
        &lt;/div&gt;
</pre></p>
<p>And the javascript to render the customer is:</p>
<p><pre class="brush: jscript;">
    ...
    $('#customer').bind('pageAnimationStart', function (e, info) {
      var cust = $(&quot;#customer&quot;).data(&quot;object&quot;)
      $(&quot;h1&quot;).text(cust.title)
      var email = $.each(cust.members, function(index, member) {
        if(member.memberType == 'property') {
            $(&quot;.members&quot;).append('&lt;li&gt;&lt;span&gt;' + member.id + ': &lt;/span&gt;&lt;span&gt;' + member.value + '&lt;/span&gt;&lt;/li&gt;')
        }
       } );
      $(&quot;.email&quot;).text(email)

    });
</pre></p>
<p>There&#8217;s plenty more that could be done to tidy this up, but that&#8217;s hopefully gives you an idea&#8230;</p>
<br />Filed under: <a href='http://danhaywood.com/category/javascript/jqtouch/'>jqtouch</a>, <a href='http://danhaywood.com/category/restful-objects/'>restful objects</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/danhaywood.wordpress.com/833/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/danhaywood.wordpress.com/833/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/danhaywood.wordpress.com/833/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/danhaywood.wordpress.com/833/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/danhaywood.wordpress.com/833/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/danhaywood.wordpress.com/833/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/danhaywood.wordpress.com/833/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/danhaywood.wordpress.com/833/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/danhaywood.wordpress.com/833/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/danhaywood.wordpress.com/833/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/danhaywood.wordpress.com/833/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/danhaywood.wordpress.com/833/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/danhaywood.wordpress.com/833/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/danhaywood.wordpress.com/833/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=danhaywood.com&amp;blog=25721749&amp;post=833&amp;subd=danhaywood&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://danhaywood.com/2011/11/23/jqtouch-and-restful-objects-apache-isis/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/204ef8a2259ebe0716f985f96c1c350d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">danhaywood</media:title>
		</media:content>
	</item>
		<item>
		<title>Restful Objects v0.51 uploaded</title>
		<link>http://danhaywood.com/2011/11/08/restful-objects-v0-51-uploaded/</link>
		<comments>http://danhaywood.com/2011/11/08/restful-objects-v0-51-uploaded/#comments</comments>
		<pubDate>Tue, 08 Nov 2011 00:31:29 +0000</pubDate>
		<dc:creator>danhaywood</dc:creator>
				<category><![CDATA[restful objects]]></category>

		<guid isPermaLink="false">http://danhaywood.com/?p=828</guid>
		<description><![CDATA[Since my last post there&#8217;s been a couple more updates to the Restful Objects spec. Restful Objects defines a set of RESTful resources, and corresponding representations, for accessing and manipulating a domain object model.  The most up-to-date version of this specification may be downloaded from  http://restfulobjects.org; as of now I&#8217;m up to v0.51. Noteworthy changes [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=danhaywood.com&amp;blog=25721749&amp;post=828&amp;subd=danhaywood&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Since my last post there&#8217;s been a couple more updates to the Restful Objects spec.</p>
<p style="text-align:left;" align="center">Restful Objects defines a set of RESTful resources, and corresponding representations, for accessing and manipulating a domain object model.  The most up-to-date version of this specification may be downloaded from <a style="text-align:0;" href="http://www.restfulobjects.org/"> </a><a href="http://restfulobjects.org">http://restfulobjects.org</a>; as of now I&#8217;m up to v0.51.</p>
<p>Noteworthy changes since my last post include:</p>
<p><span id="more-828"></span></p>
<ul>
<li>moved content from introductory chapter into new &#8220;Patterns and Practices&#8221; section at end, and expanded its discussion</li>
<li>added diagrams to show links from every representation out to the resources</li>
<li>Introduced a new action-result representation, with object, list and scalar representations inlined.  This allows implementations to append additional information in the &#8220;extensions&#8221; and &#8220;lists&#8221; nodes.  In particular, Apache Isis provides changed/dirty object lists in the &#8220;extensions&#8221; node.</li>
<li>renamed the &#8220;domain type member&#8221; resources to &#8220;domain member description&#8221;</li>
<li>introduced a new domain type action equivalent to java.lang.Class#isAssignableFrom().  This allows clients to query the type hierarchy of domain types</li>
<li>204 &#8220;no content&#8221; is hardly returned anywhere anymore.  In particular, object put, property put, property delete, collection put, collection post, collection delete all now return representations.  Actions returning void return the action-result representation.</li>
</ul>
<p>The spec is currently being implemented by two different open source frameworks: <a title="Apache Isis" href="http://incubator.apache.org/isis" target="_blank">Apache Isis</a> (Java) and <a title="Naked Objects MVC" href="http://nakedobjects.net" target="_blank">Naked Objects MVC</a> (.NET).    The changes in this version have come about either from those implementations, or from feedback of a Javascript client implementation that is underway.</p>
<p>Other comments always welcome.</p>
<br />Filed under: <a href='http://danhaywood.com/category/restful-objects/'>restful objects</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/danhaywood.wordpress.com/828/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/danhaywood.wordpress.com/828/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/danhaywood.wordpress.com/828/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/danhaywood.wordpress.com/828/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/danhaywood.wordpress.com/828/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/danhaywood.wordpress.com/828/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/danhaywood.wordpress.com/828/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/danhaywood.wordpress.com/828/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/danhaywood.wordpress.com/828/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/danhaywood.wordpress.com/828/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/danhaywood.wordpress.com/828/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/danhaywood.wordpress.com/828/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/danhaywood.wordpress.com/828/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/danhaywood.wordpress.com/828/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=danhaywood.com&amp;blog=25721749&amp;post=828&amp;subd=danhaywood&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://danhaywood.com/2011/11/08/restful-objects-v0-51-uploaded/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/204ef8a2259ebe0716f985f96c1c350d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">danhaywood</media:title>
		</media:content>
	</item>
	</channel>
</rss>
