<?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>fforw.de &#187; svenson</title>
	<atom:link href="http://fforw.de/tag/svenson/feed/" rel="self" type="application/rss+xml" />
	<link>http://fforw.de</link>
	<description>skip the boring parts</description>
	<lastBuildDate>Sat, 12 Nov 2011 11:54:31 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Generating List&lt;Something&gt; from JSON with svenson</title>
		<link>http://fforw.de/post/generating-list-from-json-with-svenson/</link>
		<comments>http://fforw.de/post/generating-list-from-json-with-svenson/#comments</comments>
		<pubDate>Thu, 09 Sep 2010 18:26:19 +0000</pubDate>
		<dc:creator>fforw</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[svenson]]></category>

		<guid isPermaLink="false">http://fforw.de/?p=217</guid>
		<description><![CDATA[Often you&#8217;ll find yourself wanting to parse a JSON into a Java collection but want the values inside the collection to be of a specific type. Nothing easier than that. import org.svenson.JSONParser; … // Getting a list containing your own type Something. // Assume json to be a String containing the JSON dataset. JSONParser parser [...]]]></description>
			<content:encoded><![CDATA[<p>Often you&#8217;ll find yourself wanting to parse a JSON into a Java collection but want the values inside the collection to be of a specific type. Nothing easier than that.</p>
<p><span style="color: #0000ff;"> </span></p>
<pre><span style="color: #0000ff;">import</span> org.svenson.JSONParser;
…
<span style="color: #008000;">// Getting a list containing your own type Something.
// Assume json to be a String containing the JSON dataset.
</span>JSONParser parser = <span style="color: #0000ff;">new</span> JSONParser();
parser.addTypeHint("[]", Something.class);
List&lt;Something&gt; someThings = parser.parse(List.class, json);
<span style="color: #008000;">// someThings will be a ArrayList instance by default. You can change
// that by changing the mappings for interfaces by calling
// org.svenson.JSONParser.setInterfaceMappings(Map&lt;Class, Class&gt;)
</span></pre>
<p>Parsing into a map is not much more complicated either</p>
<pre>JSONParser jsonParser = <span style="color: #0000ff;">new</span> JSONParser();
jsonParser.addTypeHint(new RegExPathMatcher("\\.(f1|f2)"), Something.class);
Map&lt;String,Object&gt; someThings = jsonParser.parse(Map.class, json);</pre>
<p>If we want to have our Something type for more than a single field, we need to setup a matcher. Here you see an example of a RegExPathMatcher that makes sure that both the keys &#8220;f1&#8243; and &#8220;f2&#8243; of the map we receive will be converted to Something, while all other fields are not.</p>
<p>If you want to convert all map properties to Something, the RegExPathMatcher would be like this</p>
<pre>    … new RegExPathMatcher("\\..*") …</pre>
<p>This would match every JSON path that starts with a property. If you don&#8217;t like RegularExpressions, or are on some kind of diet on them, you can also construct a more complex matcher tree from the compositable Matchers like this</p>
<pre>JSONParser jsonParser = <span style="color: #0000ff;">new</span> JSONParser();<span style="color: #000000;">
jsonParser.addTypeHint(<span style="color: #0000ff;">new</span> OrMatcher(
    <span style="color: #0000ff;">new</span> PrefixPathMatcher(".f1"),
    <span style="color: #0000ff;">new</span> PrefixPathMatcher(".f2")), Something<span style="color: #0000ff;">.class</span>);
Map&lt;String,Object&gt; someThings = jsonParser.parse(Map<span style="color: #0000ff;">.class</span>, json);
</span>
</pre>
<p><strong>Update:</strong><span style="color: #000000;"> Due to me fucking up both the Prefix-/Suffix- matchers as well as their tests, the last example will only really work with the current svenson trunk/future svenson 1.3.8</span></p>
<p><span style="color: #000000;"><br />
</span></p>
<p><span style="color: #000000;"></span></p>
]]></content:encoded>
			<wfw:commentRss>http://fforw.de/post/generating-list-from-json-with-svenson/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Annotating DOM nodes with JSON, Part 2</title>
		<link>http://fforw.de/post/annotating-dom-nodes-with-json-part-2/</link>
		<comments>http://fforw.de/post/annotating-dom-nodes-with-json-part-2/#comments</comments>
		<pubDate>Thu, 03 Jun 2010 11:49:51 +0000</pubDate>
		<dc:creator>fforw</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[download]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[svenson]]></category>

		<guid isPermaLink="false">http://fforw.de/?p=169</guid>
		<description><![CDATA[It&#8217;s been a while since I wrote Annotating DOM nodes with JSON and in retrospective I can say that I never really used the method described in a real life project. Now I&#8217;d like to present another method of decorating DOM nodes with JSON based on classes. This one I actually implemented in OpenSAGA to [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been a while since I wrote <a title="old blog post" href="http://fforw.de/post/annotating-dom-nodes-with-json/">Annotating DOM nodes with JSON</a> and in retrospective I can say that I never really used the method described in a real life project. Now I&#8217;d like to present another method of decorating DOM nodes with JSON based on classes. This one I actually implemented in <a title="OpenSAGA Project website" href="http://opensaga.org/">OpenSAGA</a> to have arbitrary metadata from some of the OpenSAGA Widgets.</p>
<p>I didn&#8217;t really like the idea of misusing onclick for the purpose of meta-data and thought about a better way of doing it. Browsing the w3 HTML specs I came upon the fact that <a title="Link to the HTML spec. Also see 'cdata-list' definition" href="http://www.w3.org/TR/html401/struct/global.html#h-7.5.2">classes can be any character separated by spaces</a>. So for use-cases where I only needed one meta-data value I used classes like</p>
<pre>&lt;div class="refId:id-1234"&gt;
    DIV content
&lt;/div&gt;
</pre>
<p>A use-case specific prefix is used to mark a class as meta-data container containing the string after the prefix. The code to evaluate this in javascript is very easy</p>
<pre>/**
 * Returns the class value with the given prefix using the giving separator
 * @param {DOMElement} elem DOM element to fetch metadata from
 * @param {String} name of the classval value
 * @param {String} separator to use between name and value. Default is ":"
 */
function classval(elem, name, separator)
{
    var match = new RegExp("\\b" + name + (separator || ":") + "([^ ]*)($| )")
                          .exec(elem.className);
    if (match)
    {
        return match[1];
    }
    return null;
}
…
// assume divElement to be DOM element of the div
var refId = classval(divElement, "refId");
</pre>
<p>I thought about going for a more elaborate prefix scheme to support nested metadata but in the end decided against it because I already have a nicely supported format for exchanging data between server and client: JSON. So I tried to come up with a scheme of using arbitrary JSON for the metadata decoration.</p>
<p>Only problem: Spaces are not valid inside classes, so I needed a method to encode and decode JSON into valid classes. The method should not totally mangle the JSON to keep readability and maybe write the encoded variant by hand for simple cases.</p>
<p>Solution:</p>
<ul>
<li>HTML encode the JSON-String</li>
<li>Replace spaces with underlines and underlines with \u005f</li>
</ul>
<p>The replacement of underlines is valid because underlines can only occur inside quoted JSON strings so they can just be replaced by their escaped unicode value \u005f.</p>
<p>Here is the java code to do the escaping. Since it&#8217;s basically a combination of string replacement and HTML encoding this should be easily doable in any server-side language:</p>
<pre>
    public String escapeDecoration(String s)
    {
        String escaped = StringEscapeUtils.escapeHtml(s);

        StringBuilder sb = new StringBuilder(escaped.length());
        sb.append("deco:");
        for (int i = 0; i < escaped.length() ; i++)
        {
            char c = escaped.charAt(i);
            switch(c)
            {
                case '_':
                    sb.append("\\u005F");
                    break;
                case ' ':
                    sb.append('_');
                    break;
                default:
                    sb.append(c);
                    break;
            }
        }

        return sb.toString();
    }
</pre>
<p>The escape method uses the escapeHTML method from Apache commons-lang's StringEscapeUtil. Going the other way in javascript is not that complicated either:</p>
<pre>/**
 * Decodes the given string containing HTML entities.
 */
function htmlDecode(s)
{
    var helper = document.createElement("SPAN");
    helper.innerHTML = s;
    return helper.innerHTML;
}

/**
 * Returns the JSON decoration of the given element.
 * @param {DOMElement} DOM element
 * @param {String} decorator classval name, default is "deco".
 */
function decoration(elem, name)
{
    var value, data, result;

    value = classval(elem, name || "deco");
    if (value)
    {
       // get raw data from DOM element
       data = value.replace(/_/g, " ");
       // replace HTML entities with the original characters
       data = htmlDecode(data);
       // evaluate JSON
       result = eval("("+data+")");
    }
    return result || {};
}
</pre>
<p>In order to achieve a better readability of escaped JSON, I also used <a href="http://code.google.com/p/svenson/">svenson</a>'s ability to deviate from the JSON standard by using single quotes instead of double quotes. Just comparing</p>
<pre>&lt;div id="tst2" class="deco:{'foo':'xxx\u005f_yyy','baz':[1,3,5,7,9]}"&gt;
JSON annotation
&lt;/div&gt;
</pre>
<p>to</p>
<pre>&lt;div id="tst2" class="deco:{&amp;quot;foo&amp;quot;:&amp;quot;xxx\u005f_yyy&amp;quot;,&amp;quot;baz&amp;quot;:[1,3,5,7,9]}"&gt;
JSON annotation
&lt;/div&gt;
</pre>
<p>should demonstrate that single quotes are not only much better readable, but also shorter. If you use eval() evaluate the JSON string, the single quotes are no problem at all. If you want json2.js / native JSON-parsing, you might have to replace the quote chars before parsing.</p>
<p><strong>Links:</strong></p>
<p><a href="http://fforw.de/static/files/meta.html">HTML test page with both metadata strategies</a></p>
]]></content:encoded>
			<wfw:commentRss>http://fforw.de/post/annotating-dom-nodes-with-json-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hood: example application for jcouchdb 0.10.0-1</title>
		<link>http://fforw.de/post/hood-example-application-for-jcouchdb-0-10-0-1/</link>
		<comments>http://fforw.de/post/hood-example-application-for-jcouchdb-0-10-0-1/#comments</comments>
		<pubDate>Wed, 14 Oct 2009 22:52:22 +0000</pubDate>
		<dc:creator>fforw</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[couchdb]]></category>
		<category><![CDATA[download]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jcouchdb]]></category>
		<category><![CDATA[JSP]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[svenson]]></category>

		<guid isPermaLink="false">http://fforw.de/?p=92</guid>
		<description><![CDATA[On the occasion of presenting CouchDB and jcouchdb at my place of work, I got around to finally create a small example application that is now downloadable as sneak preview. There need to be bugs fixed, features implemented and lots of documentation to be added, but it kind of works. It&#8217;s called &#8220;Hood&#8221; for neighbourhood [...]]]></description>
			<content:encoded><![CDATA[<p>On the occasion of presenting CouchDB and jcouchdb at my place of work, I got around to finally create a small example application that is now downloadable as sneak preview. There need to be bugs fixed, features implemented and lots of documentation to be added, but it kind of works.</p>
<p>It&#8217;s called &#8220;Hood&#8221; for neighbourhood and allows you to mark places or people around a place of activity of yours, called hood. it is meant to foster collaboration / tips on local places etc.</p>
<p>It&#8217;s Spring Web Application demonstrating some techniques of working with jcouchdb. It&#8217;s an eclipse WTP/Spring IDE project with all dependencies you need besides couchdb and tomcat or another servlet container.</p>
<p>Stay tuned for hood to grow into a fullblown app.</p>
<p><strong>Links:</strong></p>
<ul>
<li><span style="text-decoration: line-through;">Hood Alpha &#8211; download at code.google.com</span></li>
<li><a href="http://jcouchdb.googlecode.com/files/hood-beta-2.zip">Hood Beta 2 &#8211; download at code.google.com</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://fforw.de/post/hood-example-application-for-jcouchdb-0-10-0-1/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Memory consumption changes in svenson 1.3</title>
		<link>http://fforw.de/post/memory-consumption-changes-in-svenson-13/</link>
		<comments>http://fforw.de/post/memory-consumption-changes-in-svenson-13/#comments</comments>
		<pubDate>Sun, 19 Apr 2009 15:00:24 +0000</pubDate>
		<dc:creator>fforw</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[jcouchdb]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[stats]]></category>
		<category><![CDATA[svenson]]></category>

		<guid isPermaLink="false">http://blog.willie/?p=4</guid>
		<description><![CDATA[Implementing a streaming attachment feature for jcouchdb, I started to wonder whether it would be a good idea for svenson to support JSON parsing from a stream, too, as I don&#8217;t really need the complete stream to start constructing the java object graph. Implementing stream parsing was really nice and easy thanks to the units [...]]]></description>
			<content:encoded><![CDATA[<p>Implementing a streaming attachment feature for <a title="jcouchdb project page at google code" href="http://code.google.com/p/jcouchdb/">jcouchdb</a>, I started to wonder whether it would be a good idea for svenson to support JSON parsing from a stream, too, as I don&#8217;t really need the complete stream to start constructing the java object graph.</p>
<p>Implementing stream parsing was really nice and easy thanks to the units test present in svenson. After that, I came upon two ways to generally cut down on memory use. All tokens with fixed values could just have a single instance. The recording of tokens to provide token based look ahead was not really needed in all cases. But how much does that save?</p>
<p>As a test case I wrote a small tool class to generate random, nested JSON datasets, generated two test files of 65kb and 4.5mb size and parsed these with svenson 1.2.8 and what now is svenson 1.3.</p>
<p>Measuring the actual memory usage for these two test files proved to be difficult. Somehow none of the programs I tried seemed to give me the data I wanted. Eclipse TPTP just ignored Strings that were no member of any class but just parameters, making stream and string parsing look exactly the same memory-wise. tijmp and others did not provide the data I wanted at all.</p>
<p>So in the end I wrote a little python script that parses a hprof ASCII output to</p>
<ul>
<li>sum up all memory use</li>
<li>group allocations by class type, but only if the stack trace of it touches svenson</li>
<li>output the top 10 of those classes and the sums</li>
</ul>
<p>This provided meaningful data and also showed some points for further improvement. There was a huge number of java.lang.reflect.Method allocations which turned out to be caused by svenson inspecting the target classes for annotations and appropriate methods which was done on a per target basis instead of the better per target class basis.</p>
<p>All in all the memory usage went down quite a bit:</p>
<div class="wp-caption aligncenter" style="width: 507px"><img title="memory usage diagram" src="http://fforw.de/static/image/svenson-combined.png" alt="memory usage for different svenson versions, with and without streaming" width="497" height="296" /><p class="wp-caption-text">memory usage for different svenson versions, with and without streaming</p></div>
<p>45% less memory for the small file and 62% for the large file for all allocations. I think that is really good..</p>
<p>Below are some links to the files needed to repeat the benchmarking. The transform hprof script might also prove to be useful for other projects if changed appropriately.</p>
<p>The new jcouchdb release will also use stream parsing.</p>
<p><strong>Links:</strong></p>
<ul>
<li><a href="/static/files/svenson-memory-report.txt">Detailed data: Top 10 memory use by class and sums for all 6 variants</a></li>
<li><a href="/static/files/transform_hprof.py">Python script to transform hprof ASCII output</a></li>
<li><a href="http://svenson.googlecode.com/svn/trunk/test/org/svenson/RandomJSON.java">Random JSON Generator</a></li>
<li><a href="/static/files/small.json">Small JSON test file</a></li>
<li><a href="/static/files/big.json">Big JSON test file</a></li>
</ul>
<p><strong>edit:</strong><br />
The command to generate the hprof file was something like</p>
<blockquote><p>java -agentlib:hprof=heap=sites,depth=100,cutoff=0 -cp .. svensonperf.ReadJSONOld big.json</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://fforw.de/post/memory-consumption-changes-in-svenson-13/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

