<?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>Code Affine</title>
	<atom:link href="http://www.codeaffine.com/category/eclipse/feed/?author_name=fappel" rel="self" type="application/rss+xml" />
	<link>http://www.codeaffine.com</link>
	<description>Clean code that works</description>
	<lastBuildDate>Wed, 10 Apr 2013 07:53:21 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4.2</generator>
		<item>
		<title>Working Efficiently with JUnit in Eclipse</title>
		<link>http://www.codeaffine.com/2012/11/26/working-efficiently-with-junit-in-eclipse-2/</link>
		<comments>http://www.codeaffine.com/2012/11/26/working-efficiently-with-junit-in-eclipse-2/#comments</comments>
		<pubDate>Mon, 26 Nov 2012 08:10:57 +0000</pubDate>
		<dc:creator>Frank Appel</dc:creator>
				<category><![CDATA[Eclipse]]></category>

		<guid isPermaLink="false">http://www.codeaffine.com/?p=2439</guid>
		<description><![CDATA[Recently I was dragged into a discussion1 with some test infected2 fellows about how we use JUnit within the Eclipse IDE. Surprisingly the conversation brought up some &#8216;tips and tricks&#8217; not everybody was aware of. This gave me the idea to write this post doing a sum up of our talk. Who knows &#8211; maybe [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I was dragged into a discussion<sup class='footnote'><a href='#fn-2439-1' id='fnref-2439-1'>1</a></sup> with some test infected<sup class='footnote'><a href='#fn-2439-2' id='fnref-2439-2'>2</a></sup> fellows about how we use <a href="http://junit.org/" title="JUnit" target="_blank">JUnit</a> within the <a href="http://eclipse.org/" title="Eclipse" target="_blank">Eclipse IDE</a>. Surprisingly the conversation brought up some &#8216;tips and tricks&#8217; not everybody was aware of. This gave me the idea to write this post doing a sum up of our talk. Who knows &#8211; maybe there is something new for somebody out there too&#8230;</p>
<p><strong>Launch Shortcuts</strong></p>
<p>If you are doing <a href="http://en.wikipedia.org/wiki/Test-driven_development" title="Test Driven Development" target="_blank">Test Driven Development</a> you have to run your tests quite often. Obviously it gets somewhat tedious using e.g. the context menu of the editor to select the <code><em>Run As -> JUnit Test</em></code> to launch a test case under development. Fortunately the shortcut <code><em>Alt+Shift+X,T </em></code> does the same and <code><em>Alt+Shift+D,T </em></code> executes the test in debug mode. But there is more in that than meets the eye.</p>
<p>Consider the following situation: a unit under test does not work as expected anymore. You have recognized this because a certain test of your test suite fails. Having a look at the code might not be conclusive so you decide to start a debugging session. To do so you set a breakpoint at the current cursor position (<code><em>Ctrl+Shift+B</em></code>). In such a case you are probably not interested in re-running the suite or even all the tests of the given test class. You only want to launch the single failing test<sup class='footnote'><a href='#fn-2439-3' id='fnref-2439-3'>3</a></sup>. </p>
<p><img src="http://www.codeaffine.com/wp-content/uploads/2012/11/shortcut-on-selection2.png" alt="" title="Shortcut on Selection" width="586" height="139" class="size-full wp-image-2516" /></p>
<p>Now it is important to know that the &#8216;Run as&#8217; shortcuts described above are sensitive to the editor&#8217;s cursor position. Moving the cursor to a test method name allows to use those shortcuts to launch a JUnit process that runs this test method only<sup class='footnote'><a href='#fn-2439-4' id='fnref-2439-4'>4</a></sup><sup class='footnote'><a href='#fn-2439-5' id='fnref-2439-5'>5</a></sup>.</p>
<p>Carrying on the example a little bit it is very likely that you will find a suspicious spot in your unit under test during the debugging session. Considering a solution you might change some code of that unit. After that you want to see if the test method still fails. Luckily there is another shortcut in Eclipse that allows you to re-run the latest executed launch configuration.</p>
<p>Use <code><em>F11</em></code> to re-run your debug session and <code><em>Ctrl-F11</em></code> to re-run the test method normally. However there is a preference setting that have to be set to make this work reliable. After opening the <em>Launching</em> preference page (Windows -> Preferences | Run/Debug -> Launching) there is a section called  <em>Launch Operation</em>. Ensure that the <em>Always launch the previously launched application</em> radio button is selected.</p>
<p><strong>Method Templates</strong></p>
<p>Every time you are about to create a new test method you might consider using Eclipse editor templates to improve your coding efficiency. Once you have positioned the cursor at the location where the new test method should be located type <code><em>test</em></code> and hit the <code><em>Ctrl+Space</em></code> shortcut to pop up the content assist.</p>
<p><img src="http://www.codeaffine.com/wp-content/uploads/2012/11/test-editor-template.png" alt="" title="Standard JUnit Test Templates" width="500" height="101" class="size-full wp-image-2519" /></p>
<p>As shown in the first part of the picture above the content assist offers a test method template that will create a complete method stub on selection. Unfortunately this would be a JUnit 3 style method stub. But hitting <code><em>Ctrl+Space</em></code> again will reveal a second template that is written in JUnit 4 style. This is shown in the second part of the picture above.</p>
<p>In spite of all hitting the shortcut twice still seems to be too cumbersome for many developers. And writing test cases you often have to create setup and/or teardown methods annotated with the @Before/@After tag as well. But thankfully it is possible to provide your own editor templates in Eclipse. <a href="http://eclipsesource.com/blogs/author/hstaudacher/" title="Holger Staudacher" target="_blank">Holger Staudacher</a> has written a good post called <a href="http://eclipsesource.com/blogs/2012/03/20/simple-junit4-templates-for-eclipse/" title="Simple JUnit4 templates for Eclipse" target="_blank">Simple JUnit4 templates for Eclipse</a> where he explains how to do this and even provides a <a href="https://gist.github.com/2134193" title="JUnit 4 Method Templates" target="_blank">set of templates in a gist</a>.</p>
<p><strong>Favorites</strong></p>
<p>JUnit tests rely heavily on the usage of the various <code>assertXXX</code> methods provided by the class <code>junit.framework.Assert</code>. Those methods are all declared as static and can be referred to as <code>Assert.assertTrue(condition)</code> for example. But as far as I know most people would use <a href="http://en.wikipedia.org/wiki/Static_import" title="Static Imports in Java" target="_blank">static imports</a> to shorten the statement for the sake of readability to <code>assertTrue(condition)</code>.</p>
<p>But by default the IDE&#8217;s content assist will not suggest the static methods of the <code>Assert</code> class. One way to get around this is to write the class name and let the content assist propose the available methods. The latter might be accelerated by using camel case matching. After that the use of <code><em>Ctrl+Shift+M</em></code> as described in Rüdiger&#8217;s <a href="http://www.codeaffine.com/2012/03/28/how-do-you-import-static-in-eclipse/" title="How do you import static in Eclipse?" target="_blank">post about static import</a> shortens the statement and generates the import.</p>
<p>However I think the most efficient way is to configure the <code>junit.framework.Assert</code> class as <em>content assist favorite</em> to allow the proposal of the static members even if the import is still missing. The configuration takes place in (window -> Preferences | Java -> Editor -> Content Assist -> Favorites) and looks like this:</p>
<p><img src="http://www.codeaffine.com/wp-content/uploads/2012/11/favorites.png" alt="" title="favorites" width="664" height="163" class="size-full wp-image-2577" /></p>
<p><strong>JUnit View Configuration</strong></p>
<p>While working test driven running your tests regularly gets practically organic <sup class='footnote'><a href='#fn-2439-6' id='fnref-2439-6'>6</a></sup>. However running a larger test suite takes some time. In the meanwhile the JUnit View pops up and continously updates the list of test results. But this can get enervating as it is distracting in the best &#8211; or even obstructing your work in the worst case.</p>
<p>With test driven development you expect your tests to succeed at a rate of 100%. And because of this many developers want to be informed about failing tests only &#8211; the exception of the rule. The JUnit view supports this with a configuration setting called <code><em>Activate on Error/Failure Only</em></code> available via the viewpart&#8217;s menu:</p>
<p><img src="http://www.codeaffine.com/wp-content/uploads/2012/11/on-problem-only-activation.png" alt="" title="On Problem Only Activation" width="474" height="168" class="size-full wp-image-2535" /></p>
<p>Every now and then your test suite will fail and there may be more than one problem at once. By default the JUnit view lists <em>all</em> test results. But as a developer you&#8217;re generally more interested in the <em>failing</em> ones and may percive the bulk of green tests as clutter. Here focus on your work means focus on the failing tests. There is a configuration setting called <code><em>Show Failures Only</em></code> available to change this behaviour. As people tend to change this setting more frequently a toggle button in the viewpart&#8217;s toolbar is provided.</p>
<p><img src="http://www.codeaffine.com/wp-content/uploads/2012/11/show-failures-only.png" alt="" title="Show Failures Only" width="474" height="168" class="size-full wp-image-2538" /></p>
<p><strong>Fast View</strong></p>
<p>If your are working with <a href="http://download.eclipse.org/eclipse/downloads/drops/R-3.8-201206081200/" title="Eclipse 3.8 Download" target="_blank">Eclipse 3.x</a> there is a nice feature called <code><em>Fast View</em></code> that allows to unclutter your UI a bit. In general I prefer this for views that I use regularly but not continously and/or for views that I consider more lucid if provided with more space. Examples for this might be the Coverage-, History- or the Call Hierarchy view. A viewpart tab provides a content menu that makes it possible to use a view as fast view:</p>
<p><img src="http://www.codeaffine.com/wp-content/uploads/2012/11/fast-view1.png" alt="" title="Fast View Selection" width="500" height="79" class="size-full wp-image-2543" /></p>
<p>This removes the view from its stack and shows a toggle button in the fast view toolbar at the left bottom corner of your workbench. With this button you can activate/deactivate a particular view as overlay<sup class='footnote'><a href='#fn-2439-7' id='fnref-2439-7'>7</a></sup>:</p>
<p><img src="http://www.codeaffine.com/wp-content/uploads/2012/11/fast-view-overlay.png" alt="" title="Fast View Overlay" width="632" height="415" class="size-full wp-image-2546" /></p>
<p>A specific feature of the JUnit fast view button is that it provides status info about the latest test run or progress info about a currently executed one. So this little button is all the UI you need for a good deal of the time you spent with JUnit:</p>
<p><img src="http://www.codeaffine.com/wp-content/uploads/2012/11/junit-view-status-icon1.png" alt="" title="JUnit Status Icon" width="112" height="32" class="size-full wp-image-2557" /></p>
<p>Unfortunately fast views are no longer available in Eclipse 4.x. But there is a workaround that meets the behavior to a certain degree. You can move the views you want to use as &#8216;fast views&#8217; into a designated view stack and minimize this stack. The toolbar representing the minimized view stack now serves as the former fast view bar. This works so-so as the activation/deactivation sometimes hangs and you have to fiddle a bit to hide the view and get back to the editor for example.</p>
<p>In essence I think the sections above are covering the main points we were talking about in the disscussion I mentioned at the beginning of this post. Maybe you also have some infos about useful JUnit shortcuts, using patterns or the like to share &#8211; feel welcome to add a comment.</p>
<p />
<hr />
<div class='footnotes'>
<div class='footnotedivider'></div>
<ol>
<li id='fn-2439-1'>The discussion happened during one of those spontaneous couple-of-beers-after-work-sessions we like to have once in a while&#8230; <span class='footnotereverse'><a href='#fnref-2439-1'>&#8617;</a></span></li>
<li id='fn-2439-2'>It is said that the term &#8216;test infected&#8217; was originally coined by <a href="http://en.wikipedia.org/wiki/Erich_Gamma" title="Erich Gamma" target="_blank">Erich Gamma</a>. Together with <a href="http://en.wikipedia.org/wiki/Kent_Beck" title="Kent Beck" target="_blank">Kent Beck</a> he also published an article called <a href="http://junit.sourceforge.net/doc/testinfected/testing.htm" title="JUnit Test Infected: Programmers Love Writing Tests" target="_blank">JUnit Test Infected: Programmers Love Writing Tests</a> that describes how &#8216;your attitude toward development is likely to change&#8217;, once you drive your programming work consistently with tests. <span class='footnotereverse'><a href='#fnref-2439-2'>&#8617;</a></span></li>
<li id='fn-2439-3'>In particular if a breakpoint is not located in the test method as in the example but in the unit under test it can get annoying running all test methods of a test case. This is because the program execution might halt at the breakpoint triggered actually by one of the test methods that do not have a problem. <span class='footnotereverse'><a href='#fnref-2439-3'>&#8617;</a></span></li>
<li id='fn-2439-4'>Unfortunately the framework is not able to distinguish test methods from non test methods. Using the shortcut on non test methods will lead to JUnit runs that show an <em>Unrooted Tests</em> error as result. <span class='footnotereverse'><a href='#fnref-2439-4'>&#8617;</a></span></li>
<li id='fn-2439-5'>Some of the attendees considered it as a minor downside that the framework automatically creates and persists launch configurations. Because of this behaviour running single test methods via shortcuts can generate a lot of clutter in your launch configuration list over time. <span class='footnotereverse'><a href='#fnref-2439-5'>&#8617;</a></span></li>
<li id='fn-2439-6'>There are even tools available that run your tests continuously. <span class='footnotereverse'><a href='#fnref-2439-6'>&#8617;</a></span></li>
<li id='fn-2439-7'>In practice I often use the <code><em>Ctrl+F7</em></code> shortcut to switch to and/or between view parts. <span class='footnotereverse'><a href='#fnref-2439-7'>&#8617;</a></span></li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.codeaffine.com/2012/11/26/working-efficiently-with-junit-in-eclipse-2/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Running HTTP/REST Integration Tests efficiently in Eclipse</title>
		<link>http://www.codeaffine.com/2012/09/10/running-httprest-integration-tests-efficiently-in-eclipse/</link>
		<comments>http://www.codeaffine.com/2012/09/10/running-httprest-integration-tests-efficiently-in-eclipse/#comments</comments>
		<pubDate>Mon, 10 Sep 2012 08:42:40 +0000</pubDate>
		<dc:creator>Frank Appel</dc:creator>
				<category><![CDATA[Common]]></category>
		<category><![CDATA[Eclipse]]></category>

		<guid isPermaLink="false">http://www.codeaffine.com/?p=1875</guid>
		<description><![CDATA[Lately I had a chance to use the OSGi-JAX-RS-Connector library written by my dear fellow Holger Staudacher. The connector enables you to publish resources easily by registering @Path annotated types as OSGi services &#8211; which actually works quite nicely. While it is natural for me to write the service classes test driven using plain JUnit [...]]]></description>
			<content:encoded><![CDATA[<p>Lately I had a chance to use the <a target="_blank" href="https://github.com/hstaudacher/osgi-jax-rs-connector">OSGi-JAX-RS-Connector</a> library written by my dear fellow <a target="_blank" href="http://eclipsesource.com/blogs/author/hstaudacher/">Holger Staudacher</a>. The connector enables you to publish resources easily by registering <a target="_blank" href="http://docs.oracle.com/javaee/6/tutorial/doc/gilik.html">@Path</a> annotated types as <a target="_blank" href="http://en.wikipedia.org/wiki/OSGi#Services">OSGi services</a> &#8211; which actually works quite nicely.</p>
<p>While it is natural for me to write the service classes <a target="_blank" href="http://en.wikipedia.org/wiki/Test-driven_development">test driven</a> using plain <a target="_blank" href="http://junit.org/">JUnit tests</a> it is also very important to provide additional integration tests. Those tests allow to check runtime availability and functionality of such services. To provide the latter I used another little helper written by Holger &#8211; <a target="_blank" href="http://developer.eclipsesource.com/restfuse/">restfuse</a> which is a JUnit extension for automated HTTP/REST Tests.</p>
<p>The scenario looks somewhat like this:</p>
<p>A service</p>
<pre class="brush:java">
@Path( "/message" )
public class SampleService {
  
  @GET
  @Produces( MediaType.TEXT_PLAIN )
  public String getMessage() {
    return "Hello World";
  }
}
</pre>
<p>A JUnit test case</p>
<pre class="brush:java">
public class SampleServiceTest {
  
  @Test
  public void testGetMessage() {
    SampleService service = new SampleService();
    
    String message = service.getMessage();
    
    assertEquals( "Hello World", message );
  }
}
</pre>
<p>The service registration</p>
<pre class="brush:xml">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;scr:component
  xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0"
  name="SampleService"&gt;
   &lt;implementation class="sample.SampleService"/&gt;
   &lt;service&gt;
      &lt;provide interface="sample.SampleService"/&gt;
   &lt;/service&gt;
&lt;/scr:component&gt;
</pre>
<p>The restfuse integration test</p>
<pre class="brush:java">
@RunWith( HttpJUnitRunner.class )
public class SampleServiceHttpTest {
  
  @Rule
  public Destination destination
    = new Destination( "http://localhost:9092" );
  
  @Context
  private Response response;
  
  @HttpTest( method = Method.GET, path = "/services/message" )
  public void checkMessage() {
    String body = response.getBody( String.class );
    assertOk( response );
    assertEquals( MediaType.TEXT_PLAIN, response.getType() );
    assertEquals( "HelloWorld", body );
  }
}
</pre>
<p>The running service</p>
<p>
<img src="http://www.codeaffine.com/wp-content/uploads/2012/09/helloworldrestservice.png" alt="" title="Hello World Rest Service" width="374" height="116" />
</p>
<p>While all of this was quite straight forward it bugged me somehow that running the integration tests locally required first to launch the server before I was able to execute the integration test. Preoccupied by the task at hand I often forgot to launch the server and ran into connection timeouts or the like.</p>
<p>But I found a solution for this by using a <a href="http://wiki.eclipse.org/FAQ_What_is_a_PDE_JUnit_test%3F">PDE JUnit</a> launch configuration, because such a configuration can be setup to start the server within the process that runs the tests.</p>
<p>To do so create and select a test suite that contains all the integration tests to run<sup class='footnote'><a href='#fn-1875-1' id='fnref-1875-1'>1</a></sup>&#8230;</p>
<p><img src="http://www.codeaffine.com/wp-content/uploads/2012/09/integration-lauch-suite.png" alt="" title="Integration Launch Configuration - Test Suite selection" width="621" height="281" class="alignnone size-full wp-image-1902" /></p>
<p>&#8230;after that switch to the main tab and select the headless mode&#8230;</p>
<p><img src="http://www.codeaffine.com/wp-content/uploads/2012/09/integration-lauch-headless.png" alt="" title="Integration Lauch Configuration - Headless Mode" width="634" height="359" class="alignnone size-full wp-image-1898" /></p>
<p>&#8230; and last but not least configure the program arguments used by the server which in our case basically concerns the port definition.</p>
<p><img src="http://www.codeaffine.com/wp-content/uploads/2012/09/integration-lauch-server-port.png" alt="" title="Integration Launch Configuration - Server Port Configuration" width="626" height="359" class="alignnone size-full wp-image-1903" /></p>
<p>The bundle selection in the Plug-ins tab contains the same bundles as those of the osgi launch configuration that is used to run the server standalone plus the JUnit-, PDE JUnit-, restfuse-bundles and their dependencies. The selected test suite may looks like this:</p>
<pre class="brush:java">
@RunWith( Suite.class ) 
@SuiteClasses( {
  SampleServiceHttpTest.class
} )
public class AllRestApiIntegrationTestSuite {
  
  public static String BASE_URL
    = "http://localhost:" 
    + System.getProperty( "org.osgi.service.http.port" );
}
</pre>
<p>The only unusual thing here is the BASE_URL constant definition. As mentioned above the server port of the test run is specified as a program argument in the launch configuration. But restfuse tests need to provide the port during the destination rule definition. Using the approach above allows to change the port in the configuration without affecting the tests. Simply use the constant as parameter in the definition as shown in the following snippet<sup class='footnote'><a href='#fn-1875-2' id='fnref-1875-2'>2</a></sup><sup class='footnote'><a href='#fn-1875-3' id='fnref-1875-3'>3</a></sup>.</p>
<pre class="brush:java">
 @Rule
  public Destination destination
    = new Destination( BASE_URL );
</pre>
<p>This simple setup worked out very well and improved my workflow of running the integration tests locally. And saving the launch configuration in a shared project easily enables your team mates to reuse it.</p>
<p>So this is it for today and as always feedback is highly appreciated. By the way, Holger promised me to write a post about how to integrate that stuff described above into a <a target="_blank" href="http://www.eclipse.org/tycho/">maven/tycho</a> based build<sup class='footnote'><a href='#fn-1875-4' id='fnref-1875-4'>4</a></sup> &#8211; so stay tuned <img src='http://www.codeaffine.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  </p>
<hr />
<div class='footnotes'>
<div class='footnotedivider'></div>
<ol>
<li id='fn-1875-1'>Of course you can also use the possibility of running all tests of the selected project, package or source folder &#8211; but for our purposes here using the suite approach and running a single test case is quite ok <span class='footnotereverse'><a href='#fnref-1875-1'>&#8617;</a></span></li>
<li id='fn-1875-2'>You probably would provide a separate class for the constant definition in a real world scenario to avoid the coupling of the tests to the suite. I skipped this here for simplification. <span class='footnotereverse'><a href='#fnref-1875-2'>&#8617;</a></span></li>
<li id='fn-1875-3'>Note that the BASE_URL is included using static imports for better readability of the snippet <span class='footnotereverse'><a href='#fnref-1875-3'>&#8617;</a></span></li>
<li id='fn-1875-4'>Holger kept his promise, see: <a target="_blank" href="http://eclipsesource.com/blogs/2012/09/11/running-httprest-integration-tests-in-an-eclipse-tycho-build/">http://eclipsesource.com/blogs/2012/09/11/running-httprest-integration-tests-in-an-eclipse-tycho-build/</a> <span class='footnotereverse'><a href='#fnref-1875-4'>&#8617;</a></span></li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.codeaffine.com/2012/09/10/running-httprest-integration-tests-efficiently-in-eclipse/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>EclipseCon Europe — RAP Talk On-Line</title>
		<link>http://www.codeaffine.com/2011/11/18/eclipsecon-europe-%e2%80%94-rap-talk-on-line/</link>
		<comments>http://www.codeaffine.com/2011/11/18/eclipsecon-europe-%e2%80%94-rap-talk-on-line/#comments</comments>
		<pubDate>Fri, 18 Nov 2011 06:45:58 +0000</pubDate>
		<dc:creator>Frank Appel</dc:creator>
				<category><![CDATA[Eclipse]]></category>

		<guid isPermaLink="false">http://www.codeaffine.com/?p=918</guid>
		<description><![CDATA[The last weeks were very exciting since I could talk about the new RAP OSGi integration feature (see I, II, III) on various occasions. It was amazing to see how the RAP community has evolved over the last years. While in the early days you always had to do the slot &#8220;What is RAP&#8221; and [...]]]></description>
			<content:encoded><![CDATA[<p>The last weeks were very exciting since I could talk about the new RAP OSGi integration feature (see <a href="http://www.codeaffine.com/2011/08/26/raprwt-osgi-integration/" target="_blank">I</a>, <a href="http://www.codeaffine.com/2011/10/05/raprwt-osgi-integration-ii/"  target="_blank">II</a>, <a href="http://www.codeaffine.com/2011/10/13/raprwt-osgi-integration-iii/"  target="_blank">III</a>) on various <a href="http://www.codeaffine.com/events/" target="_blank">occasions</a>. It was amazing to see how the RAP community has evolved over the last years.</p>
<p>While in the early days you always had to do the slot &#8220;What is RAP&#8221; and &#8220;How does it work&#8221; nowadays the majority of the people I speak to are pretty familiar with the technology. Even more I had very interesting conversations about how people use RAP, how they adopted the <a href="http://www.eclipse.org/rap/documentation/#resources">single sourcing</a> approach with RCP and what they expect from the future development streams.</p>
<p>So I was very pleased to see that there is a huge interest in the native UI support of smartphone and tablets that RAP will offer within the next release. The underlying protocol implementation of the server-client communication needed for this, has been on the backlog for years, but so long there have not been a use case that justified the investment. Kudos goes to <a href="http://eclipsesource.com/blogs/2010/04/28/rap-2-0-protocol/" target="_blank">Holger</a> doing the groundwork here.</p>
<p>The discussions also affirmed me that the RAP team is on the right track to press ahead with improving the RWT standalone capabilities and as a result of that the integration possibilities with containers like OSGi, Spring etc.</p>
<p>So if you missed the show here is a recording of the talk <a href="http://eclipsesource.com/blogs/author/rsternberg/" target="_blank">Ralf Sternberg</a> and I were given at <a href="http://eclipsecon.org/europe2011/" target="_blank">EclipseCon Europe</a>:</p>
<p><iframe width="520" height="415" src="http://a.blip.tv/scripts/shoggplayer.html#showplayerpath=http%3A%2F%2Fa.blip.tv%2Fscripts%2Fshoggplayer.html&#038;feedurl=http%3A%2F%2Ffosslc.blip.tv%2Frss%2Fflash&#038;brandname=fosslc.org&#038;brandlink=http%3A%2F%2Ffosslc.org&#038;enablejs=true&#038;allowm4v=true&#038;tabType1=details&#038;tabTitle1=About&#038;tabType2=guide&#038;tabTitle2=Episodes&#038;tabUrl2=http%3A%2F%2Ffosslc.blip.tv%2Frss%2Fflash&#038;tabType3=none&#038;usecaptions=true&#038;file=http%3A%2F%2Fblip.tv%2Frss%2Fflash%2F5729738&#038;lookup=hdlkgt3cLgA" frameborder='0' allowfullscreen></iframe></p>
<p>Although I have finished my list of current sessions there are still opportunities to see the talk live as <a href="http://eclipsesource.com/blogs/author/rsternberg/" target="_blank">Ralf</a>, <a href="http://eclipsesource.com/blogs/author/hstaudacher/" target="_blank">Holger</a> and <a href="http://eclipsesource.com/blogs/author/mknauer/" target="_blank">Markus</a> will present it at the following <a href="http://wiki.eclipse.org/Eclipse_DemoCamps_November_2011" target="_blank">Eclipse democamps</a>: </p>
<p><a href="http://wiki.eclipse.org/Eclipse_DemoCamps_November_2011/Hamburg" target="_blank">Hamburg, 23th November</a><br />
<a href="http://wiki.eclipse.org/Eclipse_DemoCamps_November_2011/Kaiserslautern" target="_blank">Kaiserslautern, 24th November</a><br />
<a href="http://wiki.eclipse.org/Eclipse_DemoCamps_November_2011/Karlsruhe" target="_blank">Karlsruhe, 29th November</a><br />
<a href="http://wiki.eclipse.org/Eclipse_DemoCamps_November_2011/Vienna" target="_blank">Vienna, 2nd Dezember</a></p>
<p>So if you want your piece of the 10 years of Eclipse birthday cake register now <img src='http://www.codeaffine.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.codeaffine.com/2011/11/18/eclipsecon-europe-%e2%80%94-rap-talk-on-line/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Democamp Slides</title>
		<link>http://www.codeaffine.com/2011/11/16/democamp-slides/</link>
		<comments>http://www.codeaffine.com/2011/11/16/democamp-slides/#comments</comments>
		<pubDate>Wed, 16 Nov 2011 10:39:09 +0000</pubDate>
		<dc:creator>Frank Appel</dc:creator>
				<category><![CDATA[Eclipse]]></category>

		<guid isPermaLink="false">http://www.codeaffine.com/?p=912</guid>
		<description><![CDATA[For those who are interested I&#8217;ve uploaded the slides of my presentations at the eclipse democamps in bonn and munich. Thanks to Matthias, Jonas and Maximilian for organizing the events and giving me an opportunity to talk about the possibilties given with the new RWT OSGi integration bundle available in RAP.]]></description>
			<content:encoded><![CDATA[<p>For those who are interested I&#8217;ve uploaded the <a href='http://www.codeaffine.com/wp-content/uploads/2011/11/slides_rap_osgi_2011_11.pdf'>slides</a>  of my presentations at the eclipse democamps in <a href="http://wiki.eclipse.org/Eclipse_DemoCamps_November_2011/Bonn">bonn</a> and <a href="http://wiki.eclipse.org/Eclipse_DemoCamps_November_2011/Munich">munich</a>. Thanks to <a href="http://twitter.com/#!/mgutheil">Matthias</a>, <a href="http://eclipsesource.com/blogs/">Jonas and Maximilian</a> for organizing the events and giving me an opportunity to talk about the possibilties given with the new RWT OSGi integration bundle available in RAP.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codeaffine.com/2011/11/16/democamp-slides/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>RAP/RWT-OSGi Integration III</title>
		<link>http://www.codeaffine.com/2011/10/13/raprwt-osgi-integration-iii/</link>
		<comments>http://www.codeaffine.com/2011/10/13/raprwt-osgi-integration-iii/#comments</comments>
		<pubDate>Thu, 13 Oct 2011 06:21:39 +0000</pubDate>
		<dc:creator>Frank Appel</dc:creator>
				<category><![CDATA[Eclipse]]></category>

		<guid isPermaLink="false">http://www.codeaffine.com/?p=595</guid>
		<description><![CDATA[The previous posts 1 about the new RWT-OSGi integration bundle of RAP 1.5 concentrated on the various possibilities of how to run RWT as Web-UI-Toolkit in OSGi environment. In this post I will discuss some ideas of how to use RWT and OSGi to build dynamic web applications. To do so I have upgraded the [...]]]></description>
			<content:encoded><![CDATA[<p>The previous posts <sup class='footnote'><a href='#fn-595-1' id='fnref-595-1'>1</a></sup> about the new RWT-OSGi integration bundle of <a title="RAP Downloads" href="http://eclipse.org/rap/downloads/" target="_blank">RAP 1.5</a> concentrated on the various possibilities of how to run RWT as Web-UI-Toolkit in OSGi environment. In this post I will discuss some ideas of how to use RWT and OSGi to build dynamic web applications. To do so I have upgraded the example application<sup class='footnote'><a href='#fn-595-2' id='fnref-595-2'>2</a></sup> I use throughout this mini series.</p>
<h4>The Example</h4>
<p>Again I start with a short walk through of the example&#8217;s main functionality. The main development concepts behind the scenes are covered in the next section. Once you have imported the example projects into your Eclipse workspace you can use the <em>RWT-OSGi-ConfigurationAdmin</em> launch configuration contained in the configuration admin project to start the example.</p>
<p>As shown in the last post we can use the following console commands to start the example application:</p>
<pre>
startHttpService 10010
deployApplication ExampleUI1 10010
</pre>
<p>We are able to access this application in the browser using the URL &#8220;http://localhost:10010/example&#8221;:</p>
<p><img src="http://www.codeaffine.com/wp-content/uploads/2011/10/applicationframe.png" alt="" width="400" height="277" class="alignnone size-full wp-image-612" /></p>
<p>The screenshot above shows basically an empty web application frame that is bare of any content yet. To change this use the following console command:</p>
<pre>
deployUIContribution HomePageTab ExampleUI1 10010
</pre>
<p>Well, on first sight the changes are not that impressing either. But actually the command added dynamically content to our application:</p>
<p><img src="http://www.codeaffine.com/wp-content/uploads/2011/10/dynamic-contributions.png" alt="Dynamic Contributions" width="455" height="312" class="alignnone size-full wp-image-615" /></p>
<p>Using the command &#8220;ss&#8221; at the &#8220;osgi&gt;&#8221; prompt provided by our UI contribution clarifies what our contribution is all about:</p>
<p><img src="http://www.codeaffine.com/wp-content/uploads/2011/10/osgi-console.png" alt="OSGi Console" width="400" height="323" class="alignnone size-full wp-image-618" /></p>
<p>Having a console session available in our web application we can use it just as well to contribute further functionality.  Using the command as shown in the following screenshot&#8230;</p>
<p><img src="http://www.codeaffine.com/wp-content/uploads/2011/10/start-bundle-upload.png" alt="Start Bundle Upload Contribution" width="566" height="256" class="alignnone size-full wp-image-626" /></p>
<p>&#8230; contributes a new UI element to the application:</p>
<p><a href="http://www.codeaffine.com/wp-content/uploads/2011/10/upload-contribution.png"><img src="http://www.codeaffine.com/wp-content/uploads/2011/10/upload-contribution.png" alt="Upload Contribution" width="718" height="269" class="alignnone size-full wp-image-627" /></a></p>
<p>I think that is enough to grasp the basic idea of the example, so let us have a look into some of the programming details.</p>
<h4>Behind the scenes</h4>
<p>In our example application we use a little helper called <code>UIContributorTracker</code><sup class='footnote'><a href='#fn-595-3' id='fnref-595-3'>3</a></sup> to contribute content dynamically to RWT based web applications<sup class='footnote'><a href='#fn-595-4' id='fnref-595-4'>4</a></sup>. As the name implies it tracks UI contributions provided by instances of <code>UIContributor</code>. <code>UIContributor</code> implementations are meant to be used as UI builders and each contribution type is declared as OSGi service. The <code>UIContributorTracker</code> implementation uses a <code>ServiceTracker</code> to track the lifecycles of such contributions.</p>
<pre class="brush:java">public interface UIContributor {
  String getId();
  Control contribute( Composite parent );
}</pre>
<p>As you can see the contributor interface is straight forward. It demands an identifier that can be used by implementations of user interaction<sup class='footnote'><a href='#fn-595-5' id='fnref-595-5'>5</a></sup> to identify and activate a certain contribution. Furthermore it provides the actual builder functionality that allows to embed UI contributions into the RWT based web frame application. A simple implementation may look like this:</p>
<pre class="brush:java">public class HelloWorld implements UIContributor {

  @Override
  public String getId() {
    return "Hello";
  }

  @Override
  public Control contribute( Composite parent ) {
    Label label = new Label( parent, SWT.NONE );
    label.setText( "Hello World" );
    return label;
  }
}</pre>
<p>The respective OSGi service declaration will look like this:</p>
<pre class="brush:xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0"
  name="HelloWorld"
  configuration-policy="require"&gt;
  &lt;implementation
    class="com.codeaffine.example.rwt.osgi.ui.example.HelloWorld"/&gt;
  &lt;property name="type" type="String" value="page"/&gt;
  &lt;service&gt;
     &lt;provide
    interface="com.codeaffine.example.rwt.osgi.ui.platform.UIContributor"/&gt;
  &lt;/service&gt;
&lt;/scr:component&gt;</pre>
<p>Nothing spectacular in it especially if you are familiar with the previous posts. We use the configuration-policy to keep the declared service dormant until it is explicitly invoked by the configuration admin service. The property &#8220;type&#8221; will be used in an LDAP filter expression to distinguish between different kinds of UI contributions. In the &#8220;HelloWorld&#8221; case above we decided that the contribution is used as an additional page. In our example webapp page contributions are presented to the end-user as selectable entry in the navigation bar.</p>
<p>Using the following command&#8230;</p>
<pre>
deployUIContribution HelloWorld ExampleUI1 10010
</pre>
<p>&#8230; will integrate the &#8220;HelloWorld&#8221; contribution into the running example instance:</p>
<p><img src="http://www.codeaffine.com/wp-content/uploads/2011/10/hello-world-contribution.png" alt="Hello World Contribution" title="" width="355" height="239" class="alignnone size-full wp-image-657" /></p>
<p>That was not too difficult, was it?</p>
<p>Before comming an end I want to point out some of the noteworthiness things about the <code>UIContributorTracker</code> mentioned above.</p>
<ul>
<li>The tracker is intended to be extended. Implementers may override e.g. the. addingService() method.</li>
<li>The tracker implementation relies on an OSGi <code>ServiceTracker</code> that is registered as an OSGi service itself. <code>UIContributorTracker</code> instances gain access to <code>UIContributor</code> services using this global tracker service. This approach allows that each contributor has only one reference counter and can be deregistered again easily. Contributor registration and deregistration events are broadcasted to the registered <code>ContributorTracker</code>s. So despite of the name the <code>UIContributorTracker</code> is not an OSGi service tracker.</li>
<li>The tracker implementation already takes care of the background threads that notifies about service lifecycle changes. Updates of RWT UI elements are only allowed using the appropriate <code>UIThread</code>. Therefore the tracker decouples the background thread from the actual work of creating the UI parts using a callback functionality provided by RWT.</li>
</ul>
<p>Here is a snippet that shows how the tracker can be used:</p>
<pre class="brush:java">@Override
public UIContributor addingService( ServiceReference&lt;UIContributor&gt; reference, UIContributor service ) {
  if( ConfiguratorTracker.matchesType( "BundleUpload", reference ) ) {
    bundleUploadContributor = service;
    updatePage();
  }
  return result;
}</pre>
<p>The code above shows how the added <code>UIContributor</code> service is used only in case of a matching contribution type. As mentioned above the contribution type is specified as a service property e.g. at service declaration time. The contributor is buffered<sup class='footnote'><a href='#fn-595-6' id='fnref-595-6'>6</a></sup> and the call of <code>updatePage()</code> will supplement the contribution to the current page content by calling <code>UIContributor#contribute(Composite)</code> on the given contributor instance.</p>
<h4>Conclusion</h4>
<p>Although we do not have an out of the box application framework to create OSGi based web applications with RAP/RWT at the moment, I showed that there is already a lot of infrastructure available and with a little hands-on skills you can build some quite effective web apps on top of it<sup class='footnote'><a href='#fn-595-7' id='fnref-595-7'>7</a></sup>.</p>
<p>Last but not least I like to mention that a fellow developer, <a href="http://eclipsesource.com/blogs/author/rsternberg/" target="_blank">Ralf Sternberg</a>, and I will talk at <a href="http://eclipsecon.org/" target="_blank">EclipseCon Europe</a> about <a href="http://eclipsecon.org/sessions/dynamic-web-applications-osgi-and-rap" target="_blank">Dynamic Web Applications with OSGi and RAP</a>. We also have a tutorial slot <a href="http://eclipsecon.org/sessions/lightweight-dynamic-webapps-made-easy-rap-and-osgi-presented-eclipsesource">Lightweight, Dynamic Webapps Made Easy with RAP and OSGi</a> that will go more into details of things. So if you interested and you happen to be at the event &#8211; don&#8217;t be shy, just drop by <img src='http://www.codeaffine.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>&nbsp;</p>
<hr />
<div class='footnotes'>
<div class='footnotedivider'></div>
<ol>
<li id='fn-595-1'><a title="RAP/RWT-OSGi Integration" href="http://www.codeaffine.com/2011/08/26/raprwt-osgi-integration/" target="_blank">RAP/RWT-OSGi Integration</a>, <a title="RAP/RWT-OSGi Integration II" href="http://www.codeaffine.com/2011/10/05/raprwt-osgi-integration-ii/" target="_blank">RAP/RWT-OSGi Integration II</a> <span class='footnotereverse'><a href='#fnref-595-1'>&#8617;</a></span></li>
<li id='fn-595-2'><a title="RWT ConfigurationAdmin Example" href="https://github.com/fappel/RWT_CONFIG_ADMIN_EXAMPLE">https://github.com/fappel/RWT_CONFIG_ADMIN_EXAMPLE</a>: Import the plugin projects contained in the git repository into a workspace of your Eclipse IDE. The configuration admin project contains a target definition (target.target). Open this file with the target editor, wait till the target resolving job has been completed and click on the <em>Set as Target Platform</em> link afterwards (If the target editor shows problems resolving the RAP runtime, select the according entry in the list and click the update button on the right). Last you should check out <a href="http://dev.eclipse.org/viewcvs/viewvc.cgi/org.eclipse.rap/incubator/supplemental/fileupload/org.eclipse.rap.rwt.supplemental.fileupload/?root=RT_Project" target="_blank">org.eclipse.rap.rwt.supplemental.fileupload</a> and <a href="http://dev.eclipse.org/viewcvs/viewvc.cgi/org.eclipse.rap/runtime.ui/org.eclipse.rap.jettycustomizer/?root=RT_Project" target="_blank">org.eclipse.rap.jettycustomizer</a> from Eclipse CVS. <span class='footnotereverse'><a href='#fnref-595-2'>&#8617;</a></span></li>
<li id='fn-595-3'>This class is located in the com.codeaffine.example.rwt.osgi.ui.platform project. <span class='footnotereverse'><a href='#fnref-595-3'>&#8617;</a></span></li>
<li id='fn-595-4'>Unfortunately an explanation of how to build a web application frame with RWT from scratch exceeds the scope of this post <span class='footnotereverse'><a href='#fnref-595-4'>&#8617;</a></span></li>
<li id='fn-595-5'>such as clicking on a navigation bar entry <span class='footnotereverse'><a href='#fnref-595-5'>&#8617;</a></span></li>
<li id='fn-595-6'>The code snippet stores the contributor to a field of the surrounding <code>UIContributor</code>. Although this works in our simple example it is not a good idea. Since <code>UIContributors</code> are shared globally setting the field would impact all UIs where the surrounding contributor is used. Therefore a production ready solution has to use a little more sophisticated approach&#8230; <span class='footnotereverse'><a href='#fnref-595-6'>&#8617;</a></span></li>
<li id='fn-595-7'>But keep in mind that all the UI platform code I used in the example is experimental stuff and is not intended to be used in production. But otherwise you are welcome to play around with it and come up with some new and intriguing ideas <img src='http://www.codeaffine.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  <span class='footnotereverse'><a href='#fnref-595-7'>&#8617;</a></span></li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.codeaffine.com/2011/10/13/raprwt-osgi-integration-iii/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>RAP/RWT-OSGi Integration II</title>
		<link>http://www.codeaffine.com/2011/10/05/raprwt-osgi-integration-ii/</link>
		<comments>http://www.codeaffine.com/2011/10/05/raprwt-osgi-integration-ii/#comments</comments>
		<pubDate>Wed, 05 Oct 2011 03:40:07 +0000</pubDate>
		<dc:creator>Frank Appel</dc:creator>
				<category><![CDATA[Eclipse]]></category>

		<guid isPermaLink="false">http://www.codeaffine.com/?p=509</guid>
		<description><![CDATA[In my last post about the new RWT-OSGi integration bundle of RAP 1.5 I have promised to provide a little example of how to use RWT in combination with the ConfigurationAdmin service of OSGi. In this post I will keep that promise and show how to register RWT applications arbitrarily at different http service instances. To [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a title="RAP/RWT-OSGi Integration" href="http://www.codeaffine.com/2011/08/26/raprwt-osgi-integration/" target="_blank">last post</a> about the new RWT-OSGi integration bundle of <a title="RAP 1.5 Nightly Build" href="http://eclipse.org/rap/downloads/" target="_blank">RAP 1.5</a> I have promised to provide a little example of how to use RWT in combination with the <a title="ConfigurationAdmin Service" href="http://www.dynamicjava.org/articles/osgi-compendium/configuration-admin-service" target="_blank">ConfigurationAdmin </a>service of OSGi. In this post I will keep that promise and show how to register RWT applications arbitrarily at different http service instances. To do so I use the configuration admin service and the <a title="Equinox CommandProvider" href="http://blog.sarathonline.com/2008/12/using-equinox-commandprovider-to-make.html" target="_blank">CommandProvider</a> service of <a title="Eclipse Equinox" href="http://eclipse.org/equinox/" target="_blank">Equinox</a>. The sources of the example can be found at <a title="RWT ConfigurationAdmin Example" href="https://github.com/fappel/RWT_CONFIG_ADMIN_EXAMPLE">https://github.com/fappel/RWT_CONFIG_ADMIN_EXAMPLE</a> <sup class='footnote'><a href='#fn-509-1' id='fnref-509-1'>1</a></sup>.</p>
<h4>The Example</h4>
<p>I start with a short walk through of the example&#8217;s main functionality. Some of the development details behind the scenes are covered in the next section. The example project contained in the source repository mentioned above includes a launch configuration called <em>RWT-OSGi-ConfigurationAdmin</em>. After launching it we can type &#8220;help&#8221; <sup class='footnote'><a href='#fn-509-2' id='fnref-509-2'>2</a></sup> into the OSGi console window of the newly created process. This displays a list of the commands available to control the system.</p>
<p>Those who are familiar with the equinox console will detect a new block:</p>
<pre>---Configuration of ApplicationLauncher---
	startHttpService &lt;port&gt;
	stopHttpService &lt;port&gt;
	deployApplication &lt;configurator name&gt;|&lt;port&gt;|&lt;contextName(optional)&gt;
	undeployApplication &lt;configurator name&gt;|&lt;port&gt;|&lt;contextName(optional)&gt;</pre>
<p>With the first two commands we can start and stop an instance of HttpService. The service will be bound to the port specified by the command parameter:</p>
<p><img class="size-full wp-image-520 alignnone" src="http://www.codeaffine.com/wp-content/uploads/2011/10/start-http-service.png" alt="Start of Http Service" width="537" height="125" /></p>
<p>The screenshot shows the print out after starting two http service instances, one at port 10010 and one at 10020. Pointing your browser to the URL <em>http://localhost:10010/</em> or <em> http://localhost:10020/</em> respectively shows that the services are alive but return an HTTP 404. This is quite ok since we did not register any resources yet to be found. We will change this by typing:</p>
<p><img src="http://www.codeaffine.com/wp-content/uploads/2011/10/deploy-application.png" alt="Deploy Application" width="291" height="46" class="alignnone size-full wp-image-525" /></p>
<p>Using the URLs <em>http://localhost:10010/helloworld</em> or <em> http://localhost:10020/datepicker</em> now show the following applications:</p>
<p><img src="http://www.codeaffine.com/wp-content/uploads/2011/10/applications.png" alt="Applications" width="688" height="182" class="alignnone size-full wp-image-526" /></p>
<p>So the example enables us to start/stop http services dynamically in one process and deploy/undeploy<sup class='footnote'><a href='#fn-509-3' id='fnref-509-3'>3</a></sup> various RWT applications at those services. The latter uses the port property of the http service as binding selector. Quite nice I think <img src='http://www.codeaffine.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  But actually it does a little bit more. Stopping and restarting the process shows that the latest configuration has been stored<sup class='footnote'><a href='#fn-509-4' id='fnref-509-4'>4</a></sup>. The system will start up the two services and deploy the RWT applications again to those services:</p>
<p> <img src="http://www.codeaffine.com/wp-content/uploads/2011/10/relaunch.png" alt="Relaunch" width="529" height="82" class="alignnone size-full wp-image-528" /></p>
<h4>Behind the scenes</h4>
<p>To be able to start and stop the http service instances we use the managed service factory implementation provided by the jetty<sup class='footnote'><a href='#fn-509-5' id='fnref-509-5'>5</a></sup> control bundle. You can find the service in our example above using the services console command:</p>
<pre>
osgi&gt; services org.osgi.service.cm.ManagedServiceFactory
{org.osgi.service.cm.ManagedServiceFactory}={service.pid=org.eclipse.equinox.http.jetty.config, service.id=40}
  Registered by bundle: org.eclipse.equinox.http.jetty_2.0.100.v20110502 [12]
  Bundles using service:
    org.eclipse.equinox.cm_1.0.300.v20110502 [6] 
</pre>
<p>Looking at the print out we also recognize the service.pid property which I use in the <code>CommandProvider</code> implementation to create a new http service configuration at runtime:</p>
<pre class="brush:java">private Configuration createHttpServiceConfiguration()
  throws IOException
{
  ConfigurationAdmin configAdmin = getConfigurationAdmin();
  String location = findHttpServiceManagerLocation();
  String PID = "org.eclipse.equinox.http.jetty.config";
  return configAdmin .createFactoryConfiguration( PID, location );
}</pre>
<p>The location is the location attribute of the jetty bundle that registers the factory. We can use the configuration created above to start a new equinox jetty based http service at a given port:</p>
<pre class="brush:java">[...]
  Configuration configuration = createHttpServiceConfiguration();
  configuration.update( createHttpServiceSettings( port ) );
[...]

private Dictionary&lt;String, Object&gt; createHttpServiceSettings( String port ) {
  Dictionary&lt;String,Object&gt; result = new Hashtable&lt;String, Object&gt;();
  result.put( JettyConstants.HTTP_PORT, Integer.valueOf( port ) );
  result.put( JettyConstants.CUSTOMIZER_CLASS,
                 "org.eclipse.rap.jettycustomizer.internal.SessionCookieCustomizer" );
  return result;
}</pre>
<p>The <code>Configuration#update(Dictonary)</code> method starts the service and persists its configuration. This allows the system to restart the service with the same configuration during the next lauch.</p>
<p>Note that the http service settings use constant definitions of the particular <code>HttpService</code> implementation. Therefore this will not work with another service implementation.</p>
<p>Now let us have a look at how to start and bind an RWT application to such an http service instance. The example provides several <code>ApplicationConfiguration</code> service declarations that looks like this:</p>
<pre class="brush:xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0"
  immediate="true"
  configuration-policy="require"
  name="helloWorld"&gt;
  &lt;implementation
    class="com.codeaffine.example.rwt.osgi.configurationadmin.applications.HelloWorldApplicationConfiguration"/&gt;
  &lt;service&gt;
     &lt;provide
       interface="org.eclipse.rap.rwt.application.ApplicationConfiguration"/&gt;
  &lt;/service&gt;
&lt;/scr:component&gt;</pre>
<p>The interesting part for us is the property &#8220;configuration-policy&#8221; of the &#8220;component&#8221; tag. Setting it to &#8220;require&#8221; allows us to use the configuration admin to deploy RWT applications on various http services:</p>
<pre class="brush:java">Configuration configuration = configurationAdmin.createFactoryConfiguration( configurationName );
configuration.update( createApplicationSettings([...], port, [...]) );</pre>
<p>Where createApplicationSettings(&#8230;) creates the property that is used to bind the<br />
application to a certain http service. The property uses the port number as selector in a filter expression. In case the binding should be done to an http service on port 10010 it would look like this:</p>
<pre>httpService.target=(http.port=10010)</pre>
<h4>Conclusion</h4>
<p>In this post I gave an impression of the possibilities using RWT in conjunction with the <code>ConfigurationAdmin</code> service. So if you want to play around with the stuff or want to look at the implementations in more detail simply pull the example from the repository. But keep in mind that the example is only meant for demonstration purpose and not intended to be production ready.</p>
<p>Now that we have seen how to start and stop RWT applications dynamically there is still the question of how to contribute UI elements dynamically to a running application &#8211; but this is a story I will probably cover in another post.. </p>
<p>Last but not least I like to mention that a fellow developer, <a href="http://eclipsesource.com/blogs/author/rsternberg/" target="_blank">Ralf Sternberg</a>, and I will talk at <a href="http://eclipsecon.org/" target="_blank">EclipseCon Europe</a> about <a href="http://eclipsecon.org/sessions/dynamic-web-applications-osgi-and-rap" target="_blank">Dynamic Web Applications with OSGi and RAP</a>. So if you interested and you happen to be at the event &#8211; don&#8217;t be shy, just drop by <img src='http://www.codeaffine.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>&nbsp;</p>
<hr />
<div class='footnotes'>
<div class='footnotedivider'></div>
<ol>
<li id='fn-509-1'>Import the plugin project contained in the git repository into a workspace of your Eclipse IDE. The project contains a target definition (target.target). Open this file with the target editor, wait till the target resolving job has been completed and click on the <em>Set as Target Platform</em> link afterwards (If the target editor shows problems resolving the RAP runtime, select the according entry in the list and click the update button on the right). Last you should check out <a href="http://dev.eclipse.org/viewcvs/viewvc.cgi/org.eclipse.rap/incubator/supplemental/fileupload/org.eclipse.rap.rwt.supplemental.fileupload/?root=RT_Project" target="_blank">org.eclipse.rap.rwt.supplemental.fileupload</a> and <a href="http://dev.eclipse.org/viewcvs/viewvc.cgi/org.eclipse.rap/runtime.ui/org.eclipse.rap.jettycustomizer/?root=RT_Project" target="_blank">org.eclipse.rap.jettycustomizer</a> from Eclipse CVS. <span class='footnotereverse'><a href='#fnref-509-1'>&#8617;</a></span></li>
<li id='fn-509-2'><em>help</em> is actually not a command provided by the system but it does the trick anyway&#8230; <span class='footnotereverse'><a href='#fnref-509-2'>&#8617;</a></span></li>
<li id='fn-509-3'>The term <em>deploy</em> may sound a little bit oversized as the bundle containing the application declaration has already been installed. But in the context of this post the name should point out the fact, that launching an application contains the notion of binding it to a certain http service. This means we can launch the same application declaration more than once, binding each one to a different HttpService instance, where each application instance is completely isolated from the other regarding static resources and memory (The latter does not hold for static fields of course&#8230;).  <span class='footnotereverse'><a href='#fnref-509-3'>&#8617;</a></span></li>
<li id='fn-509-4'>Ensure that the <em>Clear the configuration area before launching</em> of the <em>Settings</em> tab in the launch configuration is unchecked! <span class='footnotereverse'><a href='#fnref-509-4'>&#8617;</a></span></li>
<li id='fn-509-5'>SymbolicName: org.eclipse.equinox.http.jetty <span class='footnotereverse'><a href='#fnref-509-5'>&#8617;</a></span></li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.codeaffine.com/2011/10/05/raprwt-osgi-integration-ii/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>RAP/RWT-OSGi Integration</title>
		<link>http://www.codeaffine.com/2011/08/26/raprwt-osgi-integration/</link>
		<comments>http://www.codeaffine.com/2011/08/26/raprwt-osgi-integration/#comments</comments>
		<pubDate>Fri, 26 Aug 2011 07:24:46 +0000</pubDate>
		<dc:creator>Frank Appel</dc:creator>
				<category><![CDATA[Eclipse]]></category>

		<guid isPermaLink="false">http://www.codeaffine.com/?p=393</guid>
		<description><![CDATA[Motivation During my time as RAP technology lead I took care of some consulting projects using RAP/RCP in single sourcing fashion. Although this approach has proven very powerful to help people to bring their RCP applications to the web, I consider the workbench concept often too cumbersome if you are writing pure web applications from [...]]]></description>
			<content:encoded><![CDATA[<h4>Motivation</h4>
<p>During my time as RAP technology lead I took care of some consulting projects using RAP/RCP in <a title="Single Sourcing" href="http://www.slideshare.net/rsternberg/single-sourcing-rap-and-rcp-desktop-and-web-clients-from-a-single-code-base-1212420" target="_blank">single sourcing</a> fashion. Although this approach has proven very powerful to help people to bring their RCP applications to the web, I consider the workbench concept often too cumbersome if you are writing pure web applications from scratch.</p>
<p>Hence it was a logical step to put the workbench aside and use only RAP&#8217;s widget toolkit (RWT) as standalone library in OSGi environment for some project work. Unfortunately this did not work out as easy as it sounds and it needed a little bit of insight knowledge (which I fortunately had) to get this done. As I was working with this approach for a while I was able to pick up experience about what refactorings and extensions would be needed to provide RWT as genuine OSGi service component out of the box.</p>
<p>Luckily I had some time in the first half of the year 2011 and so I could start with the <a title="Refactoring RAP/RWT to Remove Class Variables" href="http://www.codeaffine.com/2011/03/10/refactoring-raprwt-to-remove-class-variables/" target="_blank">refactorings</a>. In the meanwhile I continued working on the RWT-OSGi integration and I am happy to say that the this integration is available with RAP 1.5.</p>
<h4>RWT OSGi Integration</h4>
<p>So what is it all about?</p>
<p>As I said above with the latest RAP version you can run RWT standalone as OSGi service without the need of the workbench and equinox-registry related stuff. Therefore you are not bound to a specific OSGi implementation anymore. So far I found the time to test this at least with <a href="http://eclipse.org/equinox/" target="_blank">equinox </a>and <a href="http://felix.apache.org/site/index.html" target="_blank">felix</a>.</p>
<p>How is it used?</p>
<p>The next two sections introduce the newly provided <code>ApplicationLauncher</code> functionality. First I show how to use the service programmatically for a better understanding of how things play together. After that I explain my preferred way of using it in a declarative manner.</p>
<h4>Service API</h4>
<p>In this section I assume your application is providing an up and running service instance of <a href="http://www.osgi.org/javadoc/r4v41/org/osgi/service/http/HttpService.html" target="_blank"><code>HttpService</code></a> <sup class='footnote'><a href='#fn-393-1' id='fnref-393-1'>1</a></sup>. Add the RWT- and the RWT-OSGi integration bundle to your application and you are ready to go <sup class='footnote'><a href='#fn-393-2' id='fnref-393-2'>2</a></sup>. Using a programmatic approach you have to retrieve the <code>HttpService</code> instance and the <code>ApplicationLauncher</code> instance (provided by the RWT-OSGi integration bundle) to wire both together. Retrieving the services can be done using ServiceTracker <sup class='footnote'><a href='#fn-393-3' id='fnref-393-3'>3</a></sup>.</p>
<p>Once you have both services the third thing you need is a configuration for your application. The newly provided <code>ApplicationConfiguration</code> API allows to register themes, branding information, entrypoints etc. at the application you are about to start. A simple configuration implementation may look like this:</p>
<pre class="brush:java">public class HelloWorldConfiguration
  implements ApplicationConfiguration
{

  public void configure( Application application ) {
    application.addEntryPoint( "/helloworld", HelloWorld.class, null );
  }
}</pre>
<p>As RWT is based on servlet technology the application given as parameter in the configure method also abstracts the <code>ServletContext</code> provided by an servlet container. The configuration is the place where you might register objects which live in application scope. Within your application you might access such objects using <code>RWT#getApplicationStore()</code><sup class='footnote'><a href='#fn-393-4' id='fnref-393-4'>4</a></sup>.</p>
<p>Now we are able to start an application with the following line of code:</p>
<pre class="brush:java">HttpService httpService = [...];
ApplicationLauncher launcher = [...];
ApplicationConfiguration configuration = [...];

ApplicationReference reference
  = launcher.launch(
      configuration, httpService, null, null, "&lt;pathToContextDirectory&gt;");</pre>
<p>The <em>pathToContextDirectory</em> points to a directory on the system&#8217;s disk where RWT can write static web content files like images, javascript files and so on.</p>
<p>With the third parameter you can provide an <code>HttpContext</code> instance e.g. to allow servlets registered at the http service with the same http context to share sessions with RWT. In the scenario above where we use <code>null</code> as http context parameter an http context will be created internally.</p>
<p>The fourth parameter declares an application context name. In the example above the URL to access our application in the browser may look like &#8220;http://myserver:9876/helloworld&#8221;. Using &#8220;mycontext&#8221; as context name parameter the URL would look like &#8220;http://myserver:9876/mycontext/helloworld&#8221;. The latter allows to run multiple application instances bound to the same http service <sup class='footnote'><a href='#fn-393-5' id='fnref-393-5'>5</a></sup>. Those instances are completely isolated from each other regarding heap memory and disk storage of static content.</p>
<p>Stopping an application is also very easy. Note that the example above returns an <code>ApplicationReference</code> instance. Calling <code>ApplicationReference#stopApplication()</code> on that instance will deregister the application from the http service instance. It conducts a defined shutdown process of the RWT subsystems and clean up the directory used for static content storage.</p>
<h4>Declarative Approach</h4>
<p>Given the same setup as in the chapter before registration of a single <code>ApplicationReference</code> gets very easy. Using <a href="http://felix.apache.org/site/index.html" target="_blank">Felix</a> for example you simply have to add a component declaration to your configuration class. This effectively registers the configuration as a service and the rwt osgi integration does the wiring for you:</p>
<pre class="brush:java">@Component( provide=ApplicationConfiguration.class)
public class HelloWorldConfiguration
  implements ApplicationConfiguration
{

  public void configure( Application application ) {
    application.addEntryPoint( "/helloworld", HelloWorld.class, null );
  }
}</pre>
<p>The entrypoint implementation of <code>HelloWorld</code> may looks like:</p>
<pre class="brush:java">public class HelloWorld implements IEntryPoint {

  @Override
  public int createUI() {
    Display display = new Display();
    int shellStyle = SWT.TITLE | SWT.MAX | SWT.RESIZE;
    Shell shell = new Shell( Display.getCurrent(), shellStyle );
    shell.setBounds( new Rectangle( 30, 30, 300, 250 ) );
    shell.setLayout( new FillLayout() );

    Label label = new Label( shell, SWT.NONE );
    label.setText( "HelloWorld" );

    shell.open();
    while( !shell.isDisposed() ) {
      if( !display.readAndDispatch() ) {
        display.sleep();
      }
    }

    return 0;
  }
}</pre>
<p>Believe it or not that is all. Launch you application and use an URL that looks like &#8220;http://localhost:8080/rap&#8221; to look at your first RWT standalone app that runs in OSGi:</p>
<p><img class="aligncenter size-full wp-image-442" title="helloworld_rwt_osgi" src="http://www.codeaffine.com/wp-content/uploads/2011/08/helloworld_rwt_osgi1.png" alt="Hello World with RWT and OSGi" width="367" height="341" /></p>
<p>But this is not everything you can do with the <code>ApplicationLauncher</code>. Consider a situation where you run two http services in your OSGi server application. One for public access on port 80 and the other for internal adminstration purpose on port 8080. With the approach above the helloworld application would register automatically on both services which is probably not what you want.</p>
<p>Let us assume that we want to register the hello world application only at the http service that runs on port 80. So how do we achieve this? The following example shows an appropriate declaration with jetty http service on equinox:</p>
<pre class="brush:xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0"
  immediate="true" 
  name="helloWorld"&gt;
   &lt;implementation
     class="com.codeaffine.rwtosgi.HelloWorldConfiguration"/&gt;
   &lt;service&gt;
      &lt;provide interface="org.eclipse.rap.rwt.application.ApplicationConfiguration"/&gt;
   &lt;/service&gt;
   &lt;property
     name="httpService.target"
     type="String" value="(http.port=80)"/&gt;
&lt;/scr:component&gt;</pre>
<p>In principle this is equivalent to the annotation in the previous example. But look at the additional property definition at the bottom of the declaration. This property represents a <a href="http://www.knopflerfish.org/osgi_service_tutorial.html#accessing" target="_blank">target filter</a> that refers to a property that is set on the equinox-jetty based http service. This property specifies the port to which the http service was bound. The application launcher instance recognizes this filter and deploys the newly created application only at the appropriate http service.</p>
<p>Using the <a href="http://www.osgilook.com/2009/03/22/configuration-admin-service-explained-the-managedservice-interface/" target="_blank">configuration admin service</a> you can use the target filter mechanism to dynamically register various rwt contexts on different http services and persist such configurations. But this is a story I will probably cover in another post&#8230;</p>
<p><em>Update 2011/11/05: Changed the technical terms and code snippets used in this post due to the results of the first refinements of the described API.</em></p>
<p><em>Update 2012/09/22: Changed the technical terms and code snippets used in this post due to the results of the finalized API.</em></p>
<hr />
<div class='footnotes'>
<div class='footnotedivider'></div>
<ol>
<li id='fn-393-1'>If you are not familar with http services good starting points may be <a href="http://www.eclipse.org/equinox/server/" target="_blank">Server Side Equinox</a> or <a href="http://felix.apache.org/site/apache-felix-http-service.html" target="_blank">Apache Felix HTTP Service</a> <span class='footnotereverse'><a href='#fnref-393-1'>&#8617;</a></span></li>
<li id='fn-393-2'>You find this bundles in the latest stable build of the RAP Runtime (Target Components) which is available for download at <a href="http://eclipse.org/rap/downloads/" target="_blank">RAP-Downloads</a>  <span class='footnotereverse'><a href='#fnref-393-2'>&#8617;</a></span></li>
<li id='fn-393-3'>If you are not familiar with this Neils Bartlett has written a nice introduction to this <a title="Dynamic Service Tracking" href="http://www.eclipsezone.com/eclipse/forums/t91059.rhtml" target="_blank">topic</a> and you also can have a look at RAP&#8217;s workbench code in the HttpServiceTracker class <span class='footnotereverse'><a href='#fnref-393-3'>&#8617;</a></span></li>
<li id='fn-393-4'>Running RWT without OSGi in a servlet container the configuration is registered by the web application&#8217;s web.xml and evaluated by the <code>RWTServletContextListener</code> <span class='footnotereverse'><a href='#fnref-393-4'>&#8617;</a></span></li>
<li id='fn-393-5'>Currently this works only if you configure the http service to use URL rewriting instead of session cookies <span class='footnotereverse'><a href='#fnref-393-5'>&#8617;</a></span></li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.codeaffine.com/2011/08/26/raprwt-osgi-integration/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Refactoring RAP/RWT to Remove Class Variables</title>
		<link>http://www.codeaffine.com/2011/03/10/refactoring-raprwt-to-remove-class-variables/</link>
		<comments>http://www.codeaffine.com/2011/03/10/refactoring-raprwt-to-remove-class-variables/#comments</comments>
		<pubDate>Thu, 10 Mar 2011 05:44:04 +0000</pubDate>
		<dc:creator>Frank Appel</dc:creator>
				<category><![CDATA[Eclipse]]></category>

		<guid isPermaLink="false">http://www.facon.biz/?p=52</guid>
		<description><![CDATA[Lately I have started with the first of a set of RAP refactorings to ease the task of using RWT (RAP Widget Toolkit) as standalone widget library for web applications. With the term &#8220;standalone&#8221; I do not only refer to the possibility of running RWT in a standard servlet container without using the RCP workbench concept. [...]]]></description>
			<content:encoded><![CDATA[<p>Lately I have started with the first of a set of <a href="http://www.eclipse.org/rap/" target="_blank">RAP</a> refactorings to ease the task of using <a href="http://wiki.eclipse.org/WidgetToolkit" target="_blank">RWT</a> (RAP Widget Toolkit) as <a href="http://wiki.eclipse.org/RAP/FAQ#How_do_I_use_an_RWT_standalone_application_in_Tomcat" target="_blank">standalone widget library</a> for web applications. With the term &#8220;standalone&#8221; I do not only refer to the possibility of running RWT in a standard servlet container without using the <a href="http://wiki.eclipse.org/index.php/Rich_Client_Platform" target="_blank">RCP</a> workbench concept. I also think about the capability of using RWT inside an <a href="http://www.osgi.org/Main/HomePage" target="_blank">OSGi</a> container or integrate with other runtime technologies like <a href="http://www.springsource.org/" target="_blank">Spring</a>.</p>
<p>RAP was basically created to enable RCP developers to build web applications reusing their knowledge and/or codebases. We have coined the term <a href="http://www.eclipsecon.org/summiteurope2008/sessions?id=87" target="_blank">Single Sourcing</a> for this. While RAP has been well adopted in the <a href="http://www.eclipse.org" target="_blank">eclipse community</a> there have always been folks using RWT to build web applications setting the workbench notion of RAP aside. This is quite understandable given the fact that the workbench concept forces you into a certain kind of UI paradigm that does not fit all use cases.</p>
<p>Unfortunately there are some difficulties buried in the depth of the library that hamper the standalone usage scenarios. One of those difficulties is the dated singleton structure used as implementation pattern for certain subsystems of the library. Consider for example multiple OSGi HttpServices in the same OSGi instance that run on different ports. Having RWT applications registered for at least two of those services would cause the singletons to be shared between those apps. This even may work to some extend, but it definitely opens up problems regarding the clean separation between applications on different ports. So I&#8217;ve opened a bug (<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=337787" target="_blank">#337787</a>) targeting this problem and volunteered to provide a solution.</p>
<p>Looking into the code I have found over 20 singletons or classes with class variables. Although those classes are not API, but given the widespread use of e.g. the resource manager implementation, simply changing those classes into non singletons and provide a different approach of accessing them would have caused a huge rupture throughout the library&#8217;s codebase. So I had to find a less intrusive solution that allowed a step wise refactoring to get rid of the class variables.</p>
<p>Fortunately RWT comes with a comprehensive Testsuite that allows you to do substantial design changes without risking defects or compatibility breaches. So I felt comfortable to do a first &#8220;under the hood&#8221; refactoring step that reduced the static fields and singletons to exactly one singleton that would hold all the instances. In principle the idea looks like the following:</p>
<p>Singletons like</p>
<pre class="brush:java">public class MySingleton {
  private static MySingleton instance = new MySingleton();

  public static MySingleton getInstance() {
    return instance;
  }
}</pre>
<p>were refactored to</p>
<pre class="brush:java">public class MySingleton {

  public static MySingleton getInstance() {
    return RWTContext.getInstance().getMySingleton();
  }
}

public class RWTContext {
  private static RWTContext instance = new RWTContext();

  private MySingleton mySingleton = new MySingleton();
  // [...] further singleton instances go here

  public static RWTContext getInstance() {
     return instance;
  }

  public MySingleton getMySingleton() {
    return mySingleton;
  }

  // [...] further singleton accessors go here
}</pre>
<p>The real implementation of RWTContext is somewhat more complex and uses currently a generic approach due to a problem of keeping the test suites alive. But the code above intends to give you the basic idea. Interested readers may have a look at the bug comments and the CVS history for more information.</p>
<p>Another problem that arose was that not all class variables represented singleton instances in terms of the pattern. Such variables were often simple maps used for buffering purposes controlled by a lot of static methods of the surrounding class. In this case the first step was to refactor the classes internally to match the singleton pattern:</p>
<p>Classes like</p>
<pre class="brush:java">public class MyStaticClass {
  private static Map buffer = new HashMap();

  public static Type get( String key ) {
    Type result = (Type )buffer.get( key );
    if( result == null ) {
      result = new Type();
      buffer.put( key, result );
    }
    return result;
  }

  // [...] further methods
}</pre>
<p>were refactored to</p>
<pre class="brush:java">public class MyStaticClass {
  private static MyStaticClass instance = new MyStaticClass();

  private Map buffer = new HashMap();

  public static Type get( String key ) {
    return getInstance().doGet( key );
  }

  private Type doGet( String key ) {
    Type result = (Type )buffer.get( key );
    if( result == null ) {
      result = new Type();
      buffer.put( key, result );
    }
    return result;
  }

  private static MyStaticClass getInstance() {
    return instance;
  }

  // [...] further methods
}</pre>
<p>After that this could be refactored to move the instance to the RWTContext as explained above. Unfortunately this would led to classes that looks somewhat confusing having these &#8216;makeIt&#8217; and &#8216;doMakeIt&#8217; like method name pairs all over the place. To clean up the clutter a little bit I split those classes into two before refactoring the getInstance method:</p>
<pre class="brush:java">public class MyStaticClass {
  private static MyStaticClass instance = new MyStaticClassInstance();

  public static Type get( String key ) {
    return getInstance().get( key );
  }

  private static MyStaticClass getInstance() {
    return instance;
  }

  // [...] further methods
}

class MyStaticClassInstance {
  private Map buffer = new HashMap();

  Type get( String key ) {
    Type result = (Type )buffer.get( key );
    if( result == null ) {
      result = new Type();
      buffer.put( key, result );
    }
    return result;
  }

  // [...] further methods
}</pre>
<p>The next refactoring step was to change the singleton implementation of RWTContext to get a clean separation in case of running RWT in multiple http contexts or services on OSGi. To do so the RWTContext instance is buffered as attribute in the ServletContext instance at web context startup. This allows to use an separate instance for each web context. If a web context and with it the servlet context containing the RWTContext instance is destroyed there will be nothing left over of RWT.</p>
<p>But this left the question of how gaining access to the RWTContext within the library when you use one of the singletons we have successfully refactored to delegate to the RWTContext? Fortunately RWT has already a build in solution for this.</p>
<p>We have had a similar problem accessing instances of classes that are session scoped. To gain access to the session that belongs to the current request there is a class called ServiceContext. The idea behind this is simple: At the beginning of the request processing an instance of ServiceContext is tucked as thread local to the request thread. This instance is released at the end of the processing cycle. The service context is fed with the session, request, response and other useful things. A static accessor (ContextProvider.getContext()) allows us to access the service context throughout the request.</p>
<p>To solve the problem of RWTContext access the service context was enhanced to provide access to the RWTContext instance:</p>
<pre class="brush:java">public class RWTContext {
  private static RWTContext instance = new RWTContext();

  public static RWTContext getInstance() {
    ServiceContext context = ContextProvider.getContext();
    return context.getRWTContext();
  }
}</pre>
<p>The real implementation here is also slightly more complicated, but basically follows the idea explained above. Internally the service context implementation uses the servlet API to retrieve the ServletContext that contains the RWTContext instance.</p>
<p><strong>Conclusion</strong><br />
The changes described above are committed into CVS Head and seem to work like charm as far as we can see. The main work was done on a rainy weekend, which I judge as a fair amount of time with respect to what have been achieved. Removing the singletons from RWT did not only improve the possibility to use the library standalone. It also enabled some follow up refactorings of the library code itself. In particular it helped to improve the testing infrastructure streamlining the setup and teardown mechanism for most of the test cases.</p>
<p>However as I mentioned at the beginning this was only the first step of a set of refactorings. The next steps will address the way of how RWT is initialized, how it runs within OSGi, how it handles the UI Thread and more. So stay tuned, I&#8217;ll keep you posted <img src='http://www.codeaffine.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.codeaffine.com/2011/03/10/refactoring-raprwt-to-remove-class-variables/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
