<?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>Jayway Team Blog &#187; neo4j</title>
	<atom:link href="http://blog.jayway.com/tag/neo4j/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 11 Feb 2012 10:33:02 +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>Neo4j .NET Client over HTTP using REST and json</title>
		<link>http://blog.jayway.com/2010/04/16/neo4j-net-client-over-http-using-rest-and-json/</link>
		<comments>http://blog.jayway.com/2010/04/16/neo4j-net-client-over-http-using-rest-and-json/#comments</comments>
		<pubDate>Fri, 16 Apr 2010 09:49:25 +0000</pubDate>
		<dc:creator>Magnus Mårtensson</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[httpclient]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[neo4j]]></category>
		<category><![CDATA[rest]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/2010/04/16/neo4j-net-client-over-http-using-rest-and-json/</guid>
		<description><![CDATA[Here it is; a Proof of Concept of the world’s first Neo4j .NET Client. In other words: Here follows a discussion on how to create a client library for communicating with a graph database over REST. UPDATE: There is now a live CodePlex project for the realization of this concept; A .NET Client Library for [...]]]></description>
			<content:encoded><![CDATA[<p>Here it is; a <a href="http://en.wikipedia.org/wiki/Proof_of_concept">Proof of Concept</a> of the world’s first Neo4j .NET Client. In other words: Here follows a discussion on how to create a client library for communicating with a graph database over <a href="http://en.wikipedia.org/wiki/REST">REST</a>.</p>
<p><strong>UPDATE:</strong> There is now a live CodePlex project for the realization of this concept; A .NET Client Library for Neo4j over HTTP using REST and JSON; <a title="http://neo4jrestsharp.codeplex.com/" href="http://neo4jrestsharp.codeplex.com/">http://neo4jrestsharp.codeplex.com/</a></p>
<h3>Intro</h3>
<p><a href="http://neotechnology.com/">Neo Technologies</a> have come out with a <a href="http://components.neo4j.org/neo4j-rest/">Neo4j REST API</a> for their popular Neo4j graph database. Since I am employed at <a href="http://jayway.com">Jayway</a> and a couple of colleagues working with Neo are too a little bird by the name of <a href="http://twitter.com/peterneubauer/status/11761202320">Peter Neubauer tweeted in my ear</a> that there was a free T-Shirt involved in making a working sample for .NET that communicated with the Neo4j server. Not only was that a handsome offer – I wanted to check out what the <em>Architecture</em> of such a client library for a graph database would look like.</p>
<p>I’ve recently been involved in client library abstractions and good architecture with the RESTful interface to <a href="http://www.microsoft.com/windowsazure/windowsazure/">Windows Azure Storage</a>. (More on Azure and storage on my blog <a href="http://blog.noop.se/archive/2009/11/29/azure-contrib-codeplex-updated-to-the-november-ctp.aspx">here</a>, <a href="http://blog.noop.se/archive/2009/08/15/introducing-the-cloud-storage-api.aspx">here</a>, <a href="http://blog.noop.se/archive/2009/08/17/using-the-cloudstorage.api-the-message-queue.aspx">here</a>, <a href="http://blog.noop.se/archive/2009/08/19/using-the-cloudstorage.api-the-blob-storage.aspx">here</a> and <a href="http://blog.noop.se/archive/2009/08/20/using-the-cloudstorage.api-the-entity-storage.aspx">here</a>.) Enough with the side tracking (sorry)!</p>
<p>Said and done; We set out to code up a working sample for .NET. I hacked the client code. The Neo-guys cheered me on and offered very helpful assistance when I ran into trouble or was just plane stumped on how to proceed with the API. A very nice team effort, including a remote team debugging session, later and we have a small and running POC</p>
<p>Tweeting on this effort it is notable how a bunch of people answer back with an interest in this idea for potential applications in the .NET world. I’ve been approached both on twitter (<a href="http://twitter.com/noopman">@noopman</a>) and on <a href="http://se.linkedin.com/in/noopman">LinkedIn</a> with questions on this.</p>
<p>This blog post is to submit our findings to the world and hope that someone will be inspired to get going with a real .NET client library for Neo4j.</p>
<h3>Architecture</h3>
<p>First let’s look at the architecture for creating a client library for a RESTful service. This is a more general discussion that leads to our client library POC below. If your main reason for reading is the actual sample; scroll down.</p>
<p>When doing a client library abstractions and domain thinking comes into play. What we want is for the forgotten users (developers) of your application to work with their normal domain objects in the business code and for them to use an API that makes sense to their domain while talking to a highly specific graph database backend store. This means you have to keep all the RESTfulness, HTTP and <a href="http://json.org/">json</a> away from the domain code. Let me show you a sketch and see if I can make this explanation a bit less wordy:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/image.png" rel="lightbox"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/image_thumb.png" width="563" height="551" /></a> </p>
<p>At the other side of the Cloud from our .NET code is a Java based graph database. It is friendly enough to expose a RESTful API so that we may speak to it.</p>
<p>Doing so we want to create a client library that is capable of a couple of things:1) Taking care of serializing objects to json (and deserializing them back again). 2) Knowing about HTTP requests and how to handle them. In our sample we employed the power of the <a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx">HttpWebRequest</a> class to handle things like HTTP Headers, Content Types, URIs etc. 3) Finally this library must understand to expose an interface to your code that you can use from a specialized Data Access Component.</p>
<p>To protect the business layer from knowing anything about the specifics of the Neo4j API you really should use a specialized Data Access Component. There is now law being broken if you don’t do that. However a good rule of thumb is to add abstraction layers in your system to shield your domain code in your business components from any specifics of an underlying storage structure. The details of serialization of objects to json and making requests over HTTP are not a natural fit to the business problem you are solving. The code that does this separation is code you write yourself in your application. Only you know how to adapt a foreign library and technology to your domain. The sole purpose of this code, in other words, is to abstract away from your business logic the underlying technologies used to persist and query data used in the application. This component translates between the two worlds of your business logic and the techniques used to store data in a graph database. Most of the specific technical details of storage are wrapped up in the Client Lib mind you but the Data Access Layer DAL knows about this problem domain. It understands that the persistence indeed is a REST based service over HTTP with all that this entails. This component in your code can handle synchonisity and take care of specific errors or faults that may occur when using the storage. All of this is done in a language that is fairly close to the API that Neo4j exposes. In the end this component translates into terms useful to the domain in which your business operates. Instead of saying .PostNode() in your code perhaps you instead expose a .StorePerson() action.</p>
<p>What we achieve is a good and sound (and classic) layering model: Business Logic – DAL – Client Lib.</p>
<p>There is one more observation to make in the picture and that is the matter of <a href="http://en.wikipedia.org/wiki/Inversion_of_control">IoC - Inversion of Control</a>. In order to keep your code testable, maintainable and untangled from the implementations at lower layers you should always employ the method of Inversion of Control – making your business code for instance not reference the DAL direct but instead use a common contract to do so. The <a href="http://en.wikipedia.org/wiki/Dependency_inversion_principle">Depencency Inversion Principle</a> states briefly that a higher layer should never depend direct on a lower layer but instead depend on an abstraction. If this is true you are able to test your business logic without using the actual underlying storage. This is for instance key in a <a href="http://en.wikipedia.org/wiki/Test-driven_development">TDD – Test Driven Development</a> development style.</p>
<p>Code that depends on abstractions can be tested very quickly and does not depend on specific data in a data store to be correct in order to test the intended behavior. The Business Logic uses a contract for the DAL and the DAL implements it. Then you use something called an IoC container (read on at Wikipedia in the link above) to create the DAL instances and hand them to the Business Logic employing the technique of <a href="http://en.wikipedia.org/wiki/Dependency_injection">DI -Dependency Injection</a>. This separation enables you to modify, re-deploy or even exchange DAL components without having to touch your Business Layer at all. If separating the Business Logic from the DAL using contracts is important it is almost event more important to do so in the lower layer that in run time speaks direct to the data store! You never want to end up in the situation where in order to test your DAL code you have to have access to a specific data store with specific data in it. Not only is that an inconvenience; it also makes executing your tests run as slow as transferring data over the Internet compared to as fast as your CPU can execute code. From experience it is an obvious conclusion that tests that are slow to run are not in fact run. The conclusion from all of these IoC discussions can only be that it is imperative that your Client Library comes with an abstraction layer.</p>
<h4>What did we do with the Architecture in our POC?</h4>
<p>All of these architectural considerations are of course premature in a POC. This is why in our sample we did not really separate the DAL code from the Client Lib. However to prove the point of IoC and DI I did however separate out the Business Logic from the Data Access logic using a simple contract and an equally simple <a href="http://en.wikipedia.org/wiki/Factory_method_pattern">Factory Method Pattern</a>. Instead of new:ing up a DAL component in my code I called a factory method to access an abstraction of the DAL.</p>
<h3>Our POC sample</h3>
<p>Our code sample creates a small node graph with a few relationships. Then it makes a traversal of the graph to find all who “knows” someone according to the relationships. Finally it deletes the graph again.</p>
<p>Here is the graph we create in our sample: <a title="http://wiki.neo4j.org/content/The_Matrix" href="http://wiki.neo4j.org/content/The_Matrix">http://wiki.neo4j.org/content/The_Matrix</a> We only create names on nodes and types on relationships in our simple sample.</p>
<p>And here is also the code so that you may download and follow along with our explanation your self:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F60BB8FA-6F02-4999-8F5E-9DD4E92C4DA7:2ece3c0c-e960-4fb6-bcfc-b89358d619c9" class="wlWriterEditableSmartContent">
<div><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/Neo4j.POC.zip" target="_self">Neo4j.POC.zip</a></div>
</div>
<p>First, in accordance with architectural considerations (above) we get hold of our DAL using a factory method. We also create a new Person object and store him (in this case Thomas Anderson – Neo):</p>
<pre class="code"><span style="color: #2b91af">INeo4jStorageClient </span>neo4JStorageClient =
<span style="color: #2b91af">Neo4jStorageFactory</span>.GetNodeStorageClient(neo4jServerUri);

neo = <span style="color: blue">new </span><span style="color: #2b91af">Person</span>(<span style="color: #a31515">&quot;Thomas Anderson&quot;</span>);
neo4JStorageClient.StoreNode(neo);</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p><font color="#222222" face="Verdana">As you can see in our business code this is just standard .NET</font> classes being instantiated and a “Neo” Person is stored in a very normal way. In the business logic code there is no real details on how this storage happens. There is of course a “node” concept and you can consider for your self if that should be hidden away from business code too.</p>
<p>Since this is a POC the implementation of .StoreNode(neo) is very very trivial. If this were a real client library we would have included things like a library to transform (serialize) the neo-Person node into a json string. Now we just do it statically:</p>
<pre class="code"><span style="color: blue">public void </span>StoreNode(<span style="color: #2b91af">Person </span>person)
{
    <span style="color: blue">var </span>name = person.Name;

    <span style="color: blue">string </span>jsonString = <span style="color: #a31515">@&quot;{&quot;&quot;Name&quot;&quot;:&quot;&quot;&quot; </span>+ name + <span style="color: #a31515">@&quot;&quot;&quot;}&quot;</span>;

    <span style="color: blue">var </span>nodeProtocol = <span style="color: blue">new </span><span style="color: #2b91af">NodeProtocol</span>(uri);

    <span style="color: blue">var </span>nodeId = nodeProtocol.PostNode(jsonString);
    person.Id = nodeId;
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The interesting part here is the existence of a <span style="color: #2b91af">NodeProtocol</span> implementation. I’ve found it useful working with a remote API like Windows Azure Storage and also with this Neo4j REST API to implement methods in C# code that correlate very closely to the API methods available. In our case we have a PostNode operation on the REST API and consequently we have a .PostNode() method in the C# implementation of that HTTP method call.</p>
<pre class="code"><span style="color: blue">public int </span>PostNode(<span style="color: blue">string </span>nodeData)
{
    <span style="color: blue">var </span>uri = <span style="color: #2b91af">HttpHelper</span>.ConcatUri(baseUri, <span style="color: #a31515">&quot;node&quot;</span>);

    <span style="color: #2b91af">HttpWebRequest </span>request =
        <span style="color: #2b91af">Request</span>.CreateWebRequest(<span style="color: #2b91af">HttpWebRequestMethod</span>.POST, uri);

    <span style="color: #2b91af">HttpHelper</span>.AddBody(request, nodeData);

    <span style="color: blue">var </span>response = requestMaker.MakeRequest(request);

    <span style="color: blue">return </span><span style="color: #2b91af">HttpHelper</span>.FindNodeId(response.Item3);
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>I won’t bore you with the exact details of all of the helper classes. To dig in to those it is better if you just download the code and look at the details your self.</p>
<p>As you can see we create a HttpWebRequest, add some headers to it (in the CreateWebRequest method) specifying things like request.Accept = &quot;application/json&quot;; meaning we accept a json formatted response. Also we specify that the body we send out is formatted as json with request.ContentType = &quot;application/json&quot;;. Finally we make the call and return the id of the node we just created.</p>
<p>Again this is a solution bordering on triviality but still it is to the point of making a REST request and receiving a response. Also there is no code to handle any errors present here and the request is done synchronously.</p>
<p>What does the actual HTTP REST and json request and response look like for this simple sample?</p>
<p>Request:</p>
<pre class="code">

POST <a href="http://try.neo4j.org:9999/node">http://try.neo4j.org:9999/node</a> HTTP/1.1
Content-Type: application/json
Host: try.neo4j.org:9999
Content-Length: 26
Expect: 100-continue
Connection: Keep-Alive

<font style="background-color: #ececec"></font>
{&quot;Name&quot;:&quot;Thomas Anderson&quot;}
</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Response (note that the added line breaks in the response body were added by me):</p>
<pre class="code">

HTTP/1.1 201 Created
server: grizzly/1.8.1
Content-Encoding: UTF-8
Location: <a href="http://try.neo4j.org:9999/node/1">http://try.neo4j.org:9999/node/1</a>

Content-Type: application/json
Content-Length: 860
Date: Fri, 16 Apr 2010 08:36:45 GMT

{&quot;incoming typed relationships&quot;:

<a href="http://try.neo4j.org:9999/node/1/relationships/in/{-list|&amp;|types}">http://try.neo4j.org:9999/node/1/relationships/in/{-list|&amp;|types}</a>,

&quot;incoming relationships&quot;:<a href="http://try.neo4j.org:9999/node/1/relationships/in">http://try.neo4j.org:9999/node/1/relationships/in</a>,

&quot;all relationships&quot;:<a href="http://try.neo4j.org:9999/node/1/relationships/all">http://try.neo4j.org:9999/node/1/relationships/all</a>,

&quot;create relationship&quot;:<a href="http://try.neo4j.org:9999/node/1/relationships">http://try.neo4j.org:9999/node/1/relationships</a>,

&quot;data&quot;:{&quot;Name&quot;:&quot;Thomas Anderson&quot;},

&quot;traverse&quot;:<a href="http://try.neo4j.org:9999/node/1/traverse/{returnType}">http://try.neo4j.org:9999/node/1/traverse/{returnType}</a>,

&quot;property&quot;:<a href="http://try.neo4j.org:9999/node/1/properties/{key}">http://try.neo4j.org:9999/node/1/properties/{key}</a>,

&quot;self&quot;:<a href="http://try.neo4j.org:9999/node/1">http://try.neo4j.org:9999/node/1</a>,

&quot;properties&quot;:<a href="http://try.neo4j.org:9999/node/1/properties">http://try.neo4j.org:9999/node/1/properties</a>,

&quot;all typed relationships&quot;:

<a href="http://try.neo4j.org:9999/node/1/relationships/all/{-list|&amp;|types}">http://try.neo4j.org:9999/node/1/relationships/all/{-list|&amp;|types}</a>,

&quot;outgoing typed relationships&quot;:

<a href="http://try.neo4j.org:9999/node/1/relationships/out/{-list|&amp;|types}">http://try.neo4j.org:9999/node/1/relationships/out/{-list|&amp;|types}</a>,

&quot;outgoing relationships&quot;:<a href="http://try.neo4j.org:9999/node/1/relationships/out">http://try.neo4j.org:9999/node/1/relationships/out</a>}

</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>As you can see the Neo4j REST API is self explanatory. Creating a node gives you back a response with all the things you can now do with this new node over the API. Since this quite a lot of data when the only thing that really matters is in the header (Location: <a href="http://try.neo4j.org:9999/node/1">http://try.neo4j.org:9999/node/1</a>) I’ve already given feedback to the Neo team that I’d like a simple Uri switch (like APIDocumentation=0) to shut off the detailed response. But in fact I do like that you get so many Uris back that you may use direct. Depending on your needs this is either good or to verbose a payload to get back in your response. As you can see the node we created got the Id set to 1.</p>
<p>Now we proceed to create all the other nodes and in a very similar fashion the relationships between nodes. Here is the relationship that says that “Neo knows Trinity” (who has a node id of 2). This is a POST operation to /node/1/relationships:</p>
<pre class="code">

POST <a href="http://try.neo4j.org:9999/node/1/relationships">http://try.neo4j.org:9999/node/1/relationships</a> HTTP/1.1
Content-Type: application/json
Host: try.neo4j.org:9999
Content-Length: 56
Expect: 100-continue

{&quot;type&quot;:&quot;Knows&quot;,&quot;to&quot;:<a href="http://try.neo4j.org:9999/node/2">http://try.neo4j.org:9999/node/2</a>}
</pre>
<p>Once the node graph for the Matrix is created we proceed to make a traversal of the graph. We want to find anyone who knows someone throughout the graph.</p>
<p>The request looks like this in REST (after a similar path through the code as above with a call from business logic to DAL and through to the client lib that makes the actual call using REST):</p>
<pre class="code">

POST <a href="http://try.neo4j.org:9999/node/1/traverse/node">http://try.neo4j.org:9999/node/1/traverse/node</a> HTTP/1.1
Accept: application/json
Content-Type: application/json
Host: try.neo4j.org:9999
Content-Length: 57
Expect: 100-continue
Connection: Keep-Alive

{ &quot;relationships&quot;: { &quot;type&quot;: &quot;Knows&quot; }, &quot;max depth&quot;: 10 }
</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Again we simplified to a “max depth” of 10 relationships deep into the graph which works fine for our sample.</p>
<p>The result is a list of all the nodes that match. Because of the self explanatory API mentioned above the result also gives you actions to perform on each node that comes back in the response thus making the response body quite long. Rather than pasting the whole thing here into the blog post you can try it out your self (by downloading the application) and you will get a result exactly like this from the app:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/image1.png" rel="lightbox"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/image_thumb1.png" width="221" height="222" /></a> </p>
<p>Neo knows Trinity and Morpheus, who knows Cypher, who in turn knows Agent Smith.</p>
<h3>Difficulties</h3>
<p>We had only two real challenges in coding this POC.</p>
<p>The first one was an issue with streams and the optional so called <a href="http://en.wikipedia.org/wiki/Byte_Order_Mark">Byte Order Mark (BOM)</a> that you can put at the head of a stream. I’ve posted on this here: <a href="http://blog.jayway.com/2010/04/14/would-you-like-a-byte-order-mark-to-go-with-that/">Would you like a Byte Order Mark to go with that?</a>.</p>
<p>The other challenge was that I wrote a small app for Windows to show our results. But the guys on the Neo team are certainly not Windows users. The wanted to show the code on Mono. Just to be sure of compatibility I scaled back to a good old Windows Forms demo app in .NET Framework 3.0. This worked great on Mono which was our intent. But the drawback was that the library I’d found to handle object serialization didn’t respond well to that old version of the framework. That’s why I replaced my lib with static string creations (as you can see in the implementation of the .StoreNode() method above).</p>
<h3>What have we learned from this?</h3>
<p>First of all creating a client library for .NET to speak REST and json over HTTP to Neo4j is very doable; quite easy and straight forward.</p>
<p>Second (and that’s just a word of warning); keep your layers separated. This goes for all applications I guess but if you start to put code to create instances of web requests with web methods and content types and such in your business code you will end up in a very tangled and messy situation very fast which will be a pain and a high cost to maintain.</p>
<p>Finally we have considered looking into using <a href="http://msdn.microsoft.com/en-us/data/bb931106.aspx">WCF data services</a> (and <a href="http://www.odata.org/">OData</a> – the Open Data Protocol) and also possibly <a href="http://msdn.microsoft.com/en-us/netframework/aa904594.aspx">Linq</a> – Language Integrated Query on the client side to make implementations in the library even more powerful and useful. And we do need a object to json serializer library.</p>
<p>Oh and here is another post on using the Neo4j REST API by the team itself: <a title="http://blog.neo4j.org/2010/04/neo4j-rest-server-part1-get-it-going.html" href="http://blog.neo4j.org/2010/04/neo4j-rest-server-part1-get-it-going.html">http://blog.neo4j.org/2010/04/neo4j-rest-server-part1-get-it-going.html</a></p>
<p>That’s it!</p>
<p>We hope this is inspirational enough for you to get going with your own samples or even client libraries in .NET to speak to Neo4j. If you do; please get back in touch with us!</p>
<p>Cheers,</p>
<p>M.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/04/16/neo4j-net-client-over-http-using-rest-and-json/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Would you like a Byte Order Mark to go with that?</title>
		<link>http://blog.jayway.com/2010/04/14/would-you-like-a-byte-order-mark-to-go-with-that/</link>
		<comments>http://blog.jayway.com/2010/04/14/would-you-like-a-byte-order-mark-to-go-with-that/#comments</comments>
		<pubDate>Wed, 14 Apr 2010 06:45:35 +0000</pubDate>
		<dc:creator>Magnus Mårtensson</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[neo4j]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/2010/04/14/would-you-like-a-byte-order-mark-to-go-with-that/</guid>
		<description><![CDATA[It is possible to encode a little bit of metadata at the beginning of your byte streams to let the stream itself carry information on how it has been encoded. This is known as a Byte Order Mark (BOM) and it is as far as we know completely optional. Some .NET Framework implementations add this [...]]]></description>
			<content:encoded><![CDATA[<p>It is possible to encode a little bit of metadata at the beginning of your byte streams to let the stream itself carry information on how it has been encoded. This is known as a <a href="http://en.wikipedia.org/wiki/Byte_Order_Mark">Byte Order Mark (BOM)</a> and it is as far as we know completely optional. Some .NET Framework implementations add this BOM to the start of streams given that they are to have a specific <a href="http://en.wikipedia.org/wiki/Encoding">encoding</a>. Here is how to find the BOM, and if necessary, remove it from your stream.</p>
<h3>Context</h3>
<p>Recently <a href="http://neo4j.org/">Neo4j</a> graph database announced a <a href="http://en.wikipedia.org/wiki/REST">REST</a> interface. A couple of colleagues at <a href="http://jayway.com">Jayway</a> are working on this. This was (very much) a too intriguing temptation to resist. I naturally had to write a small <a href="http://en.wikipedia.org/wiki/Proof_of_concept">POC</a> .NET based REST client to be able to talk to that server. (Blog post on this is pending within a few days.) While trying to send REST data in HTTP requests to the server we came across something interesting that caused compatibility issues between the Java and .NET worlds. The culprit was that optional byte order mark that I unintentionally embedded in my streams of bytes. The server did not recognize them. In a joint effort from both sides of the world (.NET client and Java server) we were able to find and identify the problem. Not that this is a new problem - It is very well documented in Wikipedia (link above). However I feel that one more post on this topic with a good test to show what’s going on is warranted.</p>
<p>A very good tool was also used to nail down the problem; <a href="http://www.fiddler2.com/fiddler2/">Fiddler2</a>. This little baby of a program is an http proxy that sits on your machine and listens to your http traffic. Using the tool you can inspect exactly what you are sending over the wire in your http requests and also view the responses coming back. Sweet stuff indeed. This is a MUST tool for you if you develop anything that sends data over HTTP.</p>
<p>Using Fiddler2 we were able to observe that when sending a stream of bytes as a body for an http POST the byte length, when the request came from my code, was 108 bytes. However when I used the built in request builder in Fiddler2 to reproduce and resend the exact same request it was reported that the length was 105. Why was there a difference in three (3) bytes?</p>
<p>Problem was that these tree bytes, as I stated above, caused the server to throw a fit. It could not recognize the body of the message to be the expected json string in UTF8 encoding. Json, I’ve learned, is always in UTF8 encoding.</p>
<p>The java guys <a href="http://www.google.se/#hl=sv&amp;source=hp&amp;q=byte+order+mark&amp;meta=lr%3D&amp;aq=f&amp;aqi=g6&amp;aql=&amp;oq=&amp;gs_rfai=&amp;fp=8132a90bf14f85fd">googled</a> and I <a href="http://www.bing.com/search?q=byte+order+mark&amp;go=&amp;form=QBLH&amp;filt=all&amp;qs=n&amp;sk=&amp;sc=1-7">binged</a> ;~) and we found that these three bytes is an optional “byte order mark” or BOM. It is not wrong to send these three bytes and it is not wrong not to send them. Guess what? .The .NET world tends to send these extra bytes and everyone else tends not to. Why not have a bit of more incompatibility, right? It’s not like we want to talk to each other anyway!</p>
<h3>What’s up with the BOM? What is it’s purpose?</h3>
<p>The BOM is a way to add a kind of metadata inside of a stream of bytes instead of sending some actual metadata along next to your stream. Option one is saying “Here is my byte stream and btw it is in UTF8 encoding”. The other way to do it is saying “Here is my byte stream and if you look at the first three bytes you can read the encoding of it”. Which is better? I can’t say I care all that much other than the fact that it caused us a problem when I tried to send requests from .NET code to the Neo4j server.</p>
<h3>How can you then – finally – handle these three bytes?</h3>
<p>Well that depends… on what you intend to do. What I can show you is a piece of code that tells you exactly what this is and then you can copy that behavior into your code and modify it to serve your purpose. The code below should be pretty self explanatory but just to be sure. I take the string <span style="color: #a31515">&quot;foo&quot;</span> and encode it into a <span style="color: #2b91af">MemoryStream</span> using a <span style="color: #2b91af">StreamWriter</span>. The issue is that I tell the stream writer to use <span style="color: #2b91af">Encoding</span>.UTF8 and this is where .NET Framework adds the BOM. The resulting stream is not 3 bytes as perhaps expected. Instead it is 6 bytes long. What you have to do if you read this stream ‘raw’ – by hand – in some library, is skip over the first three bytes. A better way to do it is to use a reader that handles the BOM. Finally if you don’t want to add the BOM in the first place you can write your bytes yourself in a more ‘raw’ fashion byte by byte to the stream. As you can see .NET Framework is good enough to have a way to find an actual BOM for different encodings. The UTF8 encoding does it this way: <span style="color: #2b91af">Encoding</span>.UTF8.GetPreamble() (<a href="http://msdn.microsoft.com/en-us/library/system.text.encoding.getpreamble.aspx">msdn library link to .GetPremable()</a>).</p>
<pre class="code">[<span style="color: #2b91af">TestMethod</span>]
<span style="color: blue">public void </span>StreamWriter_with_encoding_writes_ByteOrderMark()
{
    <span style="color: blue">string </span>str = <span style="color: #a31515">&quot;foo&quot;</span>;

    <span style="color: blue">var </span>memStream = <span style="color: blue">new </span><span style="color: #2b91af">MemoryStream</span>();

    <span style="color: green">// Test
    </span><span style="color: blue">var </span>writer = <span style="color: blue">new </span><span style="color: #2b91af">StreamWriter</span>(memStream, <span style="color: #2b91af">Encoding</span>.UTF8);
    writer.Write(str);
    writer.Flush();

    <span style="color: #2b91af">Assert</span>.AreEqual(6, memStream.Length);

    <span style="color: blue">var </span>buffer = <span style="color: blue">new byte</span>[3];

    memStream.Position = 0;
    memStream.Read(buffer, 0, 3);
    <span style="color: blue">string </span>result = <span style="color: #2b91af">Encoding</span>.UTF8.GetString(buffer);

    <span style="color: blue">var </span>preamble = <span style="color: #2b91af">Encoding</span>.UTF8.GetPreamble();
    <span style="color: blue">var </span>byteOrderMarkUtf8 = <span style="color: #2b91af">Encoding</span>.UTF8.GetString(preamble);

    <span style="color: #2b91af">Assert</span>.AreEqual(byteOrderMarkUtf8, result);

    memStream.Position = 3;
    memStream.Read(buffer, 0, 3);
    result = <span style="color: #2b91af">Encoding</span>.UTF8.GetString(buffer);

    <span style="color: #2b91af">Assert</span>.AreEqual(str, result);

    <span style="color: green">// Alternative: Write the bytes yourself to skip the BOM

    </span>memStream = <span style="color: blue">new </span><span style="color: #2b91af">MemoryStream</span>();

    <span style="color: blue">foreach </span>(<span style="color: blue">var </span>@byte <span style="color: blue">in </span><span style="color: #2b91af">Encoding</span>.UTF8.GetBytes(str))
    {
        memStream.WriteByte(@byte);
    }

    <span style="color: #2b91af">Assert</span>.AreEqual(3, memStream.Length);
}</pre>
<p>You can also if you like compare bytes for the premable one by one rather than converting to a string comparison.</p>
<p>As you can see this BOM can be handled easily if you like. The thing is I did not have a clue that it was there.</p>
<p>Oh – and btw now the Neo4j server accepts REST json bodys that both can have and skip the BOM! Good ‘bug’ to solve or ‘feature’ to have.</p>
<p>Cheers,</p>
<p>M.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/04/14/would-you-like-a-byte-order-mark-to-go-with-that/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Social Computing or Let the bots talk!</title>
		<link>http://blog.jayway.com/2009/09/01/social-computing-or-let-the-bots-talk/</link>
		<comments>http://blog.jayway.com/2009/09/01/social-computing-or-let-the-bots-talk/#comments</comments>
		<pubDate>Tue, 01 Sep 2009 12:45:31 +0000</pubDate>
		<dc:creator>Peter Neubauer</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[linkedprocess]]></category>
		<category><![CDATA[neo4j]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[social computing]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[xmpp]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1918</guid>
		<description><![CDATA[This is a long article to follow up my talk at SSWC, so I will start with a summary for the lazy reader Summary With connected devices, JavaScript enabled web sites and the extensibility of the XMPP protocol, we are at the beginning of a new kind of applications that are operating in the social [...]]]></description>
			<content:encoded><![CDATA[<p>This is a long article to follow up my talk at <a href="http://www.swedensocialwebcamp.com/index.php/Main_Page">SSWC</a>, so I will start with a  summary for the lazy reader <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h2>Summary</h2>
<p>With connected devices, JavaScript enabled web sites and the extensibility of the XMPP protocol, we are at the beginning of a new kind of applications that are operating in the social context of their owners. Google Wave is just the first well known application doing other-than-chatting things on top of XMPP. <a href="http://www.linkedprocess.org">LinkedProcess</a> is trying to lay a foundation for a much more general computing and distribution infrastructure for context-aware, social-spreadable and trusted application scenarios that potentially enable users to regain control over their own graph of information and control access to it using social connections.</p>
<h2>What is XMPP?</h2>
<p>XMPP is an XML instant messaging protocol that was developed by the <a href="http://www.jabber.org/ ">Jabber foundation</a>, as a reaction to the closed protocols of ICQ, Microsoft Messenger etc etc. It is based on the concepts of</p>
<ul>
<li>server side contact lists (Roster in XMPP terminology)</li>
<li>open XML streams between the XMPP server and any connected client once the connection is established</li>
<li>every connected XMPP client gets a unique ID (e.g. "neubauer.peter@gmail.com/phone1/xyz") under the common XMPP "bare" ID (neubauer.peter@gmail.com) and is uniquely addressable by XMPP packets. This can be used in situations where there is no direct IP number available or it is changing (e.g. mobile devices), making any Internet-connected device addressable as a potential server, with a constant address over time and space - an URI.</li>
<li>extensible payloads of XML packets as defined by <a href="http://xmpp.org/">the XMPP Specification</a>, the most important reflecting the 3 paradigms of asynchronous communication, and supported by all major XMPP servers
<ul>
<li>broadcast ("<strong>&lt;presence&gt;</strong>")</li>
<li>one-to-one or one-to-many ("<strong>&lt;message&gt;</strong>")</li>
<li>request/response with acknowledgement ("<strong>&lt;iq&gt;</strong>"), similar to the HTTP protocol</li>
</ul>
</li>
<li>handling of status, presence of resources and routing of messages to the right receivers by the XMPP servers</li>
<li>from the beginning built to scale for the Internet with distributed infrastructure, as explained in <a href="http://www.jivesoftware.com/jivespace/community/jivetalks/blog/2008/01/24/xmpp-aka-jabber-is-the-future-for-cloud-services">this blog post</a></li>
<li>large existing XMPP networks to tap into (GoogleTalk, iChat, Facebook Connect, holding part of your existing social graph in the contact lists) and <a href="http://xmpp.org/software/servers.shtml">open XMPP servers</a> to set up your own XMPP network</li>
<li>SSL support built into the base specification, distributed server-to-server communication even between XMPP networks like GoogleTalk and iChat.</li>
</ul>
<p><a href="xmpp.png" rel="lightbox"><img class="alignnone size-full wp-image-1917" title="xmpp" src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/09/xmpp.png" alt="xmpp" width="522" height="287" /></a><em></em></p>
<p><em>XMPP principle setup</em></p>
<h2>Why should I care about XMPP?</h2>
<ul>
<li>XMPP is the currently most popular infrastructure for instant communication, used by systems like iChat, Google Talk and Google Wave. These are just a few of the possible applications we can do on top of XMPP, Twitter and TiVo are rumored to follow</li>
<li>via the use of a server side contact list of peers in any XMPP communication, suddenly there is a social or trust-like aspect to any XMPP conversation between two or more participating systems, users or devices</li>
<li>any modern mobile phone, javascript-enabled website, J2ME, Java or Flash-capable home automation device (e.g. BluRay players or media servers) or server application can talk XMPP and thus become a true peer to the other clients, without any new server side infrastructure or cloud service development more than existing XMPP servers for routing via e.g. http://www.kaazing.com, HTML5 web sockets or various XMPP libraries for <a href="http://code.stanziq.com/strophe/">JavaScript</a>, <a href="http://www.igniterealtime.org/projects/xiff/index.jsp">ActionScript</a>, <a href="http://www.igniterealtime.org/projects/openfire/index.jsp"> for an XMPP server</a> and <a href="http://www.igniterealtime.org/projects/smack/index.jsp"> Smack for Java</a>.</li>
</ul>
<h2>What can we do with this?</h2>
<p>Now, with all these characteristics in place, we can look at the different emerging platforms for XMPP communication:</p>
<h3>Chat - simple text exchange</h3>
<p>This is the simple tracking of presence for XMPP clients and the exchange of only human-readable text messages between them. However, a certain coolness is added by being able to distinguish between different clients logged in under the same XMPP account (e.g. different browser windows logging into GTalk and still sending and receiving in the right window). This has been in use for the past 15 years and is nothing new, even if the clients have gotten lighter and fancier over the years (see figure, marie@neubauer.se talking from the browser to neubauer.peter@gmail.com on iChat).</p>
<p><em><img class="alignnone size-full wp-image-1910" title="chat" src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/09/chat.png" alt="chat" width="589" height="167" /></em></p>
<p><em>Normal XMPP chat setup</em></p>
<h3>Google Wave - concurrent document editing on steroids</h3>
<p>Google Wave is introducing a concept where a central XML document (the Wave), reflecting the total of a conversation, is simultaneously edited by several participants (via XMPP clients) of the conversation at the same time. While the incremental changes are sent to the XMPP Google Wave server for merging into the central Wave, they are at the same time even sent to the other online clients in the Roster of the current conversation just as chat messages, creating the real-time response impression of the Google Wave experience. However, these packages do not contain simple chat but actual machine-data interpreted by special Google Wave clients in e.g. JavaScript (see <a href="http://www.waveprotocol.org/">the Wave Protocol</a><a></a>).<br />
Google Wave even supports extensions to its functionality, see <a href="http://mashable.com/2009/06/11/google-wave-extensions/">this blog post</a> which means that a lot of the infrastructure can be used to e.g. support new functionality and data packets.</p>
<p><em><img class="alignnone size-full wp-image-1913" title="gwave" src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/09/gwave.png" alt="gwave" width="575" height="277" /></em></p>
<p><em>Google Wave setup</em></p>
<h2>LinkedProcess - turn any connected device into a server with a social context</h2>
<p><a href="http://www.linkedprocess.org">LinkedProcess (LoP)</a>, driven by <a href="http://markorodriguez.com">Marko Rodriguez</a> and <a href="http://fortytwo.net/">Joshua Shinavier</a> is taking the approach of providing a set of XMPP tags for sending scripts and code snippets from XMPP clients ("LoP Villeins") to other XMPP peers acting as servers ("LoP Farms"), get them executed there and the result sent back. The thought is to be able to speed up the processing aspect of the emerging Semantic Web/Web of Data by moving the processes to the data instead of the usual move of the data to the processor.<br />
One huge application is the processing of the emerging Semantic Web or Linked Data (<a href="http://www.ted.com/index.php/talks/tim_berners_lee_on_the_next_web.html">Tim Berners Lee talks about that at TED 2009</a>) by sending processing instructions to the big servers holding large chunks of this emerging graph structure instead of having to pull all data onto your own device prior to processing it (see the <a href="http://code.google.com/p/linkedprocess/wiki/Introduction">LinkedProcess introduction</a>).</p>
<p><em><img class="alignnone size-full wp-image-1911" title="cloud" src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/09/cloud.png" alt="cloud" width="514" height="308" /></em></p>
<p><em>LinkedProcess distributed processing of LinkedData setup</em></p>
<p>This has a number of interesting aspects:</p>
<ul>
<li>any XMPP capable client (mobile phones, websites etc) can be turned into a server being in direct contact with its peers</li>
<li>data can stay at one logical place (e.g. the mobile phone) while others can send scripts to operate to the data in order to get ad-hoc queries executed</li>
<li>code can be spread within the social context, so scripts can be shared and spread through the social network of resources and people rapidly, without special installation hassle, giving birth to truly viral "web- and mobile only" applications and social networks of both humans, content and hardware</li>
<li>the access to the computing resources and data is controlled via the contact list of the XMPP client executing the script. Thus, it is always known who is trying to access the LinkedProcess server</li>
<li>via the use of existing or new social chat networks, this extends the social aspect of your contact list to any XMPP speaking resource under your account, persons, devices and software alike.</li>
</ul>
<h2>So, what is social about LinkedProcess?</h2>
<p>Well, with all this said, we have suddenly a couple of very interesting concrete scenarios:</p>
<h3>1. Personal and Social Could Computing</h3>
<p>This is the concept of spreading code to execute on other servers and devices that are available within the social context of the sender - either a number of servers being set up under the same bare account or friends and colleagues providing their resources to others in their social vicinity. E.g. if I want to transcode a HD movie from <a href="http://www.ted.com">TED</a> to fit my mobile phone, I could send a script to my home server instructing the server to download the appropriate encoder, download the original high-resolution link and put the result onto a URL and return that to me. Totally Ad Hoc, without any new programs installed in my phone or the server afterwards.</p>
<p><em><img class="alignnone size-full wp-image-1915" title="social_cloud" src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/09/social_cloud.png" alt="social_cloud" width="535" height="335" /></em></p>
<p><em>The Social Cloud</em></p>
<h3>2. Totally distributed and viral social apps - my personal Facebook</h3>
<p>A user writes, downloads or is recommended a script - "SOClet" (written in e.g. LUA or Python for Android phones, see Android Sctripting Environment) that asks all its friends phones to evaluate if there is any content related to the asking phones owner. If yes, return the URIs of matching content on the friends phones. That results in an aggregated feed on "Pictures of me by my friends, friends statuses etc" - a Facebook- like setup, totally up to every individual to customize and no central storage. Of course if desired there can be a central server as an equal XMPP client in the middle in order to help holding state, much like the Google Wave setup.</p>
<p><em><img class="alignnone size-full wp-image-1914" title="mobile" src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/09/mobile.png" alt="mobile" width="542" height="347" /></em></p>
<p><em>Viral apps spreading in the social device context across mobile devices and e.g. web pages</em></p>
<h3>3. Installing servers on phones and other resources</h3>
<p>The technical use setup is as the previous one, but here, long running server code is executed on your friends devices and thus, we create new services on top of the LinkedProcess infrastructure, and turn the devices into mini-servers. This serves potential use cases like <a href="http://unite.opera.com/">Opera Unite</a>, although not with a central namespace like Unite but totally distributed. Peter could for instalnce install a script on Maries phone serving an RSS feed back to Peter when he asks for new content every 5 minutes, including the current location. This can easily be displayed as a GeoRSS over a map on Peters phone or used to mash up the feed with other information using e.g. <a href="http://pipes.yahoo.com">Yahoo Pipes</a>. This could even be done from a web page (e.g. in Facebook), resulting in a Facebook application that talks to the phone directly and can mash up live phone data with the rest of the Facebook data.</p>
<h3>4. Privacy and ownership of everybody's personal information</h3>
<p>By turning the physical holder of your own data - the phone or your home desktop - into a server that accepts or denies requests for operations on that data, users regain control over the personal data. Imagining different protection zones (private, business, open), access can then be granted via the social contact list to individuals, groups of contacts (e.g. friends, co-workers in a project) or anyone.<br />
If unknown or public clients like e.g. Google bots want to access that information, even commercial transactions can be attached and making the commercial client sending the script or access request pay for access to e.g. the GPS location, thus reversing the current notion of users spreading their data and its connections into multiple commercial cloud services, paying with their copyright, usage patterns and privacy only to be forced to aggregate the total personal information again via services like FriendFeed, Plaxo etc.<br />
In the longer run, the total personal information, turned into a consistent personal graph of information with data models like <a href="http://www.neo4j.org">Neo4j, a Graph Database</a> would of course be held physically at more convenient locations than a non-backed up mobile phone and linked to the other personal sources of new information like desktop computers and embedded devices like cameras and GPS.</p>
<p><em><img class="alignnone size-full wp-image-1912" title="graph" src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/09/graph.png" alt="graph" width="325" height="402" /></em></p>
<p><em>Socially controlled access to the personal information</em></p>
<h3>5. Social home automation and media sharing, the Internet Of Things</h3>
<p>With media and home automation devices having Internet access (TV, set top boxes, media servers, stereo), installing XMPP aware software on them or providing a <a href="http://en.wikipedia.org/wiki/Digital_Living_Network_Alliance">DLNA</a>/XMPP gateway on my home computer under my personal account will expose these as different accessible resources on the Internet, without the intervention of firewalls, wireless routers etc. So, now my friends LinkedProcess enabled phone marie@neubuaer.se/phone1 can discover my living room TV, peter@neubaeur.se/tv1 since I am in Maries Roster, and the TV is AVAILABLE in XMPP. It discovers the capabilities of the TV much like DLNA and <a href="http://en.wikipedia.org/wiki/Universal_Plug_and_Play">UPnP</a> and then either sends over the latest photo stream to my TV directly, or negotiates means of doing so, e.g. via FTP to a third server. Voila, the home automation is freed onto the Internet and visible and controlled by me and the friends I trust. The same goes for lamps, fridges, home security systems etc with the appropriate bridging in place on a convenient machine, e.g. your home media server. For an actual implementation of light-control via XMPP, see <a href="http://blog.intuitymedialab.eu/2009/08/27/lab-session-making-things-talk-01-controlling-lights-with-your-mobile-via-xmpp">this bridging lab</a></p>
<p><em><img class="alignnone size-full wp-image-1916" title="things" src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/09/things.png" alt="things" width="563" height="310" /></em></p>
<p><em>Home autmomation devices, directly or via an UPnP/XMPP bridge exposed to LinkedProcess</em></p>
<h2>Conclusion</h2>
<p>These are just some use cases that one can think of when it comes to merging the key ingredients:</p>
<ul>
<li>status aware, realtime, lightweight messaging infrastructure with contact list support</li>
<li>widely used infrastructure with existing contact networks (GTalk, iChat etc)</li>
<li>Open Platforms like LinkedProcess providing the protocol for communication and exchange of machine-readable data packets</li>
</ul>
<p>With the advent of Google Wave, I think the time has come to realize the great potential in Social Computing - introducing social aspects into core programming, security and distribution paradigms.</p>
<p>/peter neubauer</p>
<p>Co-founder, <a href="http://www.neotechnology.com">NeoTechnology</a></p>
<p>Consultant, <a href="http://www.jayway.se">Jayway</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/09/01/social-computing-or-let-the-bots-talk/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Spring and load-time weaving of Neo4j-based domain objects</title>
		<link>http://blog.jayway.com/2009/05/26/spring-and-load-time-weaving-of-neo4j-based-domain-objects/</link>
		<comments>http://blog.jayway.com/2009/05/26/spring-and-load-time-weaving-of-neo4j-based-domain-objects/#comments</comments>
		<pubDate>Tue, 26 May 2009 07:51:25 +0000</pubDate>
		<dc:creator>Mattias Ask</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[ddd]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[neo4j]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1773</guid>
		<description><![CDATA[What do you do when your Spring configuration isn't in charge of creating your objects that needs to be injected with stuff? This became a real problem for me when I tried doing some non-anemic domain object implementations persisted as Neo4j Nodes. I was playing around with creating a Twitter clone, in my opinion the [...]]]></description>
			<content:encoded><![CDATA[<p>What do you do when your Spring configuration isn't in charge of creating your objects that needs to be injected with stuff? This became a real problem for me when I tried doing some non-anemic domain object implementations persisted as <a href="http://www.neo4j.org">Neo4j</a> Nodes. </p>
<p>I was playing around with creating a Twitter clone, in my opinion the "Hello World" of graph databases, and I started out with the following simple service.</p>
<p>Spring configurating:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;beans</span> ... <span style="font-weight: bold; color: black;">&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;context:annotation-config</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;neo&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.neo4j.api.core.EmbeddedNeo&quot;</span>
		<span style="color: #000066;">destroy-method</span>=<span style="color: #ff0000;">&quot;shutdown&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;constructor-arg<span style="font-weight: bold; color: black;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;value<span style="font-weight: bold; color: black;">&gt;</span></span></span>var/neo<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/value<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/constructor-arg<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;indexService&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.neo4j.util.index.NeoIndexService&quot;</span>
		<span style="color: #000066;">destroy-method</span>=<span style="color: #ff0000;">&quot;shutdown&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;constructor-arg</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;neo&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;twitterService&quot;</span>
		<span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;com.jayway.twitter.neo.NeoBasedTweetService&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;neo&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;neo&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;indexService&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;indexService&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #808080; font-style: italic;">&lt;!-- Transactions --&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;tx:annotation-driven</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
        ...
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/beans<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>The service:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> NeoBasedTweetService <span style="color: #000000; font-weight: bold;">implements</span> TweetService <span style="color: #66cc66;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">protected</span> NeoService neo;
	<span style="color: #000000; font-weight: bold;">protected</span> IndexService indexService;
&nbsp;
	<span style="color: #808080; font-style: italic;">//Setters for neo and indexService</span>
&nbsp;
	@Transactional
	<span style="color: #000000; font-weight: bold;">public</span> Tweet createTweet<span style="color: #66cc66;">&#40;</span>User user, <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> tweet<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		UserNode userNode = <span style="color: #000000; font-weight: bold;">new</span> UserNode<span style="color: #66cc66;">&#40;</span>indexService.<span style="color: #006600;">getSingleNode</span><span style="color: #66cc66;">&#40;</span>
				TwitterIndexConstants.<span style="color: #006600;">INDEX_USER</span>, user.<span style="color: #006600;">getUserName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		TweetNode tweetNode = <span style="color: #000000; font-weight: bold;">new</span> TweetNode<span style="color: #66cc66;">&#40;</span>neo.<span style="color: #006600;">createNode</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		tweetNode.<span style="color: #006600;">setKvitt</span><span style="color: #66cc66;">&#40;</span>tweet<span style="color: #66cc66;">&#41;</span>;
		userNode.<span style="color: #006600;">createRelationshipTo</span><span style="color: #66cc66;">&#40;</span>tweetNode, KvittRelationships.<span style="color: #006600;">KVITTRAT</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000000; font-weight: bold;">return</span> tweetNode;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Services to create User and more</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>This doesn't feel very DDD. I would really want to do the User to be responsible for creating the Tweet. Like this:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> NeoBasedTweetService <span style="color: #000000; font-weight: bold;">implements</span> TweetService <span style="color: #66cc66;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">protected</span> NeoService neo;
	<span style="color: #000000; font-weight: bold;">protected</span> IndexService indexService;
&nbsp;
	<span style="color: #808080; font-style: italic;">//Setters for neo and indexService</span>
&nbsp;
	@Transactional
	<span style="color: #000000; font-weight: bold;">public</span> Tweet createTweet<span style="color: #66cc66;">&#40;</span>User user, <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> tweet<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		UserNode userNode = <span style="color: #000000; font-weight: bold;">new</span> UserNode<span style="color: #66cc66;">&#40;</span>indexService.<span style="color: #006600;">getSingleNode</span><span style="color: #66cc66;">&#40;</span>
				TwitterIndexConstants.<span style="color: #006600;">INDEX_USER</span>, user.<span style="color: #006600;">getUserName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000000; font-weight: bold;">return</span> userNode.<span style="color: #006600;">createTweet</span><span style="color: #66cc66;">&#40;</span>tweet<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Services to create User and more</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>The TweetNode and UserNode would look like this:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TweetNode <span style="color: #000000; font-weight: bold;">extends</span> NodeDelegate <span style="color: #000000; font-weight: bold;">implements</span> Tweet <span style="color: #66cc66;">&#123;</span>
&nbsp;
	TweetNode<span style="color: #66cc66;">&#40;</span>Node underlyingNode<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span><span style="color: #66cc66;">&#40;</span>underlyingNode<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Methods for doing Tweet-stuff</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> UserNode <span style="color: #000000; font-weight: bold;">extends</span> NodeDelegate <span style="color: #000000; font-weight: bold;">implements</span> User<span style="color: #66cc66;">&#123;</span>
&nbsp;
	UserNode<span style="color: #66cc66;">&#40;</span>Node underlyingNode<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span><span style="color: #66cc66;">&#40;</span>underlyingNode<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Methods for doing User-stuff</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> Tweet createTweet<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> kvitt<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #808080; font-style: italic;">//Here comes a problem! I need a new Node</span>
		<span style="color: #808080; font-style: italic;">//from the NeoService to create the TweetNode</span>
		TweetNode tweetNode = <span style="color: #000000; font-weight: bold;">new</span> TweetNode<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span>;
		tweetNode.<span style="color: #006600;">setTweet</span><span style="color: #66cc66;">&#40;</span>tweet<span style="color: #66cc66;">&#41;</span>;
		createRelationshipTo<span style="color: #66cc66;">&#40;</span>tweetNode, TwitterRelationships.<span style="color: #006600;">TWEETED</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000000; font-weight: bold;">return</span> tweetNode;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>NodeDelegate, extended by both User- and TweetNode implements the Neo4j interface <code>Node</code> and delegates all the method calls to the underlying node ( for more on this, see my <a href="http://blog.jayway.com/2008/10/06/neo4j-matches-my-mental-model-of-information/">previous post</a>) :</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> NodeDelegate <span style="color: #000000; font-weight: bold;">implements</span> Node <span style="color: #66cc66;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Node delegate;
&nbsp;
	<span style="color: #000000; font-weight: bold;">protected</span> NodeDelegate<span style="color: #66cc66;">&#40;</span>Node underlyingNode<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		delegate = underlyingNode;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Methods for delegating all Node methods to the Node delegate</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>As you see I have a problem here. In the first version my NeoService is injected into NeoBasedTweetService and used when I create the new TweetNode. In the re-made, more DDD-style example I create the new TweetNode in the UserNode, where I don't have access to my NeoService. How do we solve this?</p>
<p>One alternative that I instinctively dislike is to inject the NeoService into the UserNode. The reason for me disliking this is that my UserNode IS a Node, and it feels very tangled if a Node holds a reference to its container. But I came to think of another solution thanks to a talk I did a while back together with Henrik Reinhold on what was new in Spring 2.5. </p>
<p>In Spring 2.5 load-time weaving (LTW) capabillites was introduced, and with LTW you can manipulate objects in load-time, as opposed to runtime weaving that is proxy based. This, combine it with @Configurable and @Autowired, proves to be <em>very</em> helpful when the Spring context is not in charge of creating the objects in question, as in the example above...</p>
<p>To enable LTW we add one tag in the Spring configuration:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;context:load-time-weaver</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
&nbsp;</pre>
<p>After that we have to inform the Spring container of how we want thing done. To do we edit the TweetNode and NodeDelegate like this:</p>
<pre class="java">&nbsp;
<span style="color: #808080; font-style: italic;">//Annotate the class with @Configurable so that Spring can find it.</span>
@Configurable
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TweetNode <span style="color: #000000; font-weight: bold;">extends</span> NodeDelegate <span style="color: #000000; font-weight: bold;">implements</span> Tweet <span style="color: #66cc66;">&#123;</span>
&nbsp;
	TweetNode<span style="color: #66cc66;">&#40;</span>Node underlyingNode<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span><span style="color: #66cc66;">&#40;</span>underlyingNode<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Add a default constructor both in the TweetNode</span>
	<span style="color: #808080; font-style: italic;">//and the NodeDelegate, it is new:able without a Node.</span>
	<span style="color: #000000; font-weight: bold;">public</span> TweetNode<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Add a setter for the underlaying Node and annotate it with @Autowired.</span>
	@Autowired
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setNode<span style="color: #66cc66;">&#40;</span>Node nodeDelegate<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006600;">setNode</span><span style="color: #66cc66;">&#40;</span>nodeDelegate<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Tweet-methods as before</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> NodeDelegate <span style="color: #000000; font-weight: bold;">implements</span> Node <span style="color: #66cc66;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Node delegate;
&nbsp;
	<span style="color: #000000; font-weight: bold;">protected</span> NodeDelegate<span style="color: #66cc66;">&#40;</span>Node underlyingNode<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		delegate = underlyingNode;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">protected</span> NodeDelegate<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> setNode<span style="color: #66cc66;">&#40;</span>Node nodeDelegate<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>delegate == <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
			delegate = nodeDelegate;
		<span style="color: #66cc66;">&#125;</span>
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Methods for delegating all Node methods to the Node delegate</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Now Spring only has to be able to create Nodes. To do that we create a simple NodeFactory, like this:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> NodeFactory <span style="color: #000000; font-weight: bold;">implements</span> FactoryBean<span style="color: #66cc66;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> NeoService neo = <span style="color: #000000; font-weight: bold;">null</span>;
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setNeo<span style="color: #66cc66;">&#40;</span>NeoService neo<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">neo</span> = neo;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	@Transactional
	<span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> getObject<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> neo.<span style="color: #006600;">createNode</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">Class</span> getObjectType<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> Node.<span style="color: #000000; font-weight: bold;">class</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">boolean</span> isSingleton<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">false</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>... and add it to the configuration, like this:</p>
<pre class="xml">&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;node&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;com.jayway.neo.utils.NodeFactory&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;neo&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;neo&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>The result of this is that Spring now has a NodeFactory that returns a new node for every request, I have annotated the TweetNode so that Spring knows of it (@Configurable) and what to do with it (@Autowired on setNode) and I've enabled load-time weaving in order to get the a new Node woven into a TweetNode every time a new instance of it is created in the code.</p>
<p>In UserNode I really don't have to make any changes. "setNode(Node)" will get a new Node after the instantiation of a TweetNode, even if the constructor that takes a Node is called. For clarity I still changed the UserNode as follows:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> UserNode <span style="color: #000000; font-weight: bold;">extends</span> NodeDelegate <span style="color: #000000; font-weight: bold;">implements</span> User<span style="color: #66cc66;">&#123;</span>
&nbsp;
	UserNode<span style="color: #66cc66;">&#40;</span>Node underlyingNode<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span><span style="color: #66cc66;">&#40;</span>underlyingNode<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">//Methods for doing User-stuff</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> Tweet createTweet<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> kvitt<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #808080; font-style: italic;">//This TweetNode will get a Node set by Spring</span>
		TweetNode tweetNode = <span style="color: #000000; font-weight: bold;">new</span> TweetNode<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		tweetNode.<span style="color: #006600;">setTweet</span><span style="color: #66cc66;">&#40;</span>tweet<span style="color: #66cc66;">&#41;</span>;
		createRelationshipTo<span style="color: #66cc66;">&#40;</span>tweetNode, TwitterRelationships.<span style="color: #006600;">TWEETED</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000000; font-weight: bold;">return</span> tweetNode;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>The problem I had when trying to make the UserNode responsible for creating its TweetNode's was that I needed to inject something that could create Nodes into the UserNodes. By using load-time weaving and instructing Spring of how to wire a TweetNode I don't have to pass my NeoService around to all the UserNodes created in my code. Instead I can rely on Spring to inject what is needed, when it's needed.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/05/26/spring-and-load-time-weaving-of-neo4j-based-domain-objects/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Neo4j matches my mental model of information</title>
		<link>http://blog.jayway.com/2008/10/06/neo4j-matches-my-mental-model-of-information/</link>
		<comments>http://blog.jayway.com/2008/10/06/neo4j-matches-my-mental-model-of-information/#comments</comments>
		<pubDate>Mon, 06 Oct 2008 11:27:55 +0000</pubDate>
		<dc:creator>Mattias Ask</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[graph database]]></category>
		<category><![CDATA[neo4j]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=335</guid>
		<description><![CDATA[I'm a visual person which means that I see pictures in my head when I think about abstract things like structure, code and information. My guess is that most people do, but anyway... When I first started looking at Neo4j I was blown away by how precise the graph database structure matched my mental model [...]]]></description>
			<content:encoded><![CDATA[<p>I'm a visual person which means that I see pictures in my head when I think about abstract things like structure, code and information. My guess is that most people do, but anyway...</p>
<p>When I first started looking at <a href="http://neo4j.org/">Neo4j</a> I was blown away by how precise the graph database structure matched my mental model of information. You have blobs of informations (nodes with properties) that relates to other blobs of information. Perfect! </p>
<p>When I started playing around with the API I couldn't do what I wanted, namely extend NodeImpl and make the objects I want to persist Nodes. Now, Neo4j has a very nice API which is hard to abuse (if you don't place your classes in the same namespace as they use), and understandably they don't want you to extend NodeImpl. The <a href="http://wiki.neo4j.org/content/Design_Guide">design guide</a> gives this example of use:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> CustomerImpl <span style="color: #000000; font-weight: bold;">implements</span> Customer<span style="color: #66cc66;">&#123;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> Node underlyingNode;
&nbsp;
        <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> KEY_FIRST_NAME = <span style="color: #ff0000;">&quot;firstName&quot;</span>;
&nbsp;
        CustomerImpl<span style="color: #66cc66;">&#40;</span> Node underlyingNode <span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">underlyingNode</span> = underlyingNode;
        <span style="color: #66cc66;">&#125;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setFirstName<span style="color: #66cc66;">&#40;</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> firstName <span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
                underlyingNode.<span style="color: #006600;">setProperty</span><span style="color: #66cc66;">&#40;</span> KEY_FIRST_NAME, firstName <span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> getFirstName<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #66cc66;">&#40;</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> <span style="color: #66cc66;">&#41;</span> underlyingNode.<span style="color: #006600;">getProperty</span><span style="color: #66cc66;">&#40;</span> KEY_FIRST_NAME <span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span>
&nbsp;
        <span style="color: #808080; font-style: italic;">// ...</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>That's great, but it doesn't match what I see in my head... In order to make things match I made a subtle change. </p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> NodeDelegate <span style="color: #000000; font-weight: bold;">implements</span> Node <span style="color: #66cc66;">&#123;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">private</span> Node delegate;
&nbsp;
        <span style="color: #000000; font-weight: bold;">protected</span> NodeDelegate<span style="color: #66cc66;">&#40;</span>Node node<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
                delegate = node;
        <span style="color: #66cc66;">&#125;</span>
&nbsp;
        <span style="color: #808080; font-style: italic;">// Delegate all methods of the Node interface to the</span>
        <span style="color: #808080; font-style: italic;">// Node received in the constructor...</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> CustomerNode <span style="color: #000000; font-weight: bold;">extends</span> NodeDelegate <span style="color: #000000; font-weight: bold;">implements</span> Customer <span style="color: #66cc66;">&#123;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> KEY_FIRST_NAME = <span style="color: #ff0000;">&quot;firstName&quot;</span>;
&nbsp;
        CustomerNode<span style="color: #66cc66;">&#40;</span>Node node<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">super</span><span style="color: #66cc66;">&#40;</span>node<span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setFirstName<span style="color: #66cc66;">&#40;</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> firstName <span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
                setProperty<span style="color: #66cc66;">&#40;</span> KEY_FIRST_NAME, firstName <span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> getFirstName<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #66cc66;">&#40;</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> <span style="color: #66cc66;">&#41;</span> getProperty<span style="color: #66cc66;">&#40;</span> KEY_FIRST_NAME <span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span>
&nbsp;
        <span style="color: #808080; font-style: italic;">// ...</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>By doing this I can work with my domain objects as Nodes. I don't know if it is "correct" but with this small change I can say that "A Customer IS a Node" and this is what I see in my head. Good? Bad? You be the judge, but it fits me <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/10/06/neo4j-matches-my-mental-model-of-information/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

