<?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>Mattias Holmqvist - Writings about software development</title>
	<atom:link href="http://mattiasholmqvist.se/feed/" rel="self" type="application/rss+xml" />
	<link>http://mattiasholmqvist.se</link>
	<description></description>
	<lastBuildDate>Fri, 06 May 2011 11:06:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Loading Clojure code with java.util.ServiceLoader</title>
		<link>http://mattiasholmqvist.se/2011/05/loading-clojure-code-with-java-util-serviceloader/</link>
		<comments>http://mattiasholmqvist.se/2011/05/loading-clojure-code-with-java-util-serviceloader/#comments</comments>
		<pubDate>Fri, 06 May 2011 11:01:44 +0000</pubDate>
		<dc:creator>Mattias Holmqvist</dc:creator>
				<category><![CDATA[clojure]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[class loading]]></category>

		<guid isPermaLink="false">http://mattiasholmqvist.se/?p=631</guid>
		<description><![CDATA[This blog post is also available in Swedish here. Here&#8217;s a something we learned when working on the game engine for the Citerus coding challenge CrazySnake (in Swedish). Maybe some of our findings about class loading in Clojure and usage of ServiceLoader will be useful for someone out there, so I thought I&#8217;d share them. [...]]]></description>
			<content:encoded><![CDATA[<p>This blog post is also available in Swedish <a href="http://www.citerus.se/post/325558-ladda-clojure-kod-med-java-util-serviceloader">here</a>.</p>
<p>Here&#8217;s a something we learned when working on the game engine for the Citerus coding challenge <a href="http://www.citerus.se/crazysnake">CrazySnake</a> (in Swedish). Maybe some of our findings about class loading in Clojure and usage of <code><a href="http://download.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html">ServiceLoader</a></code> will be useful for someone out there, so I thought I&#8217;d share them.</p>
<p>The competing teams provided their implementations of the <code>Brain</code> interface from our <a href="https://bitbucket.org/citerus/crazysnake-public">API</a> and packaged the implementation in a jar-file. </p>
<blockquote><p>
The brain was injected into a snake, that moved around autonomously on a game field, eating fruits and avoiding to crash into other snakes or walls. Remember the old game called Snake that used to be on several mobile phones? Something like that, but autonomously and multi-player.
</p></blockquote>
<p>Since we wanted to load the implementations at runtime, we needed dynamic class loading. </p>
<p>The most commonly used approach to dynamic class loading has been simply use of the <code>Class.forName()</code>. However, this only supports loading of classes using their name, and not their type. Since we didn&#8217;t want to restrict the names of the implementing classes we simply wanted to load all implementations of the <code>Brain</code> interface that were provided. The <code>ServiceLoader</code> has been around since Java SE 6 and supports dynamic class loading based on a type. The <code>ServiceLoader</code> reads files in the <code>META-INF/services/</code> directory on the classpath and tries to lazily instantiate classes based on the fully-qualified class-names in these files. The name of the file should correspond to the fully-qualified name of the service (interface) that the classes implement (in our case this was <code>se.citerus.crazysnake.Brain</code>). Look in the examples-projects <a href="https://bitbucket.org/citerus/crazysnake-public">here</a> to see how it was set up.</p>
<p>We used java.util.ServiceLoader to load each team&#8217;s implementation by creating a <code>URLClassLoader</code> that was fed into the <code>ServiceLoader.load()</code>. This looked something like this:</p>
<pre class="brush:[java]">
  URL[] urls = {file.toURI().toURL()};
  ClassLoader classLoader = new URLClassLoader(urls);
  ServiceLoader&lt;Brain&gt; services = ServiceLoader.load(Brain.class, classLoader);
</pre>
<p>The approach we first used (seen above) worked fine for our initial test-brains that were implemented in Java and we were feeling quite happy with the results. However, we also wanted it to be possible to implement the brains in more JVM-supported languages than Java and Clojure was an obvious candidate.  The solution worked fine with Groovy and Scala but when trying to implement a <code>Brain</code> in Clojure using <code>:gen-class</code> we stepped into some trouble. Below is the code for a stupid brain implemented in Clojure:</p>
<pre class="brush:[clojure]">
(ns se.citerus.crazysnake.brain.clojure-brain
  (:import
    [se.citerus.crazysnake Movement])
  (:gen-class
    :name se.citerus.crazysnake.brain.ClojureBrain
    :implements [se.citerus.crazysnake.Brain]
    :main false))

;-- Implementation of Brain interface

(defn -init [this participants meta])

(defn -getName [this]
  "ClojureBrain")

(defn -getNextMove [this state]
  Movement/FORWARD)
</pre>
<p>When we tried to load a Clojure-implementation the <code>ServiceLoader</code> threw an <code>ServiceConfigurationError</code> when accessing its iterator. Some <a href="http://dev.clojure.org/jira/browse/CLJ-260">research</a> led us to the knowledge that Clojure uses the current Thread&#8217;s context class loader by default. Since the context classloader has no knowledge of our Clojure code (only our created classloader knows this), this didn&#8217;t work. This made us understand that we had to set the Thread&#8217;s context classloader before trying to call <code>ServiceLoader.load()</code>. The following code made the whole shebang work like a charm:</p>
<pre class="brush:[java]">
File brainImplementingJarFile = new File(pathToJar);
URL[] urls = {file.toURI().toURL()};
ClassLoader contextLoader = Thread.currentThread().getContextClassLoader();
ClassLoader classLoader = new URLClassLoader(urls, contextLoader);
Thread.currentThread().setContextClassLoader(classLoader);
ServiceLoader&lt;Brain&gt; services = ServiceLoader.load(Brain.class, classLoader);

// Reset the context classloader
Thread.currentThread().setContextClassLoader(contextLoader);
</pre>
<p>Hope someone will find this useful when working with dynamically loading Clojure classes!</p>
]]></content:encoded>
			<wfw:commentRss>http://mattiasholmqvist.se/2011/05/loading-clojure-code-with-java-util-serviceloader/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Building with Tycho &#8211; part 3. Testing, Code coverage and easier development using Target Definitions.</title>
		<link>http://mattiasholmqvist.se/2010/06/building-with-tycho-part-3-testing-code-coverage-and-easier-development-using-target-definitions/</link>
		<comments>http://mattiasholmqvist.se/2010/06/building-with-tycho-part-3-testing-code-coverage-and-easier-development-using-target-definitions/#comments</comments>
		<pubDate>Thu, 10 Jun 2010 06:57:31 +0000</pubDate>
		<dc:creator>Mattias Holmqvist</dc:creator>
				<category><![CDATA[citerus]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[osgi]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tycho]]></category>

		<guid isPermaLink="false">http://mattiasholmqvist.se/?p=498</guid>
		<description><![CDATA[When you want to work effectively with Maven/Tycho on a larger project, you quickly find yourself wanting more features than the simple build presented in my previous posts. In this post i will cover some important features of Tycho that you might need to work more effectively with Tycho. I suspect this post will be [...]]]></description>
			<content:encoded><![CDATA[<p>When you want to work effectively with Maven/Tycho on a larger project, you quickly find yourself wanting more features than the simple build presented in my previous posts. In this post i will cover some important features of Tycho that you might need to work more effectively with Tycho.</p>
<p>I suspect this post will be quite massive so I&#8217;ll skip the screenshots in this one. Instead I decided to create a sample project structure and put it up on <a href="http://github.com/mattiasholmqvist/tychoexamples">my github account</a>. See the readme for information on how to set up the example projects.</p>
<h3>Overall structure and idea</h3>
<p>The parent project (with .parent suffix) is the mother of the build. Practically all configuration of the build is handled by its pom.xml file. We strive to keep the sub-projects as small as possible to minimize the duplication of information in the development environment (Eclipse in this case) and the headless build system (Tycho/Maven). </p>
<p>The information that we&#8217;re required to provide in the sub-projects&#8217; pom.xml files are the version of the project (which is verified against the version provided in the Manifest.MF) and the type of project (feature/bundle/test bundle/update site).</p>
<p>I will describe the things that I reckon is most important in the example projects so that you (hopefully) can follow what&#8217;s happening when building the projects.</p>
<h3>Features and update sites</h3>
<p>The sample project contains a feature project and an update site project. These two projects are intended to give some extra help from within the Eclipse IDE. When the plugins are built by the CI server (I assume you have one!?), the server can also push the update site (containing the feature) to an HTTP server (or similar) that is available for developers that want to use the plugins as target platform in their development. This makes the build quite modular and nice to work with.</p>
<p>Tycho makes the automation for building for your features and update sites quite a simple task. You need to create a pom.xml for your feature looking somewhat like this:</p>
<pre class="brush:[xml]">&lt;project&gt;
  &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
  &lt;parent&gt;
    &lt;groupId&gt;se.mattiasholmqvist&lt;/groupId&gt;
    &lt;artifactId&gt;examples&lt;/artifactId&gt;
    &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
  &lt;/parent&gt;
  &lt;groupId&gt;se.mattiasholmqvist&lt;/groupId&gt;
  &lt;artifactId&gt;examples.feature&lt;/artifactId&gt;
  &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
  &lt;packaging&gt;eclipse-feature&lt;/packaging&gt;
&lt;/project&gt;</pre>
<blockquote><p><b>Note:</b> See the sub-project with .feature-suffix for the provided example.</p></blockquote>
<p>This pom file is very similar to the bundle pom file. The only difference is the &lt;packaging&gt; tag that tells Tycho to build the project as a feature. The nice thing about these tiny poms is that the dependency management becomes quite easy. You can more or less work without caring about the Maven configuration since Tycho uses the Manifest and feature.xml to setup the correct build dependencies.</p>
<p>Of course, you would also need to specify a proper target platform. In my previous posts, I&#8217;ve shown how to do this with the -Dtycho.targetPlatform switch, which works but there is a cooler and more flexible way that also works great with Tycho.</p>
<h3>Target platform definitions</h3>
<p>Ok, we have our build set up nicely and all seems to be working fine. However, the great success of your project has made it grow significantly and it seems that not all developers that join the project are able (or willing) to setup their target platforms (in Eclipse) in accordance with the Tycho build since it requires quite a lot of understanding about Tycho/OSGi and perhaps Eclipse P2 as well. This causes disturbance to your project and you do your best to help your teammates out, but you reckon there must be a better/simpler way of tackling this issue than to manually manage the target platform installation for each developer.</p>
<blockquote>
<h4>A short tale about the target definition file</h4>
<p>The target definition file is quite a newcomer to the Eclipse development environment. It is a nice feature that lets you specify the target platform in a structured fashion (although the previously supported directory-based platforms are still supported in Eclipse) which I highly recommend. Another even nicer thing is that Tycho also supports resolving the target platform from the Eclipse target definition file. This means that setting up the development environment for a new developer in simply a matter of locating the target definition file and click on &#8220;Set as target platform&#8221;, and the target platform is now consistent with the platform that Tycho uses. This is probably not a perfect description but you can find some more info from the Eclipse help and some more info on using them in practice can be found <a href="http://www.modumind.com/2008/04/29/rcp-target-platform-tips/">here</a>.</p></blockquote>
<h4>The first step &#8211; creating the .target file</h4>
<p>I like to keep my target platform in a separate project, just for structure and separation. My guess is that you can make it work by putting it anywhere you want, but in my example I&#8217;ve put it in the project called <code>se.mattiasholmqvist.tychoexamples.targetplatform</code>.</p>
<p>I&#8217;ve created a target definition file in Eclipse (it&#8217;s found in the New-&gt; menu) and I&#8217;ve called this file <strong>example_target.target</strong> and placed it directly in the target platform project directory. I selected a few Eclipse dependencies that I needed for my bundle and saved the file.</p>
<p>We also need to provide some configuration to this project. I&#8217;m not sure if this is the only way to do this at the time of writing but I&#8217;m sure that it works for me. This is a snippet from the pom.xml that I use for the target-platform project:</p>
<pre class="brush:[xml]">
&lt;build&gt;
  &lt;plugins&gt;
    &lt;plugin&gt;
    &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;
      &lt;artifactId&gt;build-helper-maven-plugin&lt;/artifactId&gt;
      &lt;version&gt;1.3&lt;/version&gt;
      &lt;executions&gt;
        &lt;execution&gt;
          &lt;id&gt;attach-artifacts&lt;/id&gt;
          &lt;phase&gt;package&lt;/phase&gt;
          &lt;goals&gt;
            &lt;goal&gt;attach-artifact&lt;/goal&gt;
          &lt;/goals&gt;
          &lt;configuration&gt;
            &lt;artifacts&gt;
              &lt;artifact&gt;
                &lt;file&gt;example_target.target&lt;/file&gt;
                &lt;type&gt;target&lt;/type&gt;
                &lt;classifier&gt;example_target&lt;/classifier&gt;
              &lt;/artifact&gt;
            &lt;/artifacts&gt;
          &lt;/configuration&gt;
        &lt;/execution&gt;
      &lt;/executions&gt;
    &lt;/plugin&gt;
  &lt;/plugins&gt;
&lt;/build&gt;
</pre>
<h3>Testing</h3>
<p>Tycho supports unit-testing (JUnit) of code within bundles by default. This has long been a hazzle (for me atleast), when working with Ant + PDE  build so this support is extremely welcome. Tycho tests bundles via the <em>integration-test</em> Maven goal, which is different from the regular <em>test</em> goal. It also makes life easier if you know a bit about the conventions Tycho uses for finding tests (this might however be subject to change in the future).</p>
<p>Start by creating a simple bundle that will contain the classes of your application. Second, we will create a separate bundle that will contain our tests. The convention here is to use the same same as the bundle with your application classes and add the prefix .tests to the test bundle name. I provide a (really stupid) test in the project with .tests-suffix in the github repo. </p>
<p><strong>Note: </strong> The Test suffix is important if you want to use the default configuration of Tycho, or it won&#8217;t find your test class. Below is a snippet from the configuration of the test plugin for my example projects which enables unit testing for the project:</p>
<pre class="brush:[xml]">
&lt;packaging&gt;eclipse-test-plugin&lt;/packaging&gt;
</pre>
<blockquote><p>I also made the .tests project a fragment to the bundle it belongs to. This makes it easier to locate classes to depend on. I think this setup works well within Eclipse/OSGi development.</p></blockquote>
<h3>Code coverage using EclEmma</h3>
<p>Using code coverage in an OSGi environment is special. There are however some Eclipse plugins that support code coverage and it is possible to integrate these with Tycho. I want to give credit to the guys at Sonatype for helping me out with this. They recently posted some information on their website related to code coverage, so my example project might serve as a good complement to <a href="https://docs.sonatype.org/display/TYCHO/How+to+integrate+EMMA+(code+coverage)+with+Tycho">this article.</a> I thought it might be a good idea to wrap our discussions up in an example that is perhaps a bit more accessible than the posts on the mailing list. My example is however a bit more simplistic than the example in the article above. I do not copy resources from multiple test bundles, but instead generate a report for each bundle. Check out the article if you need that feature.</p>
<p>In large, the code coverage is handled by a Maven profile so you need to pass a <code>-Pcoverage</code> flag to enable it.</p>
<p>To run the test suite (1 test in the example project) with code coverage and reporting:</p>
<pre class="brush:[bash]">
mvn integration-test verify -Pcoverage
</pre>
<p>In my examples project I&#8217;ve put together a small bundle project that contains Eclemma Equinox runtime. It would probably be possible just to deploy it to a locally accessible Maven repository but for ease of use of the examples I&#8217;ve made it a part of the build instead. When you run <code>mvn integration-test</code> with the <code>coverage</code> profile in the parent project directory, this bundle will do code coverage of all bundles/packages that matches the configuration in the parent pom.xml. See the <code>&lt;profiles&gt;</code> configuration in the parent- and test project pom.xml files for exactly how this is done.</p>
<p>Hope this post can help someone out there with use Tycho which is a great tool for your OSGi development. </p>
<p>Checkout <a href="http://tycho.sonatype.org/">Sonatype&#8217;s Tycho website</a> to keep up-to-date with the development of Tycho.</p>
]]></content:encoded>
			<wfw:commentRss>http://mattiasholmqvist.se/2010/06/building-with-tycho-part-3-testing-code-coverage-and-easier-development-using-target-definitions/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Building with Tycho &#8211; part 2 (RCP applications)</title>
		<link>http://mattiasholmqvist.se/2010/03/building-with-tycho-part-2-rcp-applications/</link>
		<comments>http://mattiasholmqvist.se/2010/03/building-with-tycho-part-2-rcp-applications/#comments</comments>
		<pubDate>Tue, 23 Mar 2010 21:25:23 +0000</pubDate>
		<dc:creator>Mattias Holmqvist</dc:creator>
				<category><![CDATA[citerus]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[osgi]]></category>
		<category><![CDATA[tycho]]></category>

		<guid isPermaLink="false">http://mattiasholmqvist.se/?p=211</guid>
		<description><![CDATA[Building RCP applications (products) have always been quite smooth when working from within Eclipse IDE. To me, it is extremely important that the development team can easily build their product and have continuous integration of the product on a CI server such as Hudson. Previously, PDE build have been the way to build RCP applications [...]]]></description>
			<content:encoded><![CDATA[<p>Building RCP applications (products) have always been quite smooth when working from within Eclipse IDE. To me, it is extremely important that the development team can easily build their product and have <a href="http://martinfowler.com/articles/continuousIntegration.html">continuous integration</a> of the product on a CI server such as Hudson.</p>
<blockquote><p>Previously, PDE build have been the way to build RCP applications in a headless build environment (such as Hudson, for example), but all those Ant scripts and configuration options in the build.properties file are not that appealing to me.</p></blockquote>
<p>Tycho provides support for building RCP applications from product configuration files. As we will see, this makes the headless build for RCP applications a lot less confusing.</p>
<p>One nice thing that I forgot to mention about Tycho in my <a href="http://mattiasholmqvist.se/2010/02/building-with-tycho-part-1-osgi-bundles/" target="_self">previous post</a> is that is has great support for Manifest-first development. This means that the development team does not need to synchronize their Manifest files with the pom.xml that Tycho uses, it is handled automatically for them. The developers can use &#8220;Imported packages&#8221; and &#8220;Required plug-ins&#8221; as usual and Tycho will use that information to resolve the compilation target for each bundle. I find this workflow easier and more appealing than pom-first development (for example BND-plugin with a separate <code>.bnd</code> file for configuring exported/imported packages). I guess you have to figure out which way works for you.</p>
<p>This might not be as appealing for some of you who are accustomed to specifying Maven dependencies in the pom.xml but Tycho supports pom-first development as well. However, since I like to work Manifest-first I will use it for my examples here. For info on pom-first development, check out the Tycho users mailing list or the official website.</p>
<p>This will be a quick intro on how to get started with a small Eclipse RCP application in Tycho. The first steps involves creating the setup of one plugin/feature/product so you who are Eclipse-wise don&#8217;t need to follow these steps thoroughly.</p>
<p><strong>Note: This post will assume Tycho 0.7.0 and Eclipse 3.5.2. </strong>Some of the issues in this post will probably be fixed in upcoming releases of Tycho.<strong> </strong>Hopefully the main workflow will remain somewhat steady. I will also only provide examples for the explicit target platform resolver. The implicit p2 resolver should work just as fine, check out the <a href="http://mattiasholmqvist.se/2010/02/building-with-tycho-part-1-osgi-bundles/" target="_self">previous post</a> to see how to set it up. I will also not include all configuration options that are available for Tycho, but please comment if you miss something and I might add it later!</p>
<p>Let&#8217;s build an application!</p>
<h3>Creating the application plug-in</h3>
<p>Start by creating a plug-in that defines our RCP-application. There are some templates ready for creating example RCP application in the Eclipse distributions. I used the &#8220;Hello RCP&#8221; template which contains a simple application saying &#8220;Hello RCP&#8221; in the title bar. See the screenshots below for how I created my example plugin.</p>
<p><a href="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/new-plugin-project-for-rcp-1.png"><img class="alignnone size-medium wp-image-392" title="new-plugin-project-for-rcp-1" src="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/new-plugin-project-for-rcp-1-266x300.png" alt="" width="266" height="300" /></a><a href="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/new-plugin-project-for-rcp-2.png"><img class="alignnone size-medium wp-image-393" title="new-plugin-project-for-rcp-2" src="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/new-plugin-project-for-rcp-2-266x300.png" alt="" width="266" height="300" /></a><a href="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/new-plugin-project-for-rcp-3.png"><img class="alignnone size-medium wp-image-394" title="new-plugin-project-for-rcp-3" src="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/new-plugin-project-for-rcp-3-266x300.png" alt="" width="266" height="300" /></a></p>
<h3>Creating the application feature</h3>
<p>Products in Eclipse can either be plugin-based or feature-based.  We will build a feature-based application so we start by creating a project that will contain the main feature for our RCP application. The feature contains a feature.xml, which is used to define which plug-ins constitutes the feature. When asked for plug-ins to include in the feature, reference the plug-in that we created in the first step.</p>
<p><a href="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/new-feature-project-for-rcp-1.png"><img class="alignnone size-medium wp-image-396" title="new-feature-project-for-rcp-1" src="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/new-feature-project-for-rcp-1-300x287.png" alt="" width="300" height="287" /></a><a href="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/new-feature-project-for-rcp-2.png"><img class="alignnone size-medium wp-image-397" title="new-feature-project-for-rcp-2" src="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/new-feature-project-for-rcp-2-300x287.png" alt="" width="300" height="287" /></a></p>
<p>The feature will be referenced by the product definition, which tells Tycho to use it when constituting the product.</p>
<h3>Configuring the product definition</h3>
<p>We need to create the product definition that constitute our product. This will include the feature project that we created previously and the Eclipse RCP feature. <strong>Pay attention to the naming of the product definition file</strong> since Tycho uses the convention that the file name should match the maven module with a .product suffix.</p>
<p>Start by creating a new project (I prefer keeping the product file in a separate project).</p>
<p><a href="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/new-generic-project.png"><img class="alignnone size-medium wp-image-379" title="new-generic-project" src="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/new-generic-project-300x287.png" alt="New project" width="300" height="287" /></a></p>
<p>Name the project so that it matches your product in whatever way you find appropriate. I named my project se.mattiasholmqvist.rcpexample. Tycho now assumes that my product definition file is name <strong>se.mattiasholmqvist.rcpexample.product</strong></p>
<p><a href="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/new-product-project-for-rcp-2.png"><img class="alignnone size-medium wp-image-398" title="new-product-project-for-rcp-2" src="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/new-product-project-for-rcp-2-300x287.png" alt="" width="300" height="287" /></a></p>
<p>We create our product configuration file and add it to our product project.</p>
<p><a href="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/new-product-configuration.png"><img class="alignnone size-medium wp-image-401" title="new-product-configuration" src="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/new-product-configuration-300x287.png" alt="" width="300" height="287" /></a> <a href="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/new-product-configuration-2.png"><img class="alignnone size-medium wp-image-402" title="new-product-configuration-2" src="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/new-product-configuration-2-259x300.png" alt="" width="259" height="300" /></a></p>
<p>Choose an ID and a name for the product and make sure that you set your product includes native launcher artifacts.</p>
<p><a href="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/product-configuration-1.png"><img class="alignnone size-medium wp-image-403" title="product-configuration-1" src="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/product-configuration-1-300x48.png" alt="" width="300" height="48" /></a></p>
<p>We need to create a new product definition. This definition refers to the application extension that our application plug-in defines (this comes from the RCP template).</p>
<p><a href="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/product-configuration-2.png"><img class="alignnone size-medium wp-image-404" title="product-configuration-2" src="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/product-configuration-2-300x249.png" alt="" width="300" height="249" /></a></p>
<p>You need to specify which features constitutes the product. Since we build an Eclipse RCP product you need to include the RCP feature (org.eclipse.rcp) and the feature that we created earlier which contains our application-defining plug-in. Make sure that the definition specifies that the product is build <strong>using features</strong>.</p>
<p><a href="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/product-configuration-31.png"><img class="alignnone size-medium wp-image-406" title="product-configuration-3" src="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/product-configuration-31-300x42.png" alt="" width="300" height="42" /></a></p>
<p><a href="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/product-configuration-4.png"><img class="alignnone size-medium wp-image-407" title="product-configuration-4" src="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/product-configuration-4-300x168.png" alt="" width="300" height="168" /></a></p>
<h3>Setting up the build files</h3>
<p>From our workspace location, we can now generate a parent pom.xml together with a pom-file for the plug-in project we just created. Fire up your command line and generate the pom-files.</p>
<pre class="brush:[bash]">mvn3 org.sonatype.tycho:maven-tycho-plugin:generate-poms -DgroupId=se.mattiasholmqvist -Dtycho.targetPlatform=/Users/mattias/dev/eclipse-3.5.2-delta/</pre>
<p>This goal is typically run only once since you don&#8217;t want to replace any changes you&#8217;ve made to the parent pom. I use only the parent pom to add plug-ins to the build. I&#8217;m not sure if that&#8217;s the way to go but it seems like a good idea that the individual plug-in projects has minimum-sized pom files that we don&#8217;t need to change that often.</p>
<blockquote><p>You don&#8217;t actually need to run &lt;code&gt;generate-poms&lt;/code&gt;. This maven goal is only used to bootstrap the build by creating the initial pom files so you don&#8217;t need to create these files yourself initially. If you have a parent project with many plug-in projects this might be quite useful. If you want more control over what&#8217;s happening, just copy &amp; paste the pom.xml files I created (shown below) and modify them to your need.</p></blockquote>
<p>This renders a parent pom.xml that looks something like this:</p>
<pre class="brush:[xml]">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;
  &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
  &lt;groupId&gt;se.mattiasholmqvist&lt;/groupId&gt;
  &lt;artifactId&gt;rcpexample-parent&lt;/artifactId&gt;
  &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
  &lt;packaging&gt;pom&lt;/packaging&gt;
  &lt;build&gt;
    &lt;plugins&gt;
      &lt;plugin&gt;
        &lt;groupId&gt;org.sonatype.tycho&lt;/groupId&gt;
        &lt;artifactId&gt;tycho-maven-plugin&lt;/artifactId&gt;
        &lt;version&gt;0.7.0&lt;/version&gt;
        &lt;extensions&gt;true&lt;/extensions&gt;
      &lt;/plugin&gt;
    &lt;/plugins&gt;
  &lt;/build&gt;
  &lt;modules&gt;
    &lt;module&gt;se.mattiasholmqvist.rcpexample.feature&lt;/module&gt;
    &lt;module&gt;se.mattiasholmqvist.rcpexample.plugin&lt;/module&gt;
  &lt;/modules&gt;
&lt;/project&gt;</pre>
<p>As we can see this does not contain a module for the product project that we created earlier. Tycho cannot understand that our product project defines a product, but that&#8217;s a minor thing. We should add the product project to the parent pom.xml so that the modules section looks like this:</p>
<pre class="brush:[xml]">&lt;modules&gt;
  &lt;module&gt;se.mattiasholmqvist.rcpexample.feature&lt;/module&gt;
  &lt;module&gt;se.mattiasholmqvist.rcpexample.plugin&lt;/module&gt;
  &lt;module&gt;se.mattiasholmqvist.rcpexample&lt;/module&gt;
&lt;/modules&gt;</pre>
<p>We also need to create a pom.xml in the product project that looks like this:</p>
<pre class="brush:[xml]">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;project&gt;
  &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
  &lt;parent&gt;
    &lt;groupId&gt;se.mattiasholmqvist&lt;/groupId&gt;
    &lt;artifactId&gt;rcpexample-parent&lt;/artifactId&gt;
    &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
  &lt;/parent&gt;
  &lt;groupId&gt;se.mattiasholmqvist&lt;/groupId&gt;
  &lt;artifactId&gt;se.mattiasholmqvist.rcpexample&lt;/artifactId&gt;
  &lt;version&gt;1.0.0&lt;/version&gt;
  &lt;packaging&gt;eclipse-application&lt;/packaging&gt;
&lt;/project&gt;</pre>
<p>Note the <strong>eclipse-application</strong> packaging in the pom. This tells Tycho that the project is actually an RCP application and Tycho starts looking for a product definition file during the build.</p>
<h3>Installing the delta pack in the target platform</h3>
<p>To build applications that depend on platform-specific parts of the Eclipse SDK (such as SWT), we need to provide a target platform that contains the Eclipse Delta pack. There are multiple sources on the web that describes how to install the delta pack so look at for example <a href="http://louismrose.wordpress.com/2009/01/23/installing-the-rcp-delta-pack-for-eclipse/" target="_blank">this site</a> or <a href="http://www.google.com" target="_blank">this one</a>.</p>
<h3>Building the product</h3>
<p>We are now ready to build our product.</p>
<pre class="brush:[bash]">mvn3 package -Dtycho.targetPlatform=/Users/mattias/dev/eclipse-3.5.2-delta/</pre>
<p>This should build your product and place an executable application under /target directory in your product project. There are however currently some issues that you might run into depending on your build environment/target platform.</p>
<p><strong>The import org.eclipse.swt.graphics.Point cannot be resolved.</strong></p>
<p>You might run into something like this:</p>
<pre class="brush:[bash]">[ERROR] Failed to execute goal org.sonatype.tycho:maven-osgi-compiler-plugin:0.7.0:compile (default-compile) on project se.mattiasholmqvist.rcpexample.plugin: Compilation failure: Compilation failure:
/Users/mattias/dev/projects/tychoexamples/clean/se.mattiasholmqvist.rcpexample.plugin/src/se/mattiasholmqvist/rcpexample/plugin/ApplicationWorkbenchWindowAdvisor.java (at line 1):[-1,-1]
	package se.mattiasholmqvist.rcpexample.plugin;
	^
The type org.eclipse.swt.graphics.Point cannot be resolved. It is indirectly referenced from required .class files

/Users/mattias/dev/projects/tychoexamples/clean/se.mattiasholmqvist.rcpexample.plugin/src/se/mattiasholmqvist/rcpexample/plugin/ApplicationWorkbenchWindowAdvisor.java (at line 3):[-1,-1]
	import org.eclipse.swt.graphics.Point;
	       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...
...</pre>
<p>This is a problem with Tycho not knowing which native environment to build for. Tycho needs this information to find the correct SWT fragment in the target platform. The expected default behaviour would be that Tycho looks for a fragment that is supported by the system running the build but currently there are some issues with MacOS X (which I use). <em><strong>However, this issue will be fixed in release 0.8.0 of Tycho.</strong></em></p>
<p>So, we need to provide this information to Tycho somehow. In my case, I want to build for MacOS X, Cocoa windowing system and the x86 architecture. We have three options (that I know). We can provide these properties on the command line, in the Maven settings.xml or in the pom.xml directly.</p>
<p>On the command line it looks like this:</p>
<pre class="brush:[bash]">mvn3 package -Dtycho.targetPlatform=/Users/mattias/dev/eclipse-3.5.2-delta/ -Dosgi.os=macosx -Dosgi.ws=cocoa -Dosgi.arch=x86</pre>
<p>In the pom.xml (or the settings.xml for that matter):</p>
<pre class="brush:[xml]">&lt;properties&gt;
  &lt;osgi.os&gt;macosx&lt;/osgi.os&gt;
  &lt;osgi.ws&gt;cocoa&lt;/osgi.ws&gt;
  &lt;osgi.arch&gt;x86&lt;/osgi.arch&gt;
&lt;/properties&gt;
</pre>
<p><strong>Missing target environment</strong><br />
This might also be a problem:<br />
[ERROR] Failed to execute goal org.sonatype.tycho:maven-osgi-packaging-plugin:0.7.0:product-export (default-product-export) on project se.mattiasholmqvist.rcpexample: Product includes native launcher but no target environment was specified -&gt; [Help 1]</p>
<p>Which is due to the fact that the Tycho packaging plugin needs configuration to know which target environment to build the product for. We can solve this by adding the following to the <code>plugins</code> section of the parent pom.xml:</p>
<pre class="brush:[xml]">&lt;plugin&gt;
  &lt;groupId&gt;org.sonatype.tycho&lt;/groupId&gt;
  &lt;artifactId&gt;maven-osgi-packaging-plugin&lt;/artifactId&gt;
  &lt;version&gt;0.7.0&lt;/version&gt;
  &lt;configuration&gt;
    &lt;environments&gt;
      &lt;environment&gt;
        &lt;os&gt;macosx&lt;/os&gt;
        &lt;ws&gt;cocoa&lt;/ws&gt;
        &lt;arch&gt;x86&lt;/arch&gt;
      &lt;/environment&gt;
    &lt;/environments&gt;
  &lt;/configuration&gt;
&lt;/plugin&gt;
</pre>
<h3>We&#8217;re done, let&#8217;s start the application!</h3>
<p>Open the target directory of your product project (in my case se.mattiasholmqvist.rcpexample/target) and you should find an executable RCP application. In my case (since I&#8217;m on a Mac) I found a rcpexample.app in my target directory. Behind this file is this beautifully built, and extremely useful application:</p>
<p><a href="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/hello-rcp.png"><img class="alignnone size-medium wp-image-482" title="hello-rcp" src="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/03/hello-rcp-300x237.png" alt="" width="300" height="237" /></a></p>
<p>That&#8217;s it for building a simple Eclipse RCP app with Tycho. Good luck!</p>
<p>As a reminder, please check out the <a href="http://n2.nabble.com/Tycho-Users-f3053503.html">Tycho users mailing list</a>. Help the people at Sonatype out with feedback on their project.</p>
]]></content:encoded>
			<wfw:commentRss>http://mattiasholmqvist.se/2010/03/building-with-tycho-part-2-rcp-applications/feed/</wfw:commentRss>
		<slash:comments>36</slash:comments>
		</item>
		<item>
		<title>Building with Tycho &#8211; part 1 (OSGi bundles)</title>
		<link>http://mattiasholmqvist.se/2010/02/building-with-tycho-part-1-osgi-bundles/</link>
		<comments>http://mattiasholmqvist.se/2010/02/building-with-tycho-part-1-osgi-bundles/#comments</comments>
		<pubDate>Thu, 11 Feb 2010 10:01:08 +0000</pubDate>
		<dc:creator>Mattias Holmqvist</dc:creator>
				<category><![CDATA[citerus]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[osgi]]></category>
		<category><![CDATA[tycho]]></category>

		<guid isPermaLink="false">http://briljant.joyeurs.com/wordpress/?p=31</guid>
		<description><![CDATA[Maven is as many of us know a good tool for managing dependencies between components. However, when developing OSGi bundles or Eclipse plugins, we typically want to specify our dependencies as imported/exported packages in our Manifest. This has caused trouble for headless building of OSGi bundles for some time although there exist some solutions such [...]]]></description>
			<content:encoded><![CDATA[<p>Maven is as many of us know a good tool for managing dependencies between components. However, when developing OSGi bundles or Eclipse plugins, we typically want to specify our dependencies as imported/exported packages in our Manifest. This has caused trouble for headless building of OSGi bundles for some time although there exist some solutions such as <a href="http://wiki.eclipse.org/index.php/PDEBuild">PDE build</a> and <a href="http://www.aqute.biz/Code/Bnd">BND tool</a>.</p>
<p>The Tycho project provides plugins to Maven which will make it possible (and rather simple) to build OSGi bundles with Maven . There is currently a project overview which provides a good starting point (although some of the documentation is quite outdated). The best source for help is the <a href="http://n2.nabble.com/Tycho-Users-f3053503.html">Tycho users mailing list</a>.</p>
<p>This post will be the first in a series of posts covering building OSGi bundles/Eclipse RCP applications with Tycho.</p>
<p>It is important to remember that Tycho relies on new features of Maven which is only currently available in the 3.0 version of Maven which has not yet been released, but it is possible to try this out by downloading an alpha version of Maven 3.0.</p>
<h3>Environment setup</h3>
<p>I downloaded the alpha-6 from <a href="http://maven.apache.org/download.html">the Maven download site</a>. I also set up my environment to use <code>mvn3</code> instead of <code>mvn</code> for Maven 3 since I didn&#8217;t want to break my Maven 2 installation.</p>
<p>Since Tycho has been pushed to Maven central since version its last couple of revisions (0.5.0 i think), we don&#8217;t need to download anything else or setup any additional Maven repositories.</p>
<h3>Building OSGi bundles</h3>
<p>Fire up Eclipse (I use 3.5.1) and create a new project. Choose plug-in project and choose the target to be Equinox runtime. This creates a simple bundle without any plugin.xml or other Eclipse-specific dependencies.</p>
<p>I also chose to create an Activator to have some code to compile.</p>
<p><a href="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/02/new-bundle-project.png"><img class="alignnone size-thumbnail wp-image-304" title="new-bundle-project" src="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/02/new-bundle-project-150x150.png" alt="" width="150" height="150" /></a></p>
<p>I recommend that you keep your source code in a different directory from the workspace. That&#8217;s my personal preference but it keeps Eclipse IDE from cluttering the source directory too much.</p>
<p>Open up your command line and go to the directory that contains your bundle project. In my case it looks like this:</p>
<p><a href="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/02/source-dir-simplebundle.png"><img class="alignnone size-medium wp-image-194" title="source-dir-simplebundle" src="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/02/source-dir-simplebundle-300x104.png" alt="" width="300" height="104" /></a></p>
<pre class="brush:[bash]">mvn3 org.sonatype.tycho:maven-tycho-plugin:generate-poms -DgroupId=se.mattiasholmqvist -Dtycho.targetPlatform=/Users/mattias/dev/eclipse-3.5.1-delta/</pre>
<p>Tycho is downloaded and it generates a <code>pom.xml</code> for the current directory (parent project) and another <code>pom.xml</code> for the bundle project. It should look something like:</p>
<p><a href="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/02/source-dir-simplebundle-2.png"><img class="alignnone size-medium wp-image-202" title="source-dir-simplebundle-2" src="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/02/source-dir-simplebundle-2-300x167.png" alt="" width="300" height="167" /></a></p>
<p>So, Tycho has generated two poms for us. Let&#8217;s get ready to build our OSGi bundle! Try:</p>
<pre class="brush:[bash]">mvn3 clean install</pre>
<p>and watch the magic!?</p>
<p><a href="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/02/build-resolve-problem.png"><img class="alignnone size-medium wp-image-206" title="build-resolve-problem" src="http://mattiasholmqvist.se/wordpress/wp-content/uploads/2010/02/build-resolve-problem-300x110.png" alt="" width="300" height="110" /></a></p>
<p>What&#8217;s the problem here? Maven tells us that it cannot resolve the project due to a missing OSGi dependency to org.osgi.framework. It considers missing OSGi dependencies as build errors. This means that we must set up a proper target platform for Tycho, and tell it to use that target platform when building. This is required for any proper build environment that builds OSGi bundles.</p>
<p>Currently (version 0.7.0) Tycho supports two different ways of specifying a target platform.</p>
<h3>Building with an explicit target platform</h3>
<p>We can expliticly tell Tycho to use an Eclipse installation using:</p>
<pre class="brush:[bash]">-Dtycho.targetPlatform=/path/to/target</pre>
<p>I downloaded the Eclipse SDK (3.5.1) and untarred it into /Users/mattias/dev/eclipse-3.5.1/. I can now build my simple bundle from the command line with:</p>
<pre class="brush:[bash]">mvn3 clean install -Dtycho.targetPlatform=/Users/mattias/dev/eclipse-3.5.1</pre>
<h3>Using an implicit target platform</h3>
<p>If you don&#8217;t want to keep track of the target platform locally, it is possible to build the OSGi bundle with an implicit target platform. To do this, we need to help Tycho along by specifying that it should try to resolve the dependencies using a resolver. We also need to help Tycho by specifying locations (repositories) where it might find artifacts that matches our needs.</p>
<p>We&#8217;ll start by telling Tycho that it should use a p2 resolver (we&#8217;ll use Equinox from Eclipse.org as our target platform). We&#8217;ll add the following to the build section <code>pom.xml</code> for our parent project:</p>
<pre class="brush:[xml]"> &lt;plugin&gt;
  &lt;groupid&gt;org.sonatype.tycho&lt;/groupid&gt;
  &lt;artifactid&gt;target-platform-configuration&lt;/artifactid&gt;
  &lt;version&gt;${tycho-version}&lt;/version&gt;
  &lt;configuration&gt;
    &lt;resolver&gt;p2&lt;/resolver&gt;
  &lt;/configuration&gt;
&lt;/plugin&gt;
</pre>
<p>This tells Tycho to use an implicit resolver that supports p2 repositories. We are now one step from being able to build with an implicit target platform.</p>
<p>The <code>${tycho.version}</code> is a Maven property that I use to switch between versions of Tycho. This is set to 0.7.0 in my case. If you want to use just this version, replace the property with the version literals. The version of this plugin should be the same as for the <code>tycho-maven-plugin</code> entry that was auto-generated to the pom.xml from the <code>generate-poms</code> target used earlier.</p>
<p>We need to setup the repositories that Tycho should use at build time. This is accomplished by normal repository configuration Maven-style. Tycho enhances these configuration options by supporting p2 repositories as well. Open your settings configuration (in my case <code>~/.m2/settings.xml</code>) and add the following:</p>
<pre class="brush:[xml]">&lt;settings&gt;
  &lt;profiles&gt;
    &lt;profile&gt;
      &lt;id&gt;tycho&lt;/id&gt;
      &lt;repositories&gt;
        &lt;repository&gt;
		  &lt;id&gt;galileo&lt;/id&gt;
		  &lt;layout&gt;p2&lt;/layout&gt;
		  &lt;url&gt;http://download.eclipse.org/releases/galileo/&lt;/url&gt;
        &lt;/repository&gt;
      &lt;/repositories&gt;
    &lt;/profile&gt;
  &lt;/profiles&gt;
&lt;/settings&gt;
</pre>
<p>It is now possible to build the simple bundle project by using:</p>
<pre class="brush:[bash]">mvn3 clean install</pre>
<p>That&#8217;s it for now. Hope this helps with your headless OSGi builds! Keep your eyes open for the next part in this series of posts.</p>
<p>Some interesting links:</p>
<ul>
<li><a href="http://n2.nabble.com/Tycho-Users-f3053503.html">Tycho Users mailing list</a></li>
<li><a href="http://wiki.eclipse.org/Equinox_p2_Getting_Started">Getting started with p2</a></li>
<li><a href="http://github.com/sonatype/sonatype-tycho/">Sonatype&#8217;s Tycho GitHub repository</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://mattiasholmqvist.se/2010/02/building-with-tycho-part-1-osgi-bundles/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
		</item>
		<item>
		<title>Integral calculation (with Simpson&#8217;s method) in Clojure</title>
		<link>http://mattiasholmqvist.se/2009/10/integral-calculation-in-clojure/</link>
		<comments>http://mattiasholmqvist.se/2009/10/integral-calculation-in-clojure/#comments</comments>
		<pubDate>Tue, 27 Oct 2009 01:27:34 +0000</pubDate>
		<dc:creator>Mattias Holmqvist</dc:creator>
				<category><![CDATA[citerus]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[functional]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://briljant.joyeurs.com/wordpress/?p=50</guid>
		<description><![CDATA[Inspired by the latest renaissance of functional programming, I decided to take on some real-world examples of calculations using Clojure. This is an exercise from the book Structure and Interpretation of Computer Programs. There is a method for numeric integration called Simpson&#8217;s rule which can be used to approximate the integral of a given function [...]]]></description>
			<content:encoded><![CDATA[<p>Inspired by the latest renaissance of functional programming, I decided to take on some real-world examples of calculations using Clojure. This is an exercise from the book <a href="http://www.amazon.co.uk/Structure-Interpretation-Computer-Electrical-Engineering/dp/0262510871/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1256604271&amp;sr=8-1">Structure and Interpretation of Computer Programs</a>.</p>
<p>There is a method for numeric integration called <a href="http://en.wikipedia.org/wiki/Simpson%27s_rule">Simpson&#8217;s rule</a> which can be used to approximate the integral of a given function <img src='http://s.wordpress.com/latex.php?latex=f%28x%29%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f(x) ' title='f(x) ' class='latex' /> in some interval <img src='http://s.wordpress.com/latex.php?latex=%5Cleft%5Ba%2Cb%5Cright%5D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\left[a,b\right]' title='\left[a,b\right]' class='latex' />. I decided to try some Clojure on this.</p>
<p>The rule states that this approximation can be found by calculating:</p>
<img src='http://s.wordpress.com/latex.php?latex=%5Cint_%7Ba%7D%5E%7Bb%7D%20%5Capprox%20%5Cfrac%7Bh%7D%7B3%7D%20%5Cleft%5B%20%20f%28x_%7B0%7D%29%20%2B%204f%28x_%7B1%7D%29%20%2B%202f%28x_%7B2%7D%29%20%2B%204f%28x_%7B3%7D%29%20%2B%202f%28x_%7B4%7D%29%20%5Cldots%20%2B%202f%28x_%7Bn-2%7D%29%20%2B%204%20f%28x_%7Bn-1%7D%29%20%2B%20f%28x_%7Bn%7D%29%20%5Cright%5D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\int_{a}^{b} \approx \frac{h}{3} \left[  f(x_{0}) + 4f(x_{1}) + 2f(x_{2}) + 4f(x_{3}) + 2f(x_{4}) \ldots + 2f(x_{n-2}) + 4 f(x_{n-1}) + f(x_{n}) \right]' title='\int_{a}^{b} \approx \frac{h}{3} \left[  f(x_{0}) + 4f(x_{1}) + 2f(x_{2}) + 4f(x_{3}) + 2f(x_{4}) \ldots + 2f(x_{n-2}) + 4 f(x_{n-1}) + f(x_{n}) \right]' class='latex' />
<p>where <img src='http://s.wordpress.com/latex.php?latex=h%20%3D%20%5Cfrac%7B%28b-a%29%7D%7Bn%7D%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='h = \frac{(b-a)}{n} ' title='h = \frac{(b-a)}{n} ' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=y_%7Bk%7D%20%3D%20f%28a%20%2B%20kh%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y_{k} = f(a + kh)' title='y_{k} = f(a + kh)' class='latex' />.</p>
<p>First off, we can make simplify the problem a bit. We can break out the first and last element in the series (by calculating <img src='http://s.wordpress.com/latex.php?latex=x&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='x' title='x' class='latex' /> for the 0&#8242;th and n&#8217;th index) and also realize that the odd and even elements in the series have common factors. This yields:</p>
<img src='http://s.wordpress.com/latex.php?latex=%5Cint_a%5Eb%20%5Capprox%20%5Cfrac%7Bh%7D%7B3%7D%20%5Cleft%5B%20%20f%28a%29%20%2B%20f%28b%29%20%2B%202%5Csum_%7Bj%3D1%7D%5E%7Bn%2F2%20-1%7Df%28x_%7B2j%7D%29%20%2B%204%5Csum_%7Bj%3D1%7D%5E%7Bn%2F2%7Df%28x_%7B2j-1%7D%29%20%5Cright%5D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\int_a^b \approx \frac{h}{3} \left[  f(a) + f(b) + 2\sum_{j=1}^{n/2 -1}f(x_{2j}) + 4\sum_{j=1}^{n/2}f(x_{2j-1}) \right]' title='\int_a^b \approx \frac{h}{3} \left[  f(a) + f(b) + 2\sum_{j=1}^{n/2 -1}f(x_{2j}) + 4\sum_{j=1}^{n/2}f(x_{2j-1}) \right]' class='latex' />
<p>If we break this down into separate problems, we realize that we first need to find the indices for the first and second series, respectively. Once we have found the indices, we can apply the function <img src='http://s.wordpress.com/latex.php?latex=f&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f' title='f' class='latex' /> to the value of <img src='http://s.wordpress.com/latex.php?latex=x&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='x' title='x' class='latex' /> for each index.</p>
<p>Finding the indices turns out to be quite simple. We can generate a complete sequence (1-n) and then filter out all interesting values and return that sequence. The <code>range</code> function generates a sequence and the <code>filter</code> function filters the sequence and returns all values that satisfies a supplied predicate function. Luckily for us, Clojure provides the predicate functions <code>odd?</code> and <code>even?</code>, which answers to whether or not numbers are odd or even. As an example from the REPL:</p>
<pre class="brush:[clojure]">(filter odd? (range 1 10))
(1 3 5 7 9)
</pre>
<p>We can use this method in the function <code>sub-series</code> which will be responsible for generating our sums:</p>
<pre class="brush:[clojure]">(defn sub-series [n index-filter]
  (map #(f (+ a (* h %))) (filter index-filter (range 1 n))))
</pre>
<p>The <code>sub-series</code> function takes as arguments the function <img src='http://s.wordpress.com/latex.php?latex=f&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f' title='f' class='latex' /> for which we&#8217;re approximating the integral, the start of the integration interval <img src='http://s.wordpress.com/latex.php?latex=a&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='a' title='a' class='latex' />, the granularity of the integral <img src='http://s.wordpress.com/latex.php?latex=n&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='n' title='n' class='latex' />, the <img src='http://s.wordpress.com/latex.php?latex=h&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='h' title='h' class='latex' /> value as defined in the problem statement and the predicate function which is used to determine which indices to include in the series.</p>
<p>This function will apply the <img src='http://s.wordpress.com/latex.php?latex=f&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f' title='f' class='latex' /> function for each value in the series (from 1-n) that is satisfied by the given predicate function. Once the function has been applied to all those values, it will return the calculated values as a sequence.</p>
<pre class="brush:[clojure]">(defn sub-series [f a h n index-filter]
  (map #(f (+ a (* h %))) (filter index-filter (range 1 n))))</pre>
<p>I&#8217;m using a few Clojure API functions (<code>map</code> and <code>filter</code>) but I will not explain these further here. For more info about these functions, see the <a href="http://clojure.org/api">Clojure API</a>.</p>
<p>Since the first series we want to generate only include even indexes, we pass the <code>even?</code> predicate function to our <code>sub-series</code> function. For the second series we pass the <code>odd?</code> predicate function. We also multiply all values in each sequence with the proper factor (2 and 4, respectively). We use <code>reduce</code> to add together all values in the generated sequences. As a final step we also add <img src='http://s.wordpress.com/latex.php?latex=f%28a%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f(a)' title='f(a)' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=f%28b%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f(b)' title='f(b)' class='latex' /> and multiply the whole sum with <img src='http://s.wordpress.com/latex.php?latex=%5Cfrac%7Bh%7D%7B3%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\frac{h}{3}' title='\frac{h}{3}' class='latex' />:</p>
<pre class="brush:[clojure]">(defn simpson [f a b n]
  (def h (/ (- b a ) n))
  (* (/ h 3) (+
    (reduce + (map #(* % 2) (sub-series f a h n even?)))
    (reduce + (map #(* % 4) (sub-series f a h n odd?)))
    (f a)
    (f b))))</pre>
<p>Phew. Let&#8217;s try this out. First let&#8217;s try it on a simple function such as <img src='http://s.wordpress.com/latex.php?latex=f%28x%29%20%3D%20x&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f(x) = x' title='f(x) = x' class='latex' />. We can use the <code>identity</code> function from the Clojure API for this:</p>
<pre class="brush:[clojure]">(simpson identity 0.0 1.0 100)
0.5
</pre>
<p>So far so good&#8230;</p>
<p>Second, we&#8217;ll try a more sophisticated polynomial function, <img src='http://s.wordpress.com/latex.php?latex=f%28x%29%20%3D%207x%20-%208.5x%5E2%20%2B%203x%5E3&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f(x) = 7x - 8.5x^2 + 3x^3' title='f(x) = 7x - 8.5x^2 + 3x^3' class='latex' />. We&#8217;ll define the polynomial:</p>
<pre class="brush:[clojure]">(defn poly [x]
  (- (+ (* 7 x) (* 3 (cube x))) (* 8.5 (square x))))
</pre>
<p>And approximate the integral in <img src='http://s.wordpress.com/latex.php?latex=%5B0%2C2%5D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='[0,2]' title='[0,2]' class='latex' />:</p>
<pre class="brush:[clojure]">(simpson poly 0.0 2.0 100)
3.3333333333333335
</pre>
<p>which is correct.</p>
<p>To clean the whole thing up I&#8217;ll letting the <code>sub-series</code> function be a local function. This yields the final version of our Simpson-approximation:</p>
<pre class="brush:[clojure]">(defn simpson [f a b n]
  (let [h (/ (- b a ) n)]
  (letfn [
      (sub-series [index-filter]
        (map #(f (+ a (* h %))) (filter index-filter (range 1 n))))]
    (* (/ h 3) (+
    (reduce + (map #(* % 2) (sub-series even?)))
    (reduce + (map #(* % 4) (sub-series odd?)))
    (f a)
    (f b))))))
</pre>
<p>I think the end result of 10 LOC is quite neat. The rich API with <code>filter</code>, <code>map</code>, <code>reduce</code> etc is really fun to work with.</p>
<p>If you ever need to make an integral calculation, you can just paste this code and you have your area!</p>
<h4>Simplified solution</h4>
<p>As pointed out by Chris B, we don&#8217;t need to use <code>map</code> in this case, since we only multiply the sub-series values with constants (2 and 4, respectively) we can simply multiply the reduced sub-series with these values. If the sub-series values should be multiplied with a function that depends on the current value in the sub-series, <code>map</code> would be a good approach. This simplifies the solution a bit:</p>
<pre class="brush:[clojure]">(defn simpson [f a b n]
  (let [h (/ (- b a ) n)]
  (letfn [
      (sub-series [index-filter]
        (map #(f (+ a (* h %))) (filter index-filter (range 1 n))))]
    (* (/ h 3) (+
    (* 2 (reduce + (sub-series even?)))
    (* 4 (reduce + (sub-series odd?)))
    (f a)
    (f b))))))
</pre>
]]></content:encoded>
			<wfw:commentRss>http://mattiasholmqvist.se/2009/10/integral-calculation-in-clojure/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Fixed-point calculations (and square roots) in Clojure</title>
		<link>http://mattiasholmqvist.se/2009/10/fixed-point-calculations-and-square-roots-in-clojure/</link>
		<comments>http://mattiasholmqvist.se/2009/10/fixed-point-calculations-and-square-roots-in-clojure/#comments</comments>
		<pubDate>Sun, 25 Oct 2009 23:21:32 +0000</pubDate>
		<dc:creator>Mattias Holmqvist</dc:creator>
				<category><![CDATA[citerus]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[functional]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://briljant.joyeurs.com/wordpress/?p=3</guid>
		<description><![CDATA[I&#8217;m currently reading &#8220;The interpretation and structure of computer programs&#8221;, (which by the way is a really joyful read) and I felt an urge to try the examples in a more &#8220;modern&#8221; language than Lisp. Clojure seemed like a nice fit since it is a Lisp and also runs on the JVM which makes the [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m currently reading <a href="http://www.amazon.co.uk/gp/product/0262011530/ref=s9_sima_gw_s0_p14_i1?pf_rd_m=A3P5ROKL5A1OLE&amp;pf_rd_s=center-2&amp;pf_rd_r=15WVN9HA03E1NJC98ATW&amp;pf_rd_t=101&amp;pf_rd_p=467128533&amp;pf_rd_i=468294">&#8220;The interpretation and structure of computer programs&#8221;</a>, (which by the way is a really joyful read) and I felt an urge to try the examples in a more &#8220;modern&#8221; language than Lisp.</p>
<p>Clojure seemed like a nice fit since it is a Lisp and also runs on the JVM which makes the learning curve slightly less steep (for me atleast).</p>
<h2>Square root calculation using Newton&#8217;s method</h2>
<p>One of the examples in the book covers Newton&#8217;s method for calculating the square root of a number. The idea is that if we pick a guess for the square root, we&#8217;ll get a better guess by dividing our initial guess with the square rooted number. That is, if  <img src='http://s.wordpress.com/latex.php?latex=y%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y ' title='y ' class='latex' /> is a guess for the square root and <img src='http://s.wordpress.com/latex.php?latex=x%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='x ' title='x ' class='latex' /> is the number for which we&#8217;re calculating the square root, we can find:</p>
<img src='http://s.wordpress.com/latex.php?latex=y_%7Bimproved%7D%20%3D%20%5Cfrac%7Bx%7D%7By%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y_{improved} = \frac{x}{y}' title='y_{improved} = \frac{x}{y}' class='latex' />
<p>Averaging this fraction with the guess helps with the convergence of the algorithm and is needed for Newton&#8217;s method to converge. The theory behind this is beyond me, but simple calculations can show that this average is actually the same as the original fraction and only affects the algorithm convergence behavior. This method can then be applied iteratively by using the answer as input to the next iteration. So we&#8217;ll use this instead:</p>
<img src='http://s.wordpress.com/latex.php?latex=y_%7Bimproved%7D%20%3D%20%5Cfrac%7B%28y%20%2B%20%5Cfrac%7Bx%7D%7By%7D%29%7D%7B2%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y_{improved} = \frac{(y + \frac{x}{y})}{2}' title='y_{improved} = \frac{(y + \frac{x}{y})}{2}' class='latex' />
<p>Enough mumbling about stuff I don&#8217;t know that much about and let&#8217;s write some code!</p>
<p>I first define the <code>square</code>, <code>average</code> and <code>abs</code> help functions.</p>
<pre class="brush:[clojure]">(defn square [x]
  (* x x))
(defn average [x y]
  (/ (+ x y) 2))
(defn abs [x]
  (if (&lt; x 0)
    (- x)
    x))
</pre>
<p>We also need a stop criteria to be able to tell when we&#8217;ve found a good enough guess. For that, we&#8217;ll use our good-enough? predicate function. This function checks that the difference between the squared guess and the value we&#8217;re computing the square, is within our tolerance level. This will mean that we have found an acceptably good guess.</p>
<pre class="brush:[clojure]">
(defn good-enough? [guess x tolerance]
  (&lt; (abs (- (square guess) x))
     tolerance))</pre>
<p>Now, we can use a help function to iterate to a good enough guess. The <code>next-guess</code> function is responsible for calculating our next guess, given the previous guess and squared number as arguments. <code>sqrt-iter</code> is an recursive function that stops when the stop criteria (good-enough?)  is satisfied. The <code>sqrt</code> function initiates the calculations and provides the recursive <code>sqrt-iter</code> with an initial guess.</p>
<pre class="brush:[clojure]">(defn next-guess [guess x] (average guess (/ x guess)))

(defn sqrt-iter [guess x tolerance]
  (if (good-enough? guess x tolerance) guess
    (sqrt-iter (next-guess guess x) x tolerance)))

(defn sqrt [x initial-guess tolerance]
  (sqrt-iter initial-guess x tolerance))</pre>
<p>We can now make approximate calculations of the square root of a number for a specific tolerance. For example, the square root of 2 with the tolerance 0.0001 can be calculated with:</p>
<pre class="brush:[clojure]">(sqrt 2.0 1.0 0.0001)
=&gt; 1.4142156862745097</pre>
<p>I&#8217;m using 1.0 as the initial guess which I thought was reasonably good. This is all nice and dandy, but it doesn&#8217;t really show any huge advantages from using a non-functional programming language such as Java. Implementing this solution in Java is left as an exercise.</p>
<h2>Refactoring to fixed-point</h2>
<p>The power of functional programming and Clojure comes into play when we can find a generic pattern for many problems and use functions as first-order citizens. In this case, it turns out that the Newton approximation is a special case of a <a href="http://en.wikipedia.org/wiki/Fixed_point_(mathematics)">fixed-point</a> calculation. We can refactor the solution by breaking out the responsibility of finding a fixed-point for a function into a separate function:</p>
<pre class="brush:[clojure]">
(defn fixed-point [func first-guess tolerance]
  (letfn [
    (good-enough? [first second tolerance]
      (< (abs (- first second)) tolerance))
    (eval-guess [guess]
      (let [next-guess (func guess)]
        (if (good-enough? guess next-guess tolerance)
          guess
          (eval-guess next-guess))))]
  (eval-guess first-guess)))
</pre>
<p>The <code>fixed-point</code> function takes a function as its first argument. The <code>fixed-point</code> function will evaluate the given function with the current guess. The result of this evaluation is used to determine if the function has converged to within the tolerance level. If so, the current guess will be returned, else the <code>fixed-point</code> will continue with the new guess as input. This means that we must provide a function that converge under these conditions (fixed-point). As we've seen, Newton's method includes such a function for calculating the square root of a number (the <img src='http://s.wordpress.com/latex.php?latex=y_%7Bimproved%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y_{improved}' title='y_{improved}' class='latex' /> shown earlier). The <code>fixed-point</code> function also has a local function <code>good-enough?</code> that checks if the current guess is within our tolerance level (same as good-enough? in the previous solution).</p>
<p>I've used some more Clojure API support here, such as <code>letfn</code> and <code>let</code>, which let's me define local functions and variables. It makes the code a bit more concise and we don't get access to the local functions from outside the <code>fixed-point</code> function. Check out the <a href="http://clojure.org/">Clojure API</a> for more details on this.</p>
<p>We can now wrap up the refactoring with the following small function that uses the generic <code>fixed-point</code> to calculate the square root:</p>
<pre class="brush:[clojure]">(defn sqrt [x tolerance]
  (fixed-point #(average % (/ x %)) 1.0 tolerance))</pre>
<p>Here I'm using the <code>#</code> symbol, which is a short-hand notation for an anonymous function. The <code>%</code> within the function represents the first argument to the function. This means I'm actually passing an implementation of <img src='http://s.wordpress.com/latex.php?latex=y_%7Bimproved%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y_{improved}' title='y_{improved}' class='latex' /> to the <code>fixed-point</code> function.</p>
<p>To clean this up a little bit more I'm breaking out the responsibility of average damping in a separate function:</p>
<pre class="brush:[clojure]">(defn average-damp [func]
  #(average % (func %)))</pre>
<p>The average-damp function applies the average damping to the provided function and returns a new function that is calculated with applied damping. This means that we can write our square root calculation function as:</p>
<pre class="brush:[clojure]">(defn sqrt [x tolerance]
  (fixed-point (average-damp #(/ x %)) 1.0 tolerance))
</pre>
<p>We also get another payoff. We can now reuse the fixed-point method for approximating fixed points of other functions as well. For example, the <a href="http://en.wikipedia.org/wiki/Golden_ratio">golden ratio</a> is a value <img src='http://s.wordpress.com/latex.php?latex=x&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='x' title='x' class='latex' /> that satisfies:</p>
<img src='http://s.wordpress.com/latex.php?latex=x%5E2%20%3D%20x%20%2B1&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='x^2 = x +1' title='x^2 = x +1' class='latex' />
<p>To calculate this using our fixed-point function we need to reduce it to the form:</p>
<p><img src='http://s.wordpress.com/latex.php?latex=x%20%3D%201%20%2B%20%5Cfrac%7B1%7D%7Bx%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='x = 1 + \frac{1}{x}' title='x = 1 + \frac{1}{x}' class='latex' />.</p>
<p>We can pass this reduced form to our fixed-point function:</p>
<pre class="brush:[clojure]">(defn golden [tolerance]
  (fixed-point (average-damp #(+ 1 (/ 1 %))) 1.0 tolerance))</pre>
<p>To approximate the golden ratio, we can now call our golden method and pass a reasonable tolerance level (0.0001 in this case):</p>
<pre class="brush:[clojure]">(golden 0.0001)
=&gt; 1.6179380934832117</pre>
<p>It turns out that this algorithm actually does not need the average-damping to converge. Since we have separated the function for finding the fixed-point from that of average-damping we can try:</p>
<pre class="brush:[clojure]">(defn golden [tolerance]
  (fixed-point #(+ 1 (/ 1 %)) 1.0 tolerance))</pre>
<p>Which yields the same results as the average-damped version:</p>
<pre class="brush:[clojure]">(golden 0.0001)
=&gt; 1.6179380934832117</pre>
<p>Hopefully this post shows some examples on how you can use higher-order functions to modularize responsibilities. The original examples (in Scheme) in this post are available in the <a href="http://www.amazon.co.uk/gp/product/0262011530/ref=s9_sima_gw_s0_p14_i1?pf_rd_m=A3P5ROKL5A1OLE&amp;pf_rd_s=center-2&amp;pf_rd_r=15WVN9HA03E1NJC98ATW&amp;pf_rd_t=101&amp;pf_rd_p=467128533&amp;pf_rd_i=468294">book</a> and credit for this should go to Abelson, Sussman and Sussman. The book is also released under <a href="http://creativecommons.org/licenses/by-nc/3.0/">Creative Commons Unported licence 3.0</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://mattiasholmqvist.se/2009/10/fixed-point-calculations-and-square-roots-in-clojure/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

