<?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>Xebia Blog &#187; Jeroen van Wilgenburg</title>
	<atom:link href="http://blog.xebia.com/author/jvanwilgenburg/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.xebia.com</link>
	<description>Software development done right!</description>
	<lastBuildDate>Wed, 01 Feb 2012 00:30:00 +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>Scala ORM with Squeryl &#8211; A simple getting started guide</title>
		<link>http://blog.xebia.com/2011/06/25/scala-orm-with-squeryl/</link>
		<comments>http://blog.xebia.com/2011/06/25/scala-orm-with-squeryl/#comments</comments>
		<pubDate>Sat, 25 Jun 2011 16:46:02 +0000</pubDate>
		<dc:creator>Jeroen van Wilgenburg</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[sbt]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[squeryl]]></category>

	<!-- AutoMeta Start -->
	<category>squeryl</category>
	<category>movies</category>
	<category>movies</category>
	<category>squeryl_sbt_minimal_example</category>
	<category>intransaction</category>
	<category>scweery</category>
	<category>movie</category>
	<category>postgresql</category>
	<category>squeryl</category>
	<category>movies</category>
	<category>movies</category>
	<category>squeryl_sbt_minimal_example</category>
	<category>intransaction</category>
	<category>scweery</category>
	<category>movie</category>
	<category>postgresql</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=7023</guid>
		<description><![CDATA[Since my pet project (I will eventually blog about that) is in desperate need of a database and I&#8217;m doing enough Java on my day job I decided to give a Scala ORM framework a shot. I have to warn you that I&#8217;m kind of a Scala hacker. I abuse it like a scripting language [...]]]></description>
			<content:encoded><![CDATA[<p>Since my pet project (I will eventually blog about that) is in desperate need of a database and I&#8217;m doing enough Java on my day job I decided to give a Scala ORM framework a shot.<br />
I have to warn you that I&#8217;m kind of a Scala hacker. I abuse it like a scripting language and usually grab some examples, put them together and wait for my colleagues to say &#8220;You don&#8217;t want that&#8221; or &#8220;You&#8217;re doing it wrong&#8221;. So don&#8217;t hesitate to correct me, maybe I&#8217;ll learn something too <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p><span id="more-7023"></span></p>
<h2>Picking the right ORM-framework</h2>
<p>I didn&#8217;t do any extensive research, just some googling. A framework called Scweery popped up. The name <a href="http://twitter.com/#!/scweery" target="_blank">Scweery</a> sounded very nice and it has a Twitter account with a funny avatar, so why look any further? Well, it seems the project isn&#8217;t that active anymore (no updates for over a year and that&#8217;s a long time with Scala).<br />
Finally Stackoverflow came to the rescue. I found a question called <a href="http://stackoverflow.com/questions/1362748/wanted-good-examples-of-scala-database-persistence" target="_blank">Examples of Scala database persistence</a> . I picked <a href="http://squeryl.org" target="_blank">Squeryl</a>, the syntax looked nice and there was useful documentation. I&#8217;m not sure whether I picked the right framework, but it survived my initial selection, so let&#8217;s find out.</p>
<h2>Setting up the environment</h2>
<p>For this article I assume the following:</p>
<p>-You have version 2.9.0 of <a href="http://www.scala-lang.org/downloads" target="_blank">Scala</a> installed<br />
-<a href="http://git-scm.com/" target="_blank">Git</a> is on your system<br />
-<a href="https://github.com/harrah/xsbt/wiki/Setup" target="_blank">SBT</a> is available on the command line (I used version 0.7.7)</p>
<p>I believe the links above explain everything pretty well, so let&#8217;s get started!</p>
<h2>Getting started</h2>
<p>I used the &#8216;minimal example&#8217; project to get started:</p>
<pre class="brush: bash; title: ; notranslate">
git clone https://github.com/pbrant/squeryl_sbt_minimal_example
cd squeryl_sbt_minimal_example
squeryl_sbt_minimal_example&gt;sbt
....
[info]    using ExampleProject with sbt 0.7.7 and Scala 2.9.0
squeryl_sbt_minimal_example&gt;update
.....
squeryl_sbt_minimal_example&gt;compile
squeryl_sbt_minimal_example&gt;run
</pre>
<p>I updated the Scala version to 2.9.0. This can be done by changing the version number project/build/build.properties. For this article it doesn&#8217;t matter much, but for your real project this newer version has lots of improvements.</p>
<p>That went pretty smooth. Let&#8217;s rip everything out and use Postgres. Open the file Main.scala (/src/main/scala/code). First remove drop, create and printDdl. We don&#8217;t want our valuable production database to be destroyed!<br />
For my database testing I use my good old movie database. With ancient column names (in Dutch) and the ID column is a String. This might sound like a bad idea, but real databases are like this and I found out it&#8217;s a good way to test a new framework.</p>
<h3>Schema definition</h3>
<p>The first section to change is Library extends Schema. This is the section where the tables are defined. My table is called movies.</p>
<pre class="brush: scala; title: ; notranslate">
val movies = table[Movies]
</pre>
<p>When running the example (with some additional code, so don&#8217;t try it yet) I got the following error:<br />
org.postgresql.util.PSQLException: ERROR: relation &#8220;Movies&#8221; does not exist</p>
<p>It seems the queries are executed with the table names surrounded with double quotes, which means case sensitive. To solve this append (&#8220;MOVIES&#8221;) to the table definition. Now we can also solve the problem that a class is singular (unlike a database table). Now I can call the class Movie instead of Movies:</p>
<pre class="brush: scala; title: ; notranslate">
val movies = table[Movie](&quot;MOVIES&quot;)
</pre>
<h3>Table definition</h3>
<p>Our next step is the table definition. (In Dutch, &#8220;jaar&#8221; means &#8220;year&#8221; and &#8220;naam&#8221; means &#8220;name&#8221;) This time we have to use annotations to use other column names (to get rid of typos and underscores):</p>
<pre class="brush: scala; title: ; notranslate">
class Movie(
 @Column(&quot;imdb_id&quot;)
 val imdbId: String,
 @Column(&quot;jaar&quot;)
 val year: Int,
 @Column(&quot;naam_film&quot;)
 val name: String,
 @Column(&quot;genre&quot;)
 val genres: String
)
</pre>
<p>Note that I used val for the columns, when the columns are mutable it&#8217;s allowed to use var.</p>
<h3>Connecting to Postgresql</h3>
<p>To connect to to a Postgres database replace the H2 dependency in /project/build/ExampleProject.scala with</p>
<pre class="brush: scala; title: ; notranslate">
val pg = &quot;postgresql&quot; % &quot;postgresql&quot; % &quot;9.0-801.jdbc4&quot;
</pre>
<p>Now go to the main method in Main.scala and replace the driver and connection parameters:</p>
<pre class="brush: scala; title: ; notranslate">
Class.forName(&quot;org.postgresql.Driver&quot;);
SessionFactory.concreteFactory = Some(() =&gt;
 Session.create(
 java.sql.DriverManager.getConnection(&quot;jdbc:postgresql://localhost/moviedb&quot;, &quot;bill&quot;, &quot;s3cr3tp455w0rdth4t15nt5053cr3t4nym0r3n0w&quot;),
 new PostgreSqlAdapter)
)
</pre>
<p>At a first glance it just looks like JDBC, but the Some(()=&gt;..) notation might be a bit odd. This is by-name-parameter, just see it as a function that creates a session whenever needed.</p>
<h3>A select * from</h3>
<p>The final section is doing the actual query:</p>
<pre class="brush: scala; title: ; notranslate">
inTransaction {
 val movies = from(Library.movie)(select(_))
 for (movie &lt;- movies){
 println (movie.name)
 }
}
</pre>
<p>To execute queries you need a transaction (also for read only queries). A transaction is available after the initialization of the SessionFactory.concreteFactory. To run code in a transaction wrap it in an inTransaction block (you can also use &#8216;transaction&#8217;, this always starts a new transaction, inTransaction only does when there is no transaction in progress).</p>
<p>The first line in the inTransaction block does a select * from movie.</p>
<p>Scala might be a bit confusing when you&#8217;re new to it, like me. The scaladocs might help. From can be found <a href="http://squeryl.org/api/org/squeryl/dsl/boilerplate/FromSignatures.html" target="_blank">here</a> and select <a href="http://squeryl.org/api/org/squeryl/dsl/fsm/SelectState.html" target="_blank">here</a>.</p>
<p>The statement should read like this: from Library.movie apply each row to the select function. The second set of parameters for from (the so called Queryable) can be expanded with where and order by clauses. For more information read the <a href="http://squeryl.org/selects.html" target="_blank">page about selects</a> on the Squeryl website.</p>
<p>The for loop of course prints all the movie names.</p>
<h3>&#8216;Advanced&#8217; queries</h3>
<p>The previous paragraph was just a simple query you&#8217;ll probably never execute in real life. So let&#8217;s try something a little bit more difficult:</p>
<pre class="brush: scala; title: ; notranslate">
inTransaction {
 val movies = from(Library.movie)(s=&gt;
 where(s.year === 1994)
 select(s) )
 println(movies)
 for (movie &lt;- movies){
 println (movie.name)
 }
}
</pre>
<p>The operator === is a method that is added to Int (this construction is called &#8216;implicit&#8217;) to create the actual where-statement in SQL. I also added a println(movies), this prints the actual SQL-statement, very useful!</p>
<h2>Conclusion</h2>
<p>I really like Squeryl, it was easy to set up and the basic documentation is sufficient. Of course a next step is inserting and adding more expressions (and for me, handling Postgis geometry objects).<br />
I hope this article gives you a head start.</p>
<h2>Sources</h2>
<p>-<a href="http://stackoverflow.com/questions/1362748/wanted-good-examples-of-scala-database-persistence" target="_blank">Stackoverflow &#8211; Examples of Scala database persistence</a><br />
-<a href="http://www.scala-lang.org/downloads" target="_blank">Scala installation</a><br />
-<a href="http://git-scm.com/" target="_blank">Git</a><br />
-<a href="https://github.com/harrah/xsbt/wiki/Setup" target="_blank">Sbt setup</a><br />
-<a href="http://twitter.com/#!/scweery" target="_blank">Scweery</a><br />
-<a href="http://squeryl.org" target="_blank">Squeryl</a><br />
-<a href="https://github.com/max-l/Squeryl/" target="_blank">Squeryl on github </a><br />
-<a href="http://groups.google.com/group/squeryl" target="_blank">Squeryl google group</a></p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2011/06/25/scala-orm-with-squeryl/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2011%2F06%2F25%2Fscala-orm-with-squeryl%2F&amp;title=Scala%20ORM%20with%20Squeryl%20%26%238211%3B%20A%20simple%20getting%20started%20guide" id="wpa2a_2"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2011/06/25/scala-orm-with-squeryl/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Annoyed by traffic lights? &#8211; Solve it with a gps logger, Scala, GeoTools and qGis</title>
		<link>http://blog.xebia.com/2011/02/02/traffic-lights-delay-analysis/</link>
		<comments>http://blog.xebia.com/2011/02/02/traffic-lights-delay-analysis/#comments</comments>
		<pubDate>Wed, 02 Feb 2011 11:03:59 +0000</pubDate>
		<dc:creator>Jeroen van Wilgenburg</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[geotools]]></category>
		<category><![CDATA[GIS]]></category>
		<category><![CDATA[openstreetmap]]></category>
		<category><![CDATA[qgis]]></category>
		<category><![CDATA[Scala]]></category>

	<!-- AutoMeta Start -->
	<category>qgis</category>
	<category>openstreetmap</category>
	<category>geodeticcalculator</category>
	<category>qgis</category>
	<category>openstreetmap</category>
	<category>geodeticcalculator</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=5822</guid>
		<description><![CDATA[I live in Utrecht, a city where it seems the municipality tries to annoy car drivers as much as possible. Public transport isn&#8217;t an option, even despite the traffic jams it&#8217;s slower, less reliable and don&#8217;t get me started on the attitude of bus drivers. When you want to travel from one place in Utrecht [...]]]></description>
			<content:encoded><![CDATA[<p>I live in Utrecht, a city where it seems the municipality tries to annoy car drivers as much as possible. Public transport isn&#8217;t an option, even despite the traffic jams it&#8217;s slower, less reliable and don&#8217;t get me started on the attitude of bus drivers. When you want to travel from one place in Utrecht to another it&#8217;s often a good idea to find the nearest highway, it might be much longer, but often much quicker. Instead of complaining (which will stop now <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  ) there might be a solution. I have a theory that a trip is much faster when you avoid traffic lights and use the highway as much as possible. To prove that theory, test my new (Android 2.2) phone, fresh up my Scala knowledge and have a cool pet project I started logging my trips.</p>
<p>In this article I will show you how to collect the data, parse and convert it to a usable format and show it on a map. This is just a first prototype and proving my theory will probably take a lot more time which I don&#8217;t have because I&#8217;m in traffic jams all the time <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .<br />
If you don&#8217;t like all the technical mumbo jumbo, just scroll to the maps, they&#8217;re cool to look at.<br />
<span id="more-5822"></span></p>
<h2>Preparation</h2>
<p>Since I drive a Peugeot I had some trouble with GPS reception on my phone, because of the infrared coating on the windscreen. To solve this problem I used an external Bluetooth antenna and told Android to use that antenna. <a href="http://www.google.com/search?q=googoo.android.btgps" target="_blank">Bluetooth GPS</a> is a nice solution for that.<br />
Other reasons to use an external antenna are that they are much more accurate, save the battery of your phone and that you can place the antenna where the reception is best (the black rectangle behind your rear view mirror is a perfect place and this is one of the reasons this rectangle exists).<br />
<a href="http://blog.xebia.com/wp-content/uploads/2011/02/windscreen.jpg"><img class="alignleft size-medium wp-image-5825" title="Windscreen" src="http://blog.xebia.com/wp-content/uploads/2011/02/windscreen-300x226.jpg" alt="Peugeot 406 Windscreen infrared coating" width="300" height="226" /></a><br />
When you have trouble firing up the Bluetooth GPS try disabling and enabling the GPS and/or Bluetooth on your phone. I had some trouble with my car kit, but when you connect the GPS first and then the car kit you can still use both. You have to check the connection with the GPS when someone calls you, a while ago I lost my GPS connection when my colleague Mischa called me to tell me that the left lane was much faster <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>For the logging I used <a href="http://gpslogger.codeplex.com/" target="_blank">GPS Logger for Android</a>, a simple application that writes .gpx and/or .kml to the /mnt/sdcard/GPSLogger directory. You can even set the log frequency. Note that the logging is not done a the set interval, it&#8217;s just a suggestion. The antenna spits out a stream of data, when your phone is busy it just skips data. So be aware of this when processing the data and don&#8217;t hardcode the interval, but use the timestamp from the antenna.<br />
There are other logging applications available, some even draw a trace. I prefer a very fast application, I don&#8217;t want to wait for an application to start up when I start my car.</p>
<h2>Parsing the data</h2>
<p>I decided to use the .gpx data and skip .kml. I already have some experience with gpx, but kml shouldn&#8217;t be a problem. The fields I&#8217;m interested in are the coordinates (x,y) and the timestamp. Course and speed are also very useful, but that&#8217;s derived data for which I&#8217;m going to use GeoTools. Since GPS doesn&#8217;t really know when you&#8217;re stationary you get a lot of garbage at low speeds. For now it&#8217;s good enough to assume that you&#8217;re stationary when the speed drops below 5 kph. Another thing is that when you remove trackpoints from the log the speed field becomes invalid, I want the average speed on a leg of the track, not at the trackpoint itself.</p>
<p>To parse the data I used Scala. This <a href="http://programming-scala.labs.oreilly.com/ch10.html" target="_blank">sample chaper</a> explains how to parse xml in Scala. The structure of a trackpoint in the gpx is as follows:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;trkpt lat=&quot;52.131231666666665&quot; lon=&quot;5.011798333333333&quot;&gt;
 &lt;ele&gt;49.4&lt;/ele&gt;
 &lt;course&gt;329.36&lt;/course&gt;
 &lt;speed&gt;29.8172&lt;/speed&gt;
 &lt;src&gt;gps&lt;/src&gt;
 &lt;time&gt;2010-12-23T07:23:21+01:00&lt;/time&gt;
&lt;/trkpt&gt;
</pre>
<p>I&#8217;m interested in lat (y), lon (x) and time. With these fields I can calculate the speed and create my map.</p>
<h3>Displaying speed</h3>
<p>I thought it would be nice to display each leg of the track in a color that represents the speed. To display the maps I use qGis, a desktop application to display GIS-data. QGis can load all kinds of formats (shapefiles, simple .csv&#8217;s and there are lots of plugins available).<br />
After trying to generate shapefiles with GeoTools for a while I decided points were good enough (instead of legs of a track). After all I&#8217;m interested in the time spent at traffic lights.<br />
In the nightly versions of qGis 1.7 there is a new and improved delimited text plugin. The guys at Linfiniti even made an <a href="http://linfiniti.com/2010/12/video-tutorial-2-delimited-text-plugin/" target="_blank">instruction video</a> for it! With version 1.7 it is possible to import <a href="http://en.wikipedia.org/wiki/Well-known_text" target="_blank">well known text</a>. This immediately solves my problem, unfortunately it is not yet available for Mac Os yet.</p>
<p>So, for now I have to show a map with points:</p>
<p><a href="http://blog.xebia.com/wp-content/uploads/2011/02/speed.png"><img class="alignleft size-medium wp-image-5824" title="speed" src="http://blog.xebia.com/wp-content/uploads/2011/02/speed-300x229.png" alt="" width="300" height="229" /></a></p>
<p>To import the data I converted the parsed xml to .csv first. A snippet from the output:</p>
<pre class="brush: plain; title: ; notranslate">lonX, latY, speed, dateTime
5.074956666666667, 52.09170666666667, 37.266029160336, 2011-01-04T09:07:35.000+01:00
5.07473, 52.091948333333335, 31.436951983284487, 2011-01-04T09:07:38.000+01:00
5.0746, 52.092083333333335, 26.498677863536287, 2011-01-04T09:07:40.000+01:00</pre>
<h4>Calculating the speed</h4>
<p>To calculate the speed I used GeoTools in Scala:</p>
<pre class="brush: scala; title: ; notranslate">
 /**
 * @param start (starting point (lon, lat))
 * @param destination (end point (lon, lat))
 * @return Distance in meters
 */
def calcDistance(start: (Double, Double), destination: (Double, Double)): Double = {
  val geodeticCalculator = new GeodeticCalculator();
  geodeticCalculator.setStartingGeographicPoint(start._1, start._2);
  geodeticCalculator.setDestinationGeographicPoint(destination._1, destination._2);

  // To be computed only once for ever for a given GeodeticCalculator
  val ellipsoid = geodeticCalculator.getEllipsoid();
  val sourceUnit = ellipsoid.getAxisUnit();
  val targetUnit = SI.METER;

  val converterTo = sourceUnit.getConverterTo(targetUnit);

  // To apply after each distance calculation
  converterTo.convert(geodeticCalculator.getOrthodromicDistance());
}
</pre>
<p>Speed is calculated the following way: (distanceInMeters / deltaMillis) * 3600</p>
<h3>Delimited text layer</h3>
<p>The csv file can be imported into qGis with the delimited text plugin. QGis is smart enough to see that lonX and latY are the x and y coordinates. When the layer is imported you will see a map with points, all in the same color. To change the colors double click on the layer in the legend on the left. Pick symbology and graduated symbol as legend type. I increased the number of classes to 7 and hit the classify button. QGis generates some kind of gradient for you, which can be changed easily. With save and load style you can save and load these settings for later use.</p>
<h4>OpenStreetMap raster layer (georeferencing)</h4>
<p>To create a base layer I downloaded a map from <a href="http://www.openstreetmap.org" target="_blank">OpenStreetMap</a>. When you go to the site and have a nice view of a map you want to use in qGis you can click on the Export tab. This opens a dock in which you can export an image. Remember the coordinates, you need them in qGis!</p>
<p>In qGis open the Georeferencer plugin. Click the first button on the toolbar and open the image you saved. Zoom in to the upper left corner of the image and add dot (the three dots in the toolbar) and enter the coordinates you just saved. Do the same for the lower right corner. Click the green play button and click on the folder right of output raster. You now have a georeferenced tiff image which can be added as a raster layer in qGis.</p>
<p>Of course this map has only one zoom level, which looks a bit distorted (see the screenshot in the next paragraph).</p>
<p>I&#8217;m not sure if the plugins I mentioned are installed by default, if they&#8217;re not and you have trouble please let me know, then I&#8217;ll add a section to this blog. Usually plugins can be enabled/disabled und the menu plugins, manage plugins.</p>
<h3>Displaying stationary time</h3>
<p>To display the stationary time I used the interval the speed drops below 5 kph. This time is included as a field in the csv, which we can use in qGis.<br />
In qGis create a delimited text layer. At symbology pick the traffic light symbol and increase its size (I used 5 points). Now add a label. &#8216;Field containing label&#8217; should be the field that has the delay in it. The label displays on top of the symbol by default, below right is a better place. Increase the font size and color (ie. 24 and black) and add a buffer (2.0, white).<br />
Now there will appear traffic light symbols on the map with a delay next to it. Of course we also want to display a trace of the driven route. This can be achieved with a gpx layer. Go to the menu Plugins, Gps, Gps tools.<br />
Click on the tab Load GPX&#8230;, browse for the gpx and select the Tracks at Feature types.<br />
At the properties the line size and color can be adjusted.</p>
<p><a href="http://blog.xebia.com/wp-content/uploads/2011/02/delay.png"><img class="alignleft size-medium wp-image-5823" title="delay" src="http://blog.xebia.com/wp-content/uploads/2011/02/delay-300x224.png" alt="" width="300" height="224" /></a></p>
<p>The purple lines represent two different trips. The trip I analyzed starts at the traffic light with number 17, via 18 and ending with 15. On OpenStreetMap:  <a href="http://www.openstreetmap.org/?lat=52.0674&amp;lon=5.1132&amp;zoom=14&amp;layers=M" target="_blank">Exit 17 on highway A12</a>.</p>
<h2>Conclusion/Future</h2>
<p>I always thought I was waiting minutes in front of traffic lights, it&#8217;s not that bad. It rarely happens that you have to wait more than one minute. Guess I have to work on my impatience <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>I display the stationary time and this doesn&#8217;t necessarily have to be at a traffic light. So a stop symbol might be more suitable <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>The next step is &#8216;snapping&#8217; the gps data to the OpenStreetMap roads and calculate the average speed. I&#8217;m also working on getting nicer looking maps (now the maps are distorted and only suitable for one zoom level), it probably has something to do with coordinate systems and I might give OpenLayers a shot.</p>
<p><a href="http://androgeoid.com/" target="_blank">Androgeoid</a> is a very nice site with reviews of Android apps, it really helped me to pick the right tools for the job.</p>
<h2>Sources</h2>
<p><a href="http://gpslogger.codeplex.com/" target="_blank">GPS Logger for Android</a><a href="http://www.google.com/search?q=googoo.android.btgps" target="_blank"><br />
Bluetooth GPS</a><a href="http://androgeoid.com/" target="_blank"><br />
Androgeoid</a><br />
<a href="http://www.geotools.org" target="_blank">GeoTools</a><br />
<a href="http://www.openstreetmap.org/" target="_blank">OpenStreetMap</a><br />
<a href="http://linfiniti.com/2010/12/video-tutorial-2-delimited-text-plugin/" target="_blank">Delimted text plugin video</a><br />
<a href="http://programming-scala.labs.oreilly.com/ch10.html" target="_blank">Herding XML in Scala</a></p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2011/02/02/traffic-lights-delay-analysis/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2011%2F02%2F02%2Ftraffic-lights-delay-analysis%2F&amp;title=Annoyed%20by%20traffic%20lights%3F%20%26%238211%3B%20Solve%20it%20with%20a%20gps%20logger%2C%20Scala%2C%20GeoTools%20and%20qGis" id="wpa2a_4"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2011/02/02/traffic-lights-delay-analysis/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Websockets from scratch &#8211; Results from a short techrally</title>
		<link>http://blog.xebia.com/2010/12/15/websockets-from-scratch/</link>
		<comments>http://blog.xebia.com/2010/12/15/websockets-from-scratch/#comments</comments>
		<pubDate>Wed, 15 Dec 2010 08:54:46 +0000</pubDate>
		<dc:creator>Jeroen van Wilgenburg</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Web 2.0]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jetty]]></category>
		<category><![CDATA[techrally]]></category>
		<category><![CDATA[websockets]]></category>

	<!-- AutoMeta Start -->
	<category></category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=5589</guid>
		<description><![CDATA[Last friday we had a techrally at Xebia. We could pick our subject: MongoDB or Websockets or Canvas. I teamed up with Albert. There also was another websockets team consisting of Mischa, Ron and Frank. We decided to use Jetty for websockets. No particual reason to pick Jetty, we both heard it did something with [...]]]></description>
			<content:encoded><![CDATA[<p>Last friday we had a techrally at Xebia. We could pick our subject: MongoDB or Websockets or Canvas. I teamed up with Albert. There also was another websockets team consisting of Mischa, Ron and Frank.<br />
We decided to use Jetty for websockets. No particual reason to pick Jetty, we both heard it did something with websockets and in the end it was an easier solution than the other team picked (<a href="http://jwebsocket.org/" target="_blank">jWebSocket</a>).<br />
Since we only had a few hours we were in quite a hurry, but in the end it was so simple we had time to write a blog, listen to Dan North and Albert even redid everthing and more in Python.<span id="more-5589"></span></p>
<h2>Introduction</h2>
<p>I want to skip the introduction because a lot has been written about websockets and you probably want to get started as soon as possible. Check out the sources section for more information. For now you only have to know that it&#8217;s fast, it has almost no overhead, keeps a permanent connection open (so the server can push data to the client, no polling required!) and best of all: it&#8217;s very easy.</p>
<h2>Installation</h2>
<p>When you&#8217;re using maven 2+ you don&#8217;t have to download anything. Just start a maven war project and add the <a href="http://docs.codehaus.org/display/JETTY/Maven+Jetty+Plugin" target="_blank">jetty-maven-plugin</a> (we used version 7.2.1.v20101111), add a dependency to jetty-websocket (inside the project element) and you&#8217;re ready to get started.<br />
<code>&lt;dependency&gt;<br />
 &lt;groupId&gt;org.eclipse.jetty&lt;/groupId&gt;<br />
 &lt;artifactId&gt;jetty-websocket&lt;/artifactId&gt;<br />
 &lt;version&gt;7.2.1.v20101111&lt;/version&gt;<br />
&lt;/dependency&gt;</code></p>
<h2>Dissecting the WebSocketChatServlet example</h2>
<p>A sample application is included with Jetty. On <a href="http://blogs.webtide.com/gregw/entry/jetty_websocket_server" target="_blank">this blog</a> this sample is explained and in the end we used it to see what was happening and of course see some communication between client and server. After that we stripped everything and started over again to see what was actually happening.</p>
<h2>Creating your own servlet</h2>
<p>Since I used Struts and Spring MVC in the past and always copied the servlet configuration it was a while ago I added my own servlet to web.xml, so here is a litte snippet to help you (this probably was one of the most difficult parts <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  ):<br />
<code lang="xml">&lt;servlet&gt;<br />
 &lt;servlet-name&gt;hw&lt;/servlet-name&gt;<br />
 &lt;servlet-class&gt;com.xebia.ws.HelloWorldServlet&lt;/servlet-class&gt;<br />
 &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;<br />
&lt;/servlet&gt;</p>
<p>&lt;servlet-mapping&gt;<br />
 &lt;servlet-name&gt;hw&lt;/servlet-name&gt;<br />
 &lt;url-pattern&gt;hw.do&lt;/url-pattern&gt;<br />
&lt;/servlet-mapping&gt;</code><br />
The HelloWorldServlet extends WebSocketServlet and you have to implement the doWebSocketConnect method. This method returns a WebSocket. For now it&#8217;s enough to do a new HelloWorldWebSocket.</p>
<p>HelloWorldWebSocket implements WebSocket. The onConnect method receives an <a href="http://download.eclipse.org/jetty/stable-7/apidocs/org/eclipse/jetty/websocket/WebSocket.Outbound.html" target="_blank">Outbound</a> object. With this object it is possible to send data back to the client. The Outbound object is a field on the WebSocket object so we can use it in the onMessage method.</p>
<p>The onMessage method:</p>
<pre lang="java">public void onMessage(byte opcode, String data) {
    outbound.sendMessage("pong");
}</pre>
<p>When we send data in javascript (with send()) the server will respond with &#8220;pong&#8221;.</p>
<h2>The Javascript side</h2>
<p>The Javascript is also very simple. I added the <a href="http://jquery.com/" target="_blank">jQuery</a> plugin to add data to a div with id bla, but your free to do it the old-fashioned way.</p>
<pre lang="javascript">var ws=new WebSocket("ws://10.0.0.230:8080/hw.do");
ws.onmessage = onMessage;
ws.onopen = onOpen;

function onMessage(m) {
    $("#bla").append(m.data + "&lt;br/&gt;");
}

function onOpen() {
    console.log("connection open")
}

function send(){
console.log("sending ping");
    ws.send("ping");
}</pre>
<p>For testing we&#8217;re using Safari, it has a really nice console (available under the menu Develop, Show Error Console). By typing send() in the console we&#8217;re sending a ping which will respond with a pong. The response is logged to the div with id bla.</p>
<p>It&#8217;s even possible to write a simple websocket client with nothing more than the console:</p>
<pre lang="javascript">var m=new WebSocket("ws://10.0.0.230:8080")
m.onmessage=function(m){ console.log(m.data); };</pre>
<p>This piece of code prints the payload of any received message. Sending is done with m.send(&#8220;data to send&#8221;);</p>
<h2>Problems</h2>
<h3>Thinking http is the protocol of websockets</h3>
<p>We used the browser to test whether the WebSocketServlet was working. Of course websockets uses the ws:// or ws:// prefix and we used http://. I made this mistake a couple of times.</p>
<h3>WebSocket is not ready</h3>
<p>We tried to send data over the socket, but got an INVALID_STATE_ERR. It appeared the WebSocket isn&#8217;t ready immediately after creating. After the WebSocket is ready the onopen function is called and then it&#8217;s ready to send and receive. The readyState field on a WebSocket is a useful field to check the status of the socket (0=connecting, 1=open, 2=closing, 3=closed). So don&#8217;t try to do anything with the websocket before onopen is called.</p>
<h3>WebSocket disabled in Firefox 4</h3>
<p>While we were coding away Dan North paid us a visit. In a very cool improvisation style presentation he pointed us to <a href="http://hacks.mozilla.org/2010/12/websockets-disabled-in-firefox-4/" target="_blank">an article</a> about some security issues with websockets.</p>
<h2>Conclusion</h2>
<p>Websockets is a very cool technology and I&#8217;m very happy it was a subject of the techrally. Feel free to ask any questions. At least 5 people at Xebia are now websockets experts and even more listened to two presentations about it.</p>
<h2>Sources</h2>
<p><a href="http://blogs.webtide.com/gregw/entry/jetty_websocket_server" target="_blank">http://blogs.webtide.com/gregw/entry/jetty_websocket_server</a><br />
<a href="http://dev.w3.org/html5/websockets/" target="_blank">http://dev.w3.org/html5/websockets/</a><br />
<a href="http://blog.dannorth.net/" target="_blank">http://blog.dannorth.net/</a><br />
<a href="http://www.slideshare.net/spagalloco/introduction-to-websockets" target="_blank">http://www.slideshare.net/spagalloco/introduction-to-websockets</a><br />
<a href="http://docs.codehaus.org/display/JETTY/Maven+Jetty+Plugin" target="_blank">http://docs.codehaus.org/display/JETTY/Maven+Jetty+Plugin</a><br />
<a href="http://hacks.mozilla.org/2010/12/websockets-disabled-in-firefox-4/" target="_blank">http://hacks.mozilla.org/2010/12/websockets-disabled-in-firefox-4/</a><br />
<a href="http://www.xoriant.com/blog/software-product-development/html5-series-websockets.html" target="_blank">HTML5 Series: Part 6: WebSockets</a></p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2010/12/15/websockets-from-scratch/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2010%2F12%2F15%2Fwebsockets-from-scratch%2F&amp;title=Websockets%20from%20scratch%20%26%238211%3B%20Results%20from%20a%20short%20techrally" id="wpa2a_6"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2010/12/15/websockets-from-scratch/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Unleashing the power of geospatial indexing with Scala and MongoDB</title>
		<link>http://blog.xebia.com/2010/03/28/mongodb-geospatial-index/</link>
		<comments>http://blog.xebia.com/2010/03/28/mongodb-geospatial-index/#comments</comments>
		<pubDate>Sun, 28 Mar 2010 16:28:21 +0000</pubDate>
		<dc:creator>Jeroen van Wilgenburg</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[geohash]]></category>
		<category><![CDATA[geospatial]]></category>
		<category><![CDATA[GIS]]></category>
		<category><![CDATA[index]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[spatial]]></category>

	<!-- AutoMeta Start -->
	<category></category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=4330</guid>
		<description><![CDATA[Right now I&#8217;m following some geospatial tweets and came across an interesting one about a new option to add a geospatial index to a MongoDB. Since I&#8217;ve done some stuff with Scala recently I decided to insert the data into MongoDB with Scala using scamongo. Unfortunately the scamongo Scala driver for MongoDB gave me too [...]]]></description>
			<content:encoded><![CDATA[<p>Right now I&#8217;m following some geospatial tweets and came across an interesting one about a new option to add a geospatial index to a MongoDB. Since I&#8217;ve done some stuff with Scala recently I decided to insert the data into MongoDB with Scala using scamongo. Unfortunately the scamongo Scala driver for MongoDB gave me too much trouble, so I switched to the java driver.</p>
<p><span id="more-4330"></span></p>
<p>I have no experience with MongoDB at all, it just sounds cool and people tell me it&#8217;s cool. That&#8217;s enough for me to do some research. I recently finished my bachelor thesis about collecting gps points and discovering running routes from those points. The main bottleneck in my application was counting the number of points within a certain radius of a point. You basically have to check all the points to see whether they&#8217;re inside the radius. Let&#8217;s say you have 10^6 points (and I have), then (10^6)*(10^6) steps are needed.<br />
I advised to use a geospatial index with PostGIS in my conclusion, but that&#8217;s not really new and cool, so let&#8217;s give it a shot with MongoDB.</p>
<h2>What is MongoDB?</h2>
<p><img class="alignleft size-full wp-image-4329" title="mongodb-logo" src="http://blog.xebia.com/wp-content/uploads/2010/03/mongodb-logo.png" alt="mongodb-logo" width="200" height="67" style="float: right; padding: 5px;" />&#8220;MongoDB (from &#8216;humongous&#8217;) is a scalable, high-performance, open source, schema-free, document-oriented database.&#8221;<br />
Well that&#8217;s quite a proper description I think. The idea is to insert documents (JSON objects) into a collection (comparable to a table in an RDBMS) in a database. Queries don&#8217;t use SQL, they are a bit comparable with QBE.</p>
<p>Inserting and querying can be done with a plethora of languages. There is official support for C, C++, Java, Javascript, Perl, PHP, Python and Ruby. The community supports another bunch of languages which are listed <a href="http://www.mongodb.org/display/DOCS/Drivers" target="_blank">here</a>).<br />
Installing MonogDB is very easy. Just extract a file and start the database with <strong>mongod</strong>. Since it is different amongst the various operating systems I have to refer to the <a href="http://www.mongodb.org/display/DOCS/Quickstart" target="_blank">quickstart guide</a> (and I can&#8217;t explain it any clearer anyways).<br />
With the command mongo a CLI is started. Let&#8217;s insert an object and find that object.<br />
<code>&gt; db.foo.save( { a : 1 } )<br />
&gt; db.foo.find()</code><br />
The first line of code above saves a document in the collection foo with key/value a/1. When you do a find (second line) the same object is displayed, now with a unique id (the key _id is used for this)</p>
<p>There is a lot to tell about MongoDB, <a href="http://www.mongodb.org/display/DOCS/User+Feedback" target="_blank">but many people did that already</a>, so let&#8217;s focus on the geospatial indexing in combination with Scala.</p>
<h2>How a geospatial index works in MongoDB</h2>
<p>A geospatial index is just like a normal database index, but in two dimensions (or sometimes three when you account for height). The index in MongoDB is a so called grid index (there are other indexes like r-tree and quadtree, but that might be too much info for a blog).<br />
The geo-index of MongoDB encodes a geohash on top of a standard MongoDB b-tree. Geohashing (not to be confused with geocaching) is a way to divide a coordinate system into hierarchical buckets of grid shape.<br />
It basically divides an area in two for every bit and so on. An elaborate description can be found on the <a href="Right now I'm following some geospatial tweets and came across an interesting one about a new option to add a geospatial index to a MongoDB. Since I've done some stuff with Scala recently I decided to insert the data into MongoDB with Scala using scamongo. Unfortunately the scamongo Scala driver for MongoDB gave me too much trouble, so I switched to the java driver.  &lt;!--more--&gt;  I have no experience with MongoDB at all, it just sounds cool and people tell me it's cool. That's enough for me to do some research. I recently finished my bachelor thesis about collecting gps points and discovering running routes from those points. The main bottleneck in my application was counting the number of points in the radius of a point. You basically have to check all the points to see whether they're inside the radius. Let's say you have 10^6 points (and I have), then (10^6)*(10^6) steps are needed. I advised to use a geospatial index with PostGIS in my conclusion, but that's not really new and cool, so let's give it a shot with MongoDB. &lt;h2&gt;What is MongoDB&lt;/h2&gt; &lt;img class=&quot;alignleft size-full wp-image-4329&quot; title=&quot;mongodb-logo&quot; src=" target="_blank">wikipedia page</a>.<br />
A drawback of geohashing is the wrapping (-180 and 179 are very close for example), this can be solved by doing a grid search after the initial scan. It&#8217;s a bit comparable by how google maps loads the map images, it starts with the center of the viewport and then the surrounding areas are downloaded.</p>
<p>Our Laapersveld office in a geohash: <a href="http://geohash.org/u179jbzdexru" target="_blank">u179jbzdexru</a></p>
<h2>Using the java driver (in Scala)</h2>
<p>Since the Scala driver gave me too much trouble I tried the java driver. It can be downloaded from a <a href="http://github.com/mongodb/mongo-java-driver/downloads" target="_blank">github repo</a>. Just include the jar in your Scala project and you&#8217;re ready to go.</p>
<p>To query everything from collection foo, the following code is needed:<br />
<code>val mongo = new Mongo( "localhost" , 27017 )<br />
val db = mongo.getDB( "test" )<br />
val coll = db.getCollection("foo")<br />
val cursor = db.find()<br />
while (cursor.hasNext) {<br />
println(cursor.next)<br />
}</code><br />
A big warning from the API which is important enough to repeat is that toArray and length on cursor convert the cursor to an array, which can be a very expensive operation, especially on humongous databases!</p>
<h2>Inserting the data</h2>
<p>Let&#8217;s take some arbritary data from my data set:<br />
<code>{ "routeId" : "9327014.tcx", "id" : "1105409", "loc" : { "x" : 5.1400218, "y" : 52.0614276 } }</code><br />
As you can see I use a nested object, we need this for the index later on and it&#8217;s to show you how to do nested objects (plain objects are just too easy <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  ).<br />
<code>val doc = new BasicDBObject()<br />
doc.put("routeId", "9327014.tcx")<br />
doc.put("id", "1105409")<br />
val loc=new BasicDBObject()<br />
loc.put("x", 5.1400218)<br />
loc.put("y", 52.0614276)<br />
doc.put("loc", loc)<br />
coll.insert(doc) /* coll is a DBCollection */</code><br />
That&#8217;s all! No transactions to commit or connections to close.</p>
<h2>Creating the index</h2>
<p>Creating the index is quite easy, it can be done from the java driver or on the command line.</p>
<p>The objects in the database look like this:<br />
<code>{ "routeId" : "activity_123456.tcx", "id" : " 1105402", "loc" : { "x" : 5.1415501, "y" : 52.0616409 } }</code><br />
The x,y coordinates are wrapped in a loc key, because that&#8217;s the way MongoDB likes it. The first two columns in the loc object are treated as x and y coordinates.<br />
On the command line execute <strong>db.foo.ensureIndex( { loc: &#8220;2d&#8221; } )</strong> and your index is created.<br />
Creating the index in Scala is also possible:<br />
<code>val index=new BasicDBObject()<br />
index.put("loc","2d")<br />
coll.ensureIndex(index) /* coll is a DBCollection */</code><br />
Forgetting to create an index and doing spatial queries might work, but sometimes I got strange crashes (and bad performance). So check this before throwing MongoDB out of your window <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<h2>Querying the data and comparing the speed</h2>
<p>It&#8217;s now possible to do a geospatial query:<br />
<code>db.foo.find( { loc : { $near : [5.14,52.06] } } )</code><br />
This will display all the points near 5.14, 52.06 sorted by distance from that point. Note that by default a maximum of 100 points is returned! This can be solved by appending the query with <strong>.limit(500)</strong>, for a maximum of 500 results. Note that the higher the number the slower your query gets, so be careful with increasing this number.</p>
<p>I wanted to count the number of points within a certain radius. For this you need to add bounds criteria to the query:<br />
<code>db.foo.find({"loc" : {"$within" : {"$center" : [[5.14,52.06], 0.0005]}}})</code><br />
Note that the bounds criteria were added two weeks ago (version 1.3.4) and I&#8217;m not sure whether this already is ready for production. It works fine for me, but you might be a bit careful when using it for real.</p>
<p>In Scala building the query is a bit more verbose. You have to construct an object and query a collection for that object (note that this is the same as the first query):<br />
<code>val query = new BasicDBObject()<br />
val loc = new BasicDBObject()<br />
val near = new BasicDBList()<br />
near.put( "0", 5.15 )<br />
near.put( "1", 52.069 )<br />
loc.put("near", near)<br />
query.put("loc",loc)<br />
/* coll is a DBCollection */<br />
coll.find(query).limit(50)<br />
</code><br />
I wanted to do a speed comparison, but I decided it isn&#8217;t that important yet. Since MongoDB and especially the geo-index is improving every day it&#8217;s enough to say that it&#8217;s a lot faster on large data sets (for me &gt; 400,000 points). The small sets ( &lt; 200,000 ) have comparable speed.</p>
<h2>Conclusion</h2>
<p>MongoDB is cool and the people who told me that were right. Besides cool I really loved it. I got my database running within a few minutes. The documentation is very well written and updated regularly (the new features in the geo-index were updated in the documentation instantly and that&#8217;s quite unique).<br />
Scamongo was a bit of a disappointment (probably also thanks to my perseverance and wanting quick results <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  ), it looks promising so I might give it another shot within a few months.<br />
The geo-index is really cool. When I started playing around a few weeks ago some features were missing, but within days these features were added (and I had to rewrite some parts of this blog <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  ). Kudo&#8217;s to the MongoDB guys for giving me cool stuff, updating it regularly and even without breaking!</p>
<h2>Sources</h2>
<p><a href="http://www.mongodb.org/" target="_blank">MongoDB</a><br />
<a href="http://en.wikipedia.org/wiki/Geohash" target="_blank">Geohashing</a><br />
<a href="http://github.com/mongodb/mongo-java-driver/downloads" target="_blank">MongoDB Java Driver</a><br />
<a href="http://api.mongodb.org/java/index.html" target="_blank">MongoDB Java Driver API</a></p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2010/03/28/mongodb-geospatial-index/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2010%2F03%2F28%2Fmongodb-geospatial-index%2F&amp;title=Unleashing%20the%20power%20of%20geospatial%20indexing%20with%20Scala%20and%20MongoDB" id="wpa2a_8"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2010/03/28/mongodb-geospatial-index/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Java callout on the Oracle / AquaLogic Service Bus &#8211; Invoking static methods in any jar file</title>
		<link>http://blog.xebia.com/2009/10/11/java-callout-on-the-alsb/</link>
		<comments>http://blog.xebia.com/2009/10/11/java-callout-on-the-alsb/#comments</comments>
		<pubDate>Sun, 11 Oct 2009 09:39:35 +0000</pubDate>
		<dc:creator>Jeroen van Wilgenburg</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[SOA]]></category>

	<!-- AutoMeta Start -->
	<category></category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=3225</guid>
		<description><![CDATA[Sometimes a service bus is not sufficient for the job at hand. You can use EJB&#8217;s and JMS queues, but that might be overkill. That&#8217;s where a java callout might come to the rescue. This article will show you how to do a callout with &#8216;complex&#8217; objects. On the bus you can pass around java [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes a service bus is not sufficient for the job at hand. You can use EJB&#8217;s and JMS queues, but that might be overkill. That&#8217;s where a java callout might come to the rescue. This article will show you how to do a callout with &#8216;complex&#8217; objects. On the bus you can pass around java objects or use them on the bus (this requires a small transformation step). I used the AquaLogic service bus version 10.2, but I think it should work any version that supports java callouts. The only difference can be the version of xmlbeans (AL 10.2 uses version 1.0.3)<br />
<span id="more-3225"></span><br />
At our customer we did a little proof of concept with a java callout but ultimately decided to go with another solution. The java callout however can be very useful so this article will show you how to get a head start with it. I assume that you have at least a little experience with the alsb and Maven 2. Creating a proxy service and editing a message flow should be sufficient.</p>
<p>The prerequisites for a java callout are simple. Any static method in a jar-file will do. You can even return your home made objects (they don&#8217;t even have to be serializable). One downside is that you cannot do anything with these objects on the bus, they&#8217;re just an object with an id. You can however pass these objects to another java callout and use them as your regular java objects.</p>
<p>The static method you want to call should be in a jar file that is loaded on the alsb (so it is NOT a library in WebLogic). It is allowed to put dependencies in this jar file, so in theory everything is possible. But idea is to keep it small and simple, otherwise go with EJB&#8217;s and JMS with a library or application on WebLogic.</p>
<p>It is very inconvenient when you just can pass the objects around. There are however some type of objects that can be handled on the bus. Those objects  are primitives, String, BigDecimal, BigInteger, byte[], String[] and XmlObject. XmlObject is an object provided by the Apache Xml Beans framework and is basically an xml-representation of a java object. I know that converting an object to xml should happen on the bus and it would be nice when a java object can be passed to the bus, but this just isn&#8217;t the fact and this is the cleanest solution I came up with.</p>
<p>Now that you know the theory let&#8217;s get our hands dirty:</p>
<h2>Preparation</h2>
<p>Create a class with a static method and pacakge it in a jar file. I added the following maven dependency to an empty pom.xml:</p>
<pre>&lt;dependencies&gt;
 &lt;dependency&gt;
 &lt;groupId&gt;xmlbeans&lt;/groupId&gt;
 &lt;artifactId&gt;xmlbeans&lt;/artifactId&gt;
 &lt;version&gt;1.0.3&lt;/version&gt;
 &lt;scope&gt;compile&lt;/scope&gt;
 &lt;/dependency&gt;
&lt;/dependencies&gt;</pre>
<p>This will give you the Apache Xml Beans library at compile time. This library is excluded in the packaged jar because it lives in WebLogic.</p>
<p>The java class :</p>
<pre class="brush: java; title: ; notranslate">public class CalloutDemo {
    public static String getString(String input) {
		System.out.println(&quot;input: &quot; + input);
		return &quot;Buy a bicycle from &quot; + input + &quot;?&quot;;
    }

    public static XmlObject getCode(String input) throws XmlException {
		System.out.println(&quot;input: &quot; + input);

		String xmlString = String.format(&quot;&lt;root&gt;&lt;mainCode&gt;%s&lt;/mainCode&gt;&lt;subCode&gt;%s&lt;/subCode&gt;&lt;/root&gt;&quot;, &quot;mc&quot;, input);
		XmlObject instance = XmlObject.Factory.parse(xmlString);

		return instance;
    }

    public static Code getCode() {
		return new Code(&quot;hoofdCode&quot;, &quot;subCode&quot;);
    }

    public static void printCode(Code code) {
		System.out.println(&quot;code: &quot; + code);
    }
}</pre>
<p>This class returns a main code and a sub code for an input String or just a new String based on an input String.<br />
Apache Xml Beans is ued to return &#8216;complex objects&#8217;. In this example I&#8217;ll return a String and an XmlObject.</p>
<p>When you return a normal java object (ie. a domain object) and print this on the bus you will see something like this:<br />
&lt;con:java-content ref=&#8221;jcid:5333178f:11fa2a0451c:-7fda&#8221; xmlns:con=&#8221;http://www.bea.com/wli/sb/context&#8221;/&gt;<br />
It&#8217;s just a pointer to an object. When you pass this pointer to another java callout it becomes an object again. It&#8217;s not possible to do transformations or even view the java object on the bus, you can only pass it around (and probably only on the same VM instance)</p>
<p>No rocket science, just for the example. When you understand the code displayed above it&#8217;s time to put everything on the bus. But first run the command &#8216;mvn package&#8217; to compile the project and create a jar.</p>
<h2>On the bus</h2>
<p>Open the AquaLogic service bus console (I&#8217;m using the web interface by the way).<br />
Create a session with the create button. Then create a new project in the Project Explorer (I called mine callout-test)<br />
Click on callout-test in the project tree and create a jar resource.<br />
Give the resource a name (ie. callout-test-jar) and upload the jar maven delivered to you (from the target folder).<br />
When the jar is uploaded it&#8217;s possible to browse the jar. You will see your brand new class with al its methods.<br />
Now create a new Proxy Service (callout-ps), just give it a name, click last and then save.<br />
Edit the message flow and add a pipeline pair. Add a stage at the request pipeline. Edit that stage and add an action:<br />
Message processing, Java callout.<br />
When you click on &lt;method&gt; it&#8217;s possible to pick your jar and choose a method. The first method I want to show is  public static java.lang.String getString(java.lang.String). For the input expression enter xs:string(&#8216;Harrie&#8217;).<br />
In real life this is a value somewhere from the bus of course.<br />
Give the result String the name result, we can use that value later on.<br />
Click on the icon left of Java Callout and add an Alert action. At the expression enter $result and leave the summary empty.<br />
Make sure you save everything and activate the session.</p>
<p><img class="alignnone size-full wp-image-3226" title="java-callout-1" src="http://blog.xebia.com/wp-content/uploads/2009/10/java-callout-1.png" alt="java-callout-1" width="476" height="375" /></p>
<h2>Putting it to the test</h2>
<p>When everything is saved it&#8217;s time to test the proxy service. Find the proxy service in your project explorer and click on the debug icon (the little bug icon in the action colum). Since we created an any xml-service it&#8217;s okay enter anything in the payload field as long as it&#8217;s xml. Click the execute button and you&#8217;ll get the response you entered in the payload field. Of course we want to see what happened internally.<br />
Click on home and then pipeline alerts. There probably is a new alert named &#8216;AquaLogic Service Bus Alert&#8217; with a timestamp of a few seconds ago. Click on this alert and you&#8217;ll see the new String in the Description field:</p>
<p><img class="alignnone size-full wp-image-3227" title="java-callout-2" src="http://blog.xebia.com/wp-content/uploads/2009/10/java-callout-2.png" alt="java-callout-2" width="444" height="307" /></p>
<p>Since we used System.out.println (I know it&#8217;s evil, but I wanted no dependencies in my little jar) the server console shows:<br />
input: Harrie</p>
<h2>The next step</h2>
<p>Now of course it&#8217;s time to use the &#8216;advanced&#8217; xml.<br />
Re-open the flow of the proxy service, click on Stage1, click Edit, click on the getString method and change it to getCode (the one that returns XmlObject).<br />
Enter xs:string(&#8216;Arie&#8217;) at the expression. Since the method is returning xml we can print the part of the message we want. Enter $result/subCode at the Alert message (or $result/subCode/text() if you just want the text without xml tags, but alerting the text you just entered isn&#8217;t cool <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  )<br />
Save and activate and repeat the steps from &#8216;Putting it to the test&#8217;</p>
<p>It&#8217;s easy to predict what happens now.</p>
<p>Unfortunately we didn&#8217;t find use for the java callout at our project, but it&#8217;s pretty cool nonetheless.</p>
<h2>Disclaimer</h2>
<p>I used the term alsb and AquaLogic Service Bus in this article, it&#8217;s probably called Oracle Service Bus. But everyone I know still talks about the AquaLogic Service bus.<br />
I started this article a while ago and since Oracle removed edocs.bea.com I can&#8217;t show you the sources where I got my information from.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2009/10/11/java-callout-on-the-alsb/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2009%2F10%2F11%2Fjava-callout-on-the-alsb%2F&amp;title=Java%20callout%20on%20the%20Oracle%20%2F%20AquaLogic%20Service%20Bus%20%26%238211%3B%20Invoking%20static%20methods%20in%20any%20jar%20file" id="wpa2a_10"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2009/10/11/java-callout-on-the-alsb/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Installing Oracle Service Bus 10gR3 on Mac Os X</title>
		<link>http://blog.xebia.com/2008/12/24/installing-oracle-service-bus-10gr3-on-mac-os-x/</link>
		<comments>http://blog.xebia.com/2008/12/24/installing-oracle-service-bus-10gr3-on-mac-os-x/#comments</comments>
		<pubDate>Wed, 24 Dec 2008 09:55:19 +0000</pubDate>
		<dc:creator>Jeroen van Wilgenburg</dc:creator>
		<br />
<b>Warning</b>:  Invalid argument supplied for foreach() in <b>/home/blog.xebia.com/www/wp-content/plugins/autometa/autometa.php</b> on line <b>303</b><br />
		<category><![CDATA[SOA]]></category>
		<category><![CDATA[alsb]]></category>
		<category><![CDATA[aqualogic]]></category>
		<category><![CDATA[bea]]></category>
		<category><![CDATA[esb]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[Oracle]]></category>
		<category><![CDATA[weblogic]]></category>

	<!-- AutoMeta Start -->
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=857</guid>
		<description><![CDATA[Last week I installed WebLogic and the AquaLogic Service Bus on a Mac. There is no Mac-download on the download page, but by using the HP-UX version everything works fine, you just have to add some command line parameters. How to install WebLogic on a Mac is explained in this blog: Running WebLogic Server 10g [...]]]></description>
			<content:encoded><![CDATA[<p>Last week I installed WebLogic and the AquaLogic Service Bus on a Mac. There is no Mac-download on the download page, but by using the HP-UX version everything works fine, you just have to add some command line parameters.</p>
<p><span id="more-857"></span><br />
How to install WebLogic on a Mac is explained in this blog:<br />
<a href="http://yusuke.homeip.net/blog/2008/09/20/running_weblogic_server_10g_release_3_on_a_mac.html" target="_blank">Running WebLogic Server 10g Release 3 on a Mac</a><br />
Make sure you also read the comments on the blog when you get errors, they contain valuable information that&#8217;ll save you a lot of time.</p>
<p>Go to the <a href="http://www.oracle.com/technology/software/products/osb/index.html" target="_blank">Oracle download page</a> and pick the HP-UX Itanium version. I picked the HP-UX version because it&#8217;s in fact a generic version.</p>
<p>Run the installer on the command line (don&#8217;t run the jar directly!):</p>
<pre>java -Xmx1024m -jar -Dos.name=unix osb103_wls103_generic.jar</pre>
<p>Since the WebLogic installer had some memory problems on a Mac I added the -Xmx1024m paramter. The os.name parameter is added to prevent the &#8220;Insufficient disk space!&#8221; error.</p>
<p>Follow the default installation instructions. When the screen &#8220;Choose Products and Components&#8221; appears I also included the Service Bus Examples, they might come in handy.</p>
<p>After installing the OSB you have to extend your domain with the Oracle Service Bus (or just create a new domain).<br />
Start the Configuration Wizard ($BEA_HOME/wlserver_10.3/common/bin/config.sh) and pick Extend an existing WebLogic domain (assuming you already have a domain running)<br />
Search for the directory where your domain is running (ie. $BEA_HOME/user_projects/domain/base_domain)<br />
<a href="http://blog.xebia.com/wp-content/uploads/2008/12/alsb-extend.png"><img class="alignnone size-medium wp-image-858" title="alsb-extend" src="http://blog.xebia.com/wp-content/uploads/2008/12/alsb-extend-300x60.png" alt="" /></a></p>
<p>I chose to replace all components when asked for and picked the default choice at every wizard screen.</p>
<p>The changes you made to startWebLogic.sh (see the blog by Yusuke Yamamoto I mentioned earlier) also have to be reapplied.</p>
<p>When you start your domain (with startWebLogic.sh)  you should be able to access the Service Bus Console on <a href="http://localhost:7001/sbconsole" target="_blank">http://localhost:7001/sbconsole</a></p>
<p>To check whether things are working I followed the <a href="http://edocs.bea.com/alsb/docs20/tutorial/tutRoute.html#1054563" target="_blank">first tutorial</a>.</p>
<p><a href="http://blog.xebia.com/wp-content/uploads/2008/12/alsb-home.png"><img class="alignnone size-medium wp-image-859" title="alsb-home" src="http://blog.xebia.com/wp-content/uploads/2008/12/alsb-home-300x275.png" alt="" width="300" height="275" /></a></p>
<h3>Sources</h3>
<ul>
<li><a href="http://yusuke.homeip.net/blog/2008/09/20/running_weblogic_server_10g_release_3_on_a_mac.html" target="_blank">Running WebLogic Server 10g Release 3 on a Mac</a></li>
<li><a href="http://edocs.bea.com/alsb/docs20/tutorial/tutIntro.html" target="_blank">Introduction to the BEA AquaLogic Service Bus Tutorials</a></li>
</ul>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2008/12/24/installing-oracle-service-bus-10gr3-on-mac-os-x/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2008%2F12%2F24%2Finstalling-oracle-service-bus-10gr3-on-mac-os-x%2F&amp;title=Installing%20Oracle%20Service%20Bus%2010gR3%20on%20Mac%20Os%20X" id="wpa2a_12"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2008/12/24/installing-oracle-service-bus-10gr3-on-mac-os-x/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Unit testing a Stripes ActionBean wired with Spring Beans</title>
		<link>http://blog.xebia.com/2008/12/16/unit-testing-a-stripes-actionbean-wired-with-spring-beans/</link>
		<comments>http://blog.xebia.com/2008/12/16/unit-testing-a-stripes-actionbean-wired-with-spring-beans/#comments</comments>
		<pubDate>Tue, 16 Dec 2008 11:03:24 +0000</pubDate>
		<dc:creator>Jeroen van Wilgenburg</dc:creator>
		<br />
<b>Warning</b>:  Invalid argument supplied for foreach() in <b>/home/blog.xebia.com/www/wp-content/plugins/autometa/autometa.php</b> on line <b>303</b><br />
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[stripes spring unit test actionbean]]></category>

	<!-- AutoMeta Start -->
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=847</guid>
		<description><![CDATA[Last friday I spent quite some time to figure out how to initialize my Spring beans when unit-testing some Stripes ActionBeans. There wasn&#8217;t any Spring context at all and you really need that for integration testing. How to set up a unit test with Stripes is explained pretty good here. I applied approach 2, run [...]]]></description>
			<content:encoded><![CDATA[<p>Last friday I spent quite some time to figure out how to initialize my Spring beans when unit-testing some Stripes ActionBeans. There wasn&#8217;t any Spring context at all and you really need that for integration testing.<br />
<span id="more-847"></span><br />
How to set up a unit test with Stripes is explained pretty good <a href="http://stripesframework.org/display/stripes/Unit+Testing" target="blank">here</a>.<br />
I applied approach 2, run the tests within a mock container.</p>
<p>My unit test is extending <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/test/context/junit4/AbstractTransactionalJUnit4SpringContextTests.html" target="_blank">AbstractTransactionalJUnit4SpringContextTests</a> and is annotated with @RunWith(SpringJUnit4ClassRunner.class) and @ContextConfiguration(locations = { &#8230; })</p>
<p>The code I&#8217;m about to show should be put after initialzing the MockServletContext. I recommend using a method annotated with @Before where you do the initialization (I called mine setUpMockServletContext)<br />
Since the unit tests run before the Spring config files are put in the WEB-INF directory, you have to tell Stripes where to find the configuration files:</p>
<pre lang="java">context.addInitParameter("contextConfigLocation",
"classpath:dataSourceContext.xml\nclasspath:daoContext.xml\nclasspath:applicationContext.xml");</pre>
<p>Stripes isn&#8217;t smart enough (yet?) to read the @ContextConfiguration annotation, but this file will probably included somewhere in a parent-unit test, so it isn&#8217;t a big deal.</p>
<p>The final step is telling Spring to initialize its context with your MockServletContext (note that this is a Stripes MockServletContext, not the one used by Spring!):</p>
<pre lang="java">ContextLoaderListener springContextLoader = new ContextLoaderListener();
springContextLoader.contextInitialized(new ServletContextEvent(context));</pre>
<p>That&#8217;s all there is to it. Let&#8217;s hope google picks up this blog and other people can handle this tiny problem quicker than I did.</p>
<h3>Sources</h3>
<p>* <a href="http://static.springframework.org/spring/docs/2.5.x/reference/testing.html" target="_blank">Unit testing with Spring</a><br />
* <a href="http://stripesframework.org/display/stripes/Unit+Testing" target="_blank">Unit testing Stripes</a><br />
* <a href="http://www.stripesframework.org/display/stripes/Spring+with+Stripes">Using Spring with Stripes</a><br />
* <a href="http://www.nabble.com/stripes-users-f16325.html">Stripes mailing list</a></p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2008/12/16/unit-testing-a-stripes-actionbean-wired-with-spring-beans/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2008%2F12%2F16%2Funit-testing-a-stripes-actionbean-wired-with-spring-beans%2F&amp;title=Unit%20testing%20a%20Stripes%20ActionBean%20wired%20with%20Spring%20Beans" id="wpa2a_14"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2008/12/16/unit-testing-a-stripes-actionbean-wired-with-spring-beans/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sorting and pagination with Hibernate Criteria &#8211; How it can go wrong with joins</title>
		<link>http://blog.xebia.com/2008/12/11/sorting-and-pagination-with-hibernate-criteria-how-it-can-go-wrong-with-joins/</link>
		<comments>http://blog.xebia.com/2008/12/11/sorting-and-pagination-with-hibernate-criteria-how-it-can-go-wrong-with-joins/#comments</comments>
		<pubDate>Thu, 11 Dec 2008 09:29:37 +0000</pubDate>
		<dc:creator>Jeroen van Wilgenburg</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[criteria]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[pagination]]></category>

	<!-- AutoMeta Start -->
	<category></category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=841</guid>
		<description><![CDATA[Lately I ran into an annoying problem with Hibernate. I tried to do pagination on a query result which was doing an SQL-JOIN under the hood. The query before paging returned about 100 results. When I turned on paging (with 20 results per page) all the pages had less than 20 results! The reason for [...]]]></description>
			<content:encoded><![CDATA[<p>Lately I ran into an annoying problem with Hibernate. I tried to do pagination on a query result which was doing an SQL-JOIN under the hood. The query before paging returned about 100 results. When I turned on paging (with 20 results per page) all the pages had less than 20 results!<br />
The reason for this is that with a JOIN there can be duplicate results and those results are filtered out <strong>after</strong> pagination is done. In this blog I will explain how to solve those problems and it also a cleaner way to build your Criteria queries.<br />
<span id="more-841"></span><br />
Let me explain this with some examples.<br />
Our data model for today consists of doors and colors. A door can have multiple colors.<br />
The data set to start with:<br />
Door A:<br />
-id: 1<br />
-size: large<br />
-colors: red and green</p>
<p>Door B:<br />
-id: 2<br />
-size: small<br />
-color: blue and green</p>
<p>Now lets select all red, green or blue doors, that will be two doors right?</p>
<pre lang="java">Criteria crit = session.createCriteria(Door.class);
crit.createAlias("colors", "c");
crit.add(Restrictions.in("c.name", new Object[]{ "red" , "green" , "blue" }));</pre>
<p>Because of the colors alias an INNER JOIN is used and the result might not be what you expect.<br />
The size of the list is 4, 4 Door objects are returned! That is very strange. When you have a look at the SQL you will see the following query:<br />
<code>select this_.id as id2_1_, this_.size as size2_1_, colors3_.DOOR_ID as DOOR1_, c1_.id as COLOR2_, c1_.id as id3_0_, c1_.name as name3_0_<br />
from doors this_ inner join DOORS_COLORS colors3_ on this_.id=colors3_.DOOR_ID inner join colors c1_ on colors3_.COLOR_ID=c1_.id<br />
where c1_.name in (?, ?, ?)</code><br />
Translated to readable SQL:<br />
<code>SELECT * FROM doors d<br />
INNER JOIN doors_colors dc on d.id=dc.door_id<br />
INNER JOIN colors c ON c.id=dc.color_id<br />
WHERE c.name in (?, ?, ?)</code><br />
This query will indeed return 4 results, but we&#8217;re selecting Door objects, not SQL-rows. Looking at the java code I expected Door object, not query result rows wrapped in a Door object<br />
To solve this problem you can add a ResultTransformer to the crit-object:</p>
<pre lang="java">crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);</pre>
<p>Now only two doors are selected, problem solved.<br />
Well, not so fast, let&#8217;s see what happens with many doors. Our database now has 16 doors. When we select the red, green and blue doors again, 11 results appears. Suppose we want to add paging to the results, because it&#8217;s just too many doors to handle at a time. 5 doors per page is enough.<br />
We can achieve it by adding the following two lines:</p>
<pre lang="java">crit.setFirstResult(0);
crit.setMaxResults(5);</pre>
<p>11 doors found, 5 results per page and display the results starting from the first result (which is 0-indexed).<br />
How many results do you expect on the first page?<br />
Not the 3 results returned probably. The ResultTransformer is still active by the way. What happens is that the paging is applied before the duplicate entities are filtered out.</p>
<p>When you start thinking in SQL you might come up with the idea to use a subquery. This is exactly what we&#8217;re are going to do in Hibernate.<br />
A subquery in pseudocode:<br />
select * from doors d where d.id in (select id from doors, colors where colors.name in (&#8216;red&#8217;,'green&#8217;,'blue&#8217;))<br />
As you can see the subquery only selects the id column and in my previous example a complete Door object was selected.<br />
To select other columns than the columns in the Entity object you can use Projections. With multiple columns use the ProjectionList object. For now we need an id-projection, which has is own method:</p>
<pre lang="java">crit.setProjection(Projections.id());</pre>
<p>Now a list with int&#8217;s is selected. This result is the input for the next query. You can create Criteria objects without a Hibernate Session for later use. These objects are called DetachedCriteria.</p>
<p>When we rename the crit to dc and create it as a DetachedCriteria you will have the following lines of code:</p>
<pre lang="java">DetachedCriteria dc = DetachedCriteria.forClass(Door.class);
dc.createAlias( "colors" , "c");
dc.add(Restrictions.in( "c.name" , new Object[]{ "red" , "green" , "blue" }));
dc.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
dc.setProjection(Projections.id());</pre>
<p>The next step is creating an outer query around the previous query.</p>
<pre lang="java">Criteria outer = session.createCriteria(Door.class);
outer.add(Subqueries.propertyIn("id", dc));
outer.setFirstResult(0);
outer.setMaxResults(5);</pre>
<p>With Subqueries.propertyIn you can add the previous query. When you add paging and sorting to the new outer query object all your problems are solved. You can even get rid of the ResultTransformer and get the same result. When you&#8217;re tuning performance it might be a nice test to see whether it makes any difference to do the DISTINCT before you pass the results to the outer query.</p>
<p>How you can solve DISTINCT problemns is explained reasonably in the Hibernate FAQ:<br />
<a href="http://www.hibernate.org/117.html#A12" target="_blank">Hibernate does not return distinct results for a query with outer join fetching enabled for a collection (even if I use the distinct keyword)?</a></p>
<p>The lesson I learned with Hibernate is that you still have to know SQL and don&#8217;t trust the results blindly. If you don&#8217;t know why you have to use DISTINCT and how a JOIN presents its results you&#8217;ll get lost very soon.</p>
<p>With the DetachedCriteria object you can split your queries in a very readable way and when using projections, the SQL under the hood only selects the needed columns, which improves performance.</p>
<h3>sources</h3>
<p><a href="http://floledermann.blogspot.com/2007/10/solving-hibernate-criterias-distinct.html" target="_blank">http://floledermann.blogspot.com/2007/10/solving-hibernate-criterias-distinct.html</a><br />
<a href="http://www.hibernate.org/117.html#A12" target="_blank">http://www.hibernate.org/117.html#A12</a></p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2008/12/11/sorting-and-pagination-with-hibernate-criteria-how-it-can-go-wrong-with-joins/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2008%2F12%2F11%2Fsorting-and-pagination-with-hibernate-criteria-how-it-can-go-wrong-with-joins%2F&amp;title=Sorting%20and%20pagination%20with%20Hibernate%20Criteria%20%26%238211%3B%20How%20it%20can%20go%20wrong%20with%20joins" id="wpa2a_16"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2008/12/11/sorting-and-pagination-with-hibernate-criteria-how-it-can-go-wrong-with-joins/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Readable url’s in Wicket &#8211; An introduction to wicketstuff-annotation</title>
		<link>http://blog.xebia.com/2008/10/09/readable-url%e2%80%99s-in-wicket-an-introduction-to-wicketstuff-annotation/</link>
		<comments>http://blog.xebia.com/2008/10/09/readable-url%e2%80%99s-in-wicket-an-introduction-to-wicketstuff-annotation/#comments</comments>
		<pubDate>Thu, 09 Oct 2008 11:29:34 +0000</pubDate>
		<dc:creator>Jeroen van Wilgenburg</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Wicket]]></category>

	<!-- AutoMeta Start -->
	<category></category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=765</guid>
		<description><![CDATA[Have you ever tried to pronounce a url generated by Wicket? It’s quite a tedious job and often end users want to have understandable url’s (even when that url has no meaning). It’s is quite easy to get normal url’s in Wicket. In this article I’ll show you several solutions, the first two with plain [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever tried to pronounce a url generated by Wicket? It’s quite a tedious job and often end users want to have understandable url’s (even when that url has no meaning).</p>
<p>It’s is quite easy to get normal url’s in Wicket. In this article I’ll show you several solutions, the first two with plain Wicket and the final solution is with wicketstuff-annotations.</p>
<p><span id="more-765"></span></p>
<p>Recently I read an article called “<a href="http://css.dzone.com/news/wicket-creating-restful-urls" target="_blank">Wicket Creating RESTful URLs</a>”. It’s a useful article but it still didn’t feel right. It should be easier and in the right place.<br />
In <a href="http://www.stripesframework.org" target="_blank">Stripes</a> for example you can just put @UrlBinding(&#8220;/helloWorld.action&#8221;) on your ActionBean and it works. That’s what I want!</p>
<p>After some searching I found wicketstuff-annotation. <a href="http://www.wicketstuff.org" target="_blank">Wicketstuff</a> provides a large set of additions to Wicket to make it even better. wicketstuff-annotation is a small part of it.</p>
<h3>Start from scratch</h3>
<p>To demonstrate wsa (Wicketstuff annotation) I will let Maven 2 generate a simple Wicket application from scratch. To generate this application visit http://wicket.apache.org/quickstart.html</p>
<p><img src="http://blog.xebia.com/wp-content/uploads/2008/10/wicketstuff-url-generate.png" alt="" width="524" height="200" /></p>
<p>Execute this statement on the command line and you’ll have a working Wicket application within seconds.</p>
<p>Add a link to HomePage.html so you can see what url’s Wicket generates and how to improve them:</p>
<blockquote>
<pre>&lt;wicket:link&gt;
&lt;a href="HomePage2.html?page=133&amp;paragraph=25"&gt;
Link to wicket document HomePage2.html
&lt;/a&gt;
&lt;/wicket:link&gt;</pre>
</blockquote>
<p>Make a copy of HomePage.java and HomePage.html and call the files HomePage2.java and HomePage2.html. Change the href to HomePage2.html in the file HomePage2.html to HomePage.html. When you redeploy the application you will see the unreadable url I was talking about earlier:</p>
<blockquote>
<pre>http://localhost:8080
/wicketstuff-test/?wicket:bookmarkablePage=:com.xebia.HomePage2&amp;paragraph=25&amp;page=133</pre>
</blockquote>
<p>I added the parameters page and paragraph to show that even these parameters can be made more readable.</p>
<p>Another bad thing is that we expose our package structure. End users don’t care in what package the page is and you shouldn’t give potential hackers any information.</p>
<h3>The plain Wicket solution</h3>
<p>The simplest solution is mounting a package to a path. We can map all of the package com.xebia to http://localhost:8080/wicketstuff-test/web for example. Unfortunately we cannot map to the root (/) of the application. To mount a package add the following line to the constructor of WicketApplication:</p>
<blockquote>
<pre>mount("web",PackageName.forClass(HomePage.class));</pre>
</blockquote>
<p>The ugly url now looks much better:</p>
<blockquote>
<pre>http://localhost:8080/wicketstuff-test/web/HomePage2/paragraph/25/page/133/</pre>
</blockquote>
<p>Even the parameters page and paragraph are improved.</p>
<p>Suppose you don’t want to expose the name of your WebPage (HomePage2) and also hide the parameter names. This can be achieved by mounting a MixedParamurlCodingStrategy to the application:</p>
<blockquote>
<pre>public WicketApplication() {</pre>
<pre>    String[] parameterNames = new String[] { "page", "paragraph"};</pre>
<pre>    MixedParamUrlCodingStrategy mixedParamUrlCodingStrategy =
new MixedParamUrlCodingStrategy(</pre>
<pre>            "h2", HomePage2.class, parameterNames);</pre>
<pre>    mount(mixedParamUrlCodingStrategy);</pre>
<pre>}</pre>
</blockquote>
<p>The problem with this solution is that you have to pass all parameters and put all class files in the Application file. The url structure and page parameters are related to the page, not the application, so they should be on the WebPage. But the result is a very nice url without  having to add an extra dependency to wsa:</p>
<blockquote>
<pre>http://localhost:8080/wicketstuff-test/h2/133/25/</pre>
</blockquote>
<h3>The Wicketstuff Annotation solution</h3>
<p>To add wsa suppport to your application you have to add a dependency to your pom.xml:</p>
<blockquote>
<pre>&lt;dependency&gt;</pre>
<pre>     &lt;groupId&gt;org.wicketstuff&lt;/groupId&gt;</pre>
<pre>     &lt;artifactId&gt;wicketstuff-annotation&lt;/artifactId&gt;</pre>
<pre>     &lt;version&gt;1.1&lt;/version&gt;</pre>
<pre> &lt;/dependency&gt;</pre>
</blockquote>
<p>The next step is clearing the old solution from the constructor of WicketApplication.<br />
Add the folllowing line:<br />
new AnnotatedMountScanner().scanPackage(&#8220;com.xebia&#8221;).mount(this);<br />
This line will search the package com.xebia for annotations to mount url’s. In a production environment it is probably smarter to limit this to the package where all the WebPage classes are (ie. com.xebia.web).</p>
<p>Now we can finally add annotations to HomePage2 :</p>
<blockquote>
<pre>@MountPath(path = "h2")</pre>
<pre>@MountMixedParam(parameterNames = { "page", "paragraph" })</pre>
<pre>public class HomePage2 extends WebPage {</pre>
<pre>...</pre>
<pre>}</pre>
</blockquote>
<p>This works exactly the same as before, only in the right place.</p>
<p>There are several variations on the second annotation :</p>
<blockquote><p>@MountPath (and no second annotation)</p>
<p>http://localhost:8080/wicketstuff-test/h2/paragraph/25/page/133/</p>
<p>@MountPath and @MountMixedParam</p>
<p>http://localhost:8080/wicketstuff-test/h2/133/25/</p>
<p>@MountPath and @MountQueryString</p>
<p>http://localhost:8080/wicketstuff-test/h2?paragraph=25&#038;page=133</p></blockquote>
<p>There are several other encoding strategies you can use. On the wsa javadoc there isn’t much information. When you want to know more you should consult the Wicket javadocs and look for the package org.wicket.request.target.coding. The names used here are similar to the ones for wsa.</p>
<h3>Conclusion</h3>
<p>Wicketstuff annotation is a very nice addition to Wicket. It helps you to encode your url’s in the right place. The only small drawback is the dependency on Spring core, such a small library as wsa should work without Spring (not that Spring is a bad thing, I just don’t like many dependencies). So don’t be alarmed when you see a Spring jar pop up between your libraries.<br />
Also be aware that the mount(path, packageName) solution is the safest when you don’t want to expose the package structure. When you forget to add annotations you end up with the ugly url’s and still exposing the package structure. I tried to add multiple mount points, but this wasn’t possible.</p>
<h3>Sources</h3>
<p><a href="http://wicketstuff.org/confluence/display/STUFFWIKI/wicketstuff-annotation" target="_blank">http://wicketstuff.org/confluence/display/STUFFWIKI/wicketstuff-annotation</a></p>
<p><a href="http://css.dzone.com/news/wicket-creating-restful-urls" target="_blank">http://css.dzone.com/news/wicket-creating-restful-urls</a></p>
<p><a href="http://cwiki.apache.org/WICKET/url-coding-strategies.html" target="_blank">http://cwiki.apache.org/WICKET/url-coding-strategies.html</a></p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2008/10/09/readable-url%e2%80%99s-in-wicket-an-introduction-to-wicketstuff-annotation/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2008%2F10%2F09%2Freadable-url%25e2%2580%2599s-in-wicket-an-introduction-to-wicketstuff-annotation%2F&amp;title=Readable%20url%E2%80%99s%20in%20Wicket%20%26%238211%3B%20An%20introduction%20to%20wicketstuff-annotation" id="wpa2a_18"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2008/10/09/readable-url%e2%80%99s-in-wicket-an-introduction-to-wicketstuff-annotation/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  blog.xebia.com/author/jvanwilgenburg/feed/ ) in 14.04551 seconds, on Feb 9th, 2012 at 6:01 pm UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on Feb 9th, 2012 at 7:01 pm UTC -->
