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

<channel>
	<title>Sword Systems &#187; JSON</title>
	<atom:link href="http://swordsystems.com/tag/json/feed/" rel="self" type="application/rss+xml" />
	<link>http://swordsystems.com</link>
	<description>Cutting Commentary</description>
	<lastBuildDate>Tue, 10 Jan 2012 02:02:29 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>JSON conversion and request thread reuse</title>
		<link>http://swordsystems.com/2009/12/18/json-conversion-and-request-thread-reuse/</link>
		<comments>http://swordsystems.com/2009/12/18/json-conversion-and-request-thread-reuse/#comments</comments>
		<pubDate>Fri, 18 Dec 2009 15:33:52 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Controller]]></category>
		<category><![CDATA[frustration]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[JSON]]></category>

		<guid isPermaLink="false">http://swordsystems.com/?p=50</guid>
		<description><![CDATA[When reusable thread pools and thread local variables can bite you in the butt.]]></description>
			<content:encoded><![CDATA[<p>Wrapping up (I hope) my experience with custom JSON conversions in Grails&#8230; The day before we were supposed to hit a major release milestone last week, I finally caught sight of a random bug that had been driving us nuts.  For some AJAX requests, seemingly at random, the object that has the transient properties was not being rendered with them.  Instead, it had only the regular, persistent properties and full representations of its associated objects rather than just the normal stubs of related objects with just the type and id.  In other words, it was using deep JSON rendering, and this was overriding the custom JSON <code>ObjectMarshaller</code> that we had set for the class.  But why was it doing it seemingly at random?  This is where luck and experience combined to make the solution clear rather quickly and avoided some painful slogging through request handling on the server.</p>
<p>The luck part was that I remembered seeing a checkin from a teammate a couple of weeks ago where he got rid of direct use of a <code>grails.converters.deep.JSON</code> object (which is deprecated) and instead switched to a normal <code>grails.converters.JSON</code> object with a <code>use('deep')</code> statement:</p>
<p><code>def get = {<br />
	def o = OurClass.get(params.id);<br />
	JSON.use("deep")<br />
	render(contentType: "application/json", text: o as JSON)<br />
}<br />
</code><br />
This change was in a different controller for a different domain object though.  Why was it affecting our other domain class?  That&#8217;s where the experience part came in.  A few years ago I had to track down why hibernate transactions would fail seemingly at random in another web app when running under JBoss.  I could see why an initial transaction would fail (we&#8217;d get a timeout and not rollback properly), but there was no reason why later requests would cause failures.  That&#8217;s when I discovered the downside of request thread pooling.  Under most web contains, HTTP requests are handled by a pool of reusable threads.  That means changes to thread local variables stick around between requests unless explicitly reset.  In the case of the Hibernate bug, since the session was not getting closed properly, it wasn&#8217;t getting fully reset and cleared out, so subsequent requests that used that thread were getting the old session and failing because there was no way to get it back to a good state.</p>
<p>For the current JSON conversion bug, the <code>JSON.use</code> method was calling <code>ConvertersConfigurationHolder.setTheadLocalConverterConfiguration(...)</code>, thus making the deep converter stick around for that thread.  So when future requests came in to any controller on that thread, all JSON conversion calls were made with the deep configuration.</p>
<p>The solution is straightforward.  Use the <code>JSON.use(String, Closure)</code> call instead when you want to make a deep call:</p>
<p><code>def get = {<br />
    def o = OurClass.get(params.id);<br />
    JSON.use("deep") {<br />
        render(contentType: "application/json", text: o as JSON)<br />
    }<br />
}</p>
<p></code>This sets the configuration only for the closure, saving you from thread-based side effects later on.</p>
]]></content:encoded>
			<wfw:commentRss>http://swordsystems.com/2009/12/18/json-conversion-and-request-thread-reuse/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Grails JSON converter and transient properties</title>
		<link>http://swordsystems.com/2009/11/23/grails-json-converter-and-transient-properties/</link>
		<comments>http://swordsystems.com/2009/11/23/grails-json-converter-and-transient-properties/#comments</comments>
		<pubDate>Mon, 23 Nov 2009 16:04:55 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://swordsystems.com/?p=42</guid>
		<description><![CDATA[I figured out why my domain object was rendering as JSON differently in unit tests vs. when running the application and integration tests. Drum roll, please&#8230;No grailsApplication object is setup in unit tests. I hear a great big, &#8220;Huh?&#8221; First, a little background on converters. (You may want to get the Grails source code and [...]]]></description>
			<content:encoded><![CDATA[<p>I figured out why my domain object was rendering as JSON differently in unit tests vs. when running the application and integration tests.   Drum roll, please&#8230;No grailsApplication object is setup in unit tests.</p>
<p>I hear a great big, &#8220;Huh?&#8221;  </p>
<p>First, a little background on converters.  (You may want to get the Grails source code and have directories open to the <code>org.codehaus.groovy.grails.web.converters</code> and <code>grails.converter</code> packages before diving into this.)  When a <code>JSON</code> converter is created, it obtains a <code>ConverterConfiguration</code> from the global <code>ConvertersConfigurationHolder</code>.  <code>ConverterConfiguration</code> has several properties which influence the conversion process, but the most interesting for this discussion is its prioritized set of <code>ObjectMarshallers</code>.  <code>ObjectMarshaller</code>s are what do the actual work of turning an object into a JSON representation.  Each <code>ObjectMarshaller</code> handles a certain set of classes, like arrays, maps, beans, grails domain objects, etc.  When the <code>JSON</code> object is ready to convert a data object, it calls <code>config.getMarshaller(data)</code>.  The config iterates through its list of marshallers, calling <code>marshaller.supports(data)</code> on each.  Since multiple marshallers may be able to handle a specific class (like <code>GroovyBeanMarshaller</code> and <code>DomainClassMarshaller</code> can both handle domain classes), whichever marshaller has highest priority (i.e. is called first) will be invoked.</p>
<p>When the standard <code>ConverterConfiguration</code> is initialized, the <code>DomainClassMarshaller</code> is given higher priority than the <code>GroovyBeanMarshaller</code>.  Thus, it handles the conversion of domain objects during normal Grails application execution even though domain objects are also groovy beans.  However, the <code>DomainClassMarshaller.supports()</code> method has a slight twist to it.  It depends on there being a <code>GrailsApplication</code> object registered in the <code>ConverterUtil</code> class in order to tell it that a particular object is a domain object.  Without the <code>GrailsApplication</code> object, <code>ConverterUtil.isDomainClass()</code> always returns false, causing <code>DomainClassMarshaller.supports()</code> to also return false.  The <code>ConverterConfiguration</code> next checks the <code>GroovyBeanMarshaller</code>.  Its <code>supports()</code> method returns true, so it handles the conversion in this case.  </p>
<p>So why is this a big deal?  For most domain object, it probably isn&#8217;t.  Both marshallers render the primary properties of the domain object.  However, the <code>DomainClassMarshaller</code> only renders properties return by <code>domainClass.getPersistentProperties()</code> while <code>GroovyBeanMarshaller</code> renders all properties, including transient ones.  Because I needed some transient properties in the JSON representation, my unit tests worked great (since there is no grailsApplication setup, so the <code>GroovyBeanMarshaller</code> did the full rendering), but then my code failed when I ran the integration tests and the real app (since the <code>DomainClassMarshaller</code> handled the rendering).</p>
<p>How do you fix this?  It&#8217;s pretty easy once you know where to look.  First, I wanted to make my unit tests behave like the real app, so I had to get them to fail.  Unfortunately, the conversion classes are written in java, not groovy, so you can&#8217;t just do a quick override of the <code>ConverterUtil</code> metaclass to get it to return what you want.  You actually need to setup a <code>GrailsApplication</code> object.  Rather than trying to create and initialize a whole one though, I determined that I could create a small stub class that overrode the two methods I needed:</p>
<p><code><br />
import org.codehaus.groovy.grails.commons.*<br />
class GrailsApplicationStub extends DefaultGrailsApplication {<br />
    def artefacts = [(DomainClassArtefactHandler.TYPE):[:]]</p>
<p>    boolean isArtefactOfType(String artefactType, String className) {<br />
        return getArtefact(artefactType, className) != null<br />
    }</p>
<p>    GrailsClass getArtefact(String artefactType, String name) {<br />
        def retVal = artefacts[artefactType] ? artefacts[artefactType][name] : null<br />
        return retVal<br />
    }<br />
}<br />
</code><br />
When initializing the unit test, I created the stub and set in the particular domain class that I wanted to be recognized.  Then register the application stub with the <code>ConverterUtil</code> class:</p>
<p><code><br />
def grailsApp = new GrailsApplicationStub();<br />
grailsApp.artefacts[DomainClassArtefactHandler.TYPE][YourClass.name] = new DefaultGrailsDomainClass(YourClass);<br />
ConverterUtil.setGrailsApplication(grailsApp);<br />
</code><br />
Instances of <code>YourClass</code> will now be handled by the <code>DomainClassMarshaller</code> in the unit test.  When the unit test checks for the existence of a transient property in a JSON representation, it should fail.</p>
<p>Next, I needed to change the marshaller prioritization so that the desired domain class was handled by a regular <code>GroovyBeanMarshaller</code>.  Since I always wanted the <code>GroovyBeanMarshaller</code> to handle the class, I inserted this code into my unit test setup (and later into <code>BootStrap</code> so the behavior would apply to the full app):</p>
<p><code><br />
JSON.registerObjectMarshaller(YourClass, {o, c -><br />
    new GroovyBeanMarshaller().marshalObject(o, c)<br />
    })<br />
</code></p>
<p>This creates a <code>ClosureObjectMarshaller</code> that handles <code>YourClass</code> objects and gives the new marshaller the default priority of 1 (which puts it at the top of the priority list).  When processing an object, this closure marshaller simply passes it through to a <code>GroovyBeanMarshaller</code>.  Since the new marshaller only handles <code>YourClass</code> objects, the rendering behavior for all other domain objects is not affected.</p>
<p>This resolved my original issue.  The JSON rendering of my object is now correct when I run my app. I did go down a side path while coming to this final solution.  If you only want to override how a <code>YourClass</code> object is rendered some of the time, you could instead register a named configuration for it like this:</p>
<p><code><br />
JSON.createNamedConfig("FullYourClassRender") {cfg -><br />
    cfg.registerObjectMarshaller(new ClosureOjectMarshaller<JSON>(YourClass, {o, c -><br />
        new GroovyBeanMarshaller().marshalObject(o, c)<br />
        }))<br />
    }<br />
</code><br />
Then when you want to use that particular configuration, you wrap the <code>JSON</code> object calls in a use statement:</p>
<p><code><br />
JSON.use("FullYourClassRender") {<br />
    render(contentType: "application/json", text: myObject as JSON)<br />
    }<br />
</code></p>
<p>Other configuration options are also available.  Take a look at the <code>JSON</code> class to see them.</p>
<p>I hope this helps document the conversion process a bit.</p>
]]></content:encoded>
			<wfw:commentRss>http://swordsystems.com/2009/11/23/grails-json-converter-and-transient-properties/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Fun with Grails JSON conversion</title>
		<link>http://swordsystems.com/2009/11/20/fun-with-grails-json-conversion/</link>
		<comments>http://swordsystems.com/2009/11/20/fun-with-grails-json-conversion/#comments</comments>
		<pubDate>Fri, 20 Nov 2009 06:15:15 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[Intellij]]></category>
		<category><![CDATA[JSON]]></category>

		<guid isPermaLink="false">http://swordsystems.com/?p=39</guid>
		<description><![CDATA[I discovered a problem this afternoon with how one of the domain objects in my Grails app was being converted to JSON in its controller.  The conversion functioned as expected in a unit test, but failed in integration tests and when running the real app.  &#8220;Time to see how good the debugger in Intellij 9 [...]]]></description>
			<content:encoded><![CDATA[<p>I discovered a problem this afternoon with how one of the domain objects in my Grails app was being converted to JSON in its controller.  The conversion functioned as expected in a unit test, but failed in integration tests and when running the real app.  &#8220;Time to see how good the debugger in Intellij 9 is,&#8221; I say to myself.  So I dive into the grails.converters.JSON class to try to find where the difference comes from.  Unfortunately, every time I step into the render() method, the rendering quickly fails with this exception:</p>
<p>org.codehaus.groovy.grails.web.json.JSONException: &#8220;Misplaced object&#8221;</p>
<p>It turns out that the JSON converter has a writer property that is a JSONWriter object.  The act of showing the writer in the variables window of the Intellij debugger causes its toString() method to be called by the IDE (though any breakpoints set in the class do not get triggered by the call).  This, in turn, causes the writer to actually do the writing of the object which, when complete, changes the writer&#8217;s state property to DONE.  When the real code execution tries to process the data, the JSONWriter throws the exception because it thinks it has already finished rendering.</p>
<p>The trick to step through the JSON converter is to define a custom Type Renderer for the JSONWriter class that does not invoke the &#8220;toString&#8221; method.  <a href="http://blogs.jetbrains.com/idea/2008/04/type-renderers/" target="_blank">A blog post</a> on the Intellij site defines how to setup a Type Renderer for a class.  I set mine up so that the node renders simply as &#8220;JSONWriter&#8221; since I don&#8217;t need to see the details for it.  One caveat though &#8211; I found that the new Type Renderer didn&#8217;t affect entries already in my variables window until I right-clicked one and selected &#8220;View As -&gt; JSONWriter&#8221;.  Then the view changed to use the new display settings.</p>
<p>Now back to debugging&#8230;maybe I&#8217;ll actually figure out the real problem sometime before the sun comes up.</p>
]]></content:encoded>
			<wfw:commentRss>http://swordsystems.com/2009/11/20/fun-with-grails-json-conversion/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

