<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>dr. macphail&#039;s trance</title>
	<atom:link href="http://deors.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://deors.wordpress.com</link>
	<description>the cake is a lie</description>
	<lastBuildDate>Wed, 22 Feb 2012 17:35:32 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='deors.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://1.gravatar.com/blavatar/d531b0707db7a2fd8494cc296005ecb3?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>dr. macphail&#039;s trance</title>
		<link>http://deors.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://deors.wordpress.com/osd.xml" title="dr. macphail&#039;s trance" />
	<atom:link rel='hub' href='http://deors.wordpress.com/?pushpress=hub'/>
		<item>
		<title>10,000 visits!!</title>
		<link>http://deors.wordpress.com/2012/02/22/10000-visits/</link>
		<comments>http://deors.wordpress.com/2012/02/22/10000-visits/#comments</comments>
		<pubDate>Wed, 22 Feb 2012 17:35:30 +0000</pubDate>
		<dc:creator>deors</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://deors.wordpress.com/?p=324</guid>
		<description><![CDATA[Today the blog has hit the 10,000 visits. I never thought this would happen one day, so I&#8217;m really really happy. Thank you all.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=deors.wordpress.com&amp;blog=21758442&amp;post=324&amp;subd=deors&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Today the blog has hit the 10,000 visits. I never thought this would happen one day, so I&#8217;m really really happy.</p>
<p>Thank you all.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/deors.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/deors.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/deors.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/deors.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/deors.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/deors.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/deors.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/deors.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/deors.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/deors.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/deors.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/deors.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/deors.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/deors.wordpress.com/324/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=deors.wordpress.com&amp;blog=21758442&amp;post=324&amp;subd=deors&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://deors.wordpress.com/2012/02/22/10000-visits/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d964b48ba3c3366cc967250087401257?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">deors</media:title>
		</media:content>
	</item>
		<item>
		<title>Test Automation with Selenium WebDriver and Selenium Grid – part 3: Continuous Integration</title>
		<link>http://deors.wordpress.com/2012/02/02/selenium-webdriver-grid-3/</link>
		<comments>http://deors.wordpress.com/2012/02/02/selenium-webdriver-grid-3/#comments</comments>
		<pubDate>Thu, 02 Feb 2012 12:06:03 +0000</pubDate>
		<dc:creator>deors</dc:creator>
				<category><![CDATA[Automation]]></category>
		<category><![CDATA[Code Quality]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Test]]></category>
		<category><![CDATA[Cargo]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[JaCoCo]]></category>
		<category><![CDATA[Jenkins]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Oracle VirtualBox]]></category>
		<category><![CDATA[Selenium]]></category>
		<category><![CDATA[Selenium Grid]]></category>
		<category><![CDATA[Selenium WebDriver]]></category>
		<category><![CDATA[Sonar]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Tomcat]]></category>

		<guid isPermaLink="false">http://deors.wordpress.com/?p=292</guid>
		<description><![CDATA[In part 1 in the series (read it here) I discussed about Selenium, the widely used tool for browser test automation, and I showed how easy is to setup a testing grid with multiple OS and browsers. In part 2 (read it &#8230; <a href="http://deors.wordpress.com/2012/02/02/selenium-webdriver-grid-3/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=deors.wordpress.com&amp;blog=21758442&amp;post=292&amp;subd=deors&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In part 1 in the series (read it <a href="http://deors.wordpress.com/2012/02/02/selenium-webdriver-grid-1/">here</a>) I discussed about Selenium, the widely used tool for browser test automation, and I showed how easy is to setup a testing grid with multiple OS and browsers. In part 2 (read it <a href="http://deors.wordpress.com/2012/02/02/selenium-webdriver-grid-2/">here</a>) I showed how to leverage WebDriver API to create and execute tests distributed across the grid that was created.</p>
<p>Now in part 3 I will show how to execute Selenium tests under a Continuous Integration process with Maven, Cargo and Jenkins, and how to gather code coverage metrics for those tests using Sonar and JaCoCo.</p>
<p><span id="more-292"></span></p>
<p>Adding Selenium WebDriver tests to a Continuous Integration process is easy if you know how. When Maven is used for build automation and life-cycle management, having the tests executed is as easy as adding a few configuration lines to the project&#8217;s pom.xml. Actually most of what I am going to show in this post is already published in some previous posts about HtmlUnit (read them <a href="http://deors.wordpress.com/2011/09/30/maven-htmlunit/">here</a> and <a href="http://deors.wordpress.com/2011/10/20/htmlunit-sonar-jacoco/">here</a>) &#8211; the approach is precisely the same. No matter what tool is used to write and execute the tests as long as they run on top of JUnit.</p>
<h2>Reasons for Having Independent Tests</h2>
<p>If you stop to think what are the weakest points about running Selenium tests, as shown in previous posts in the series, most probably you will agree with me that there are two: the Selenium Grid should exist and the application under test should be deployed on an application server, accessible to the test nodes.</p>
<p>Let&#8217;s focus on the second one &#8211; Maven and Cargo will come to the rescue. Things that need to be done are:</p>
<ul>
<li>Configure Maven Failsafe plug-in to automate the execution of the integration tests.</li>
<li>Configure Maven Cargo plug-in to automate the application server provisioning for the tests and to automate the deployment of the application under test. The application server will exist only during the Maven process (embedded runtime).</li>
<li>Optionally, leverage an embedded database. This is out of the scope of this post and actually a subject for another one. In short, use Spring JDBC embedded database support (you can read about this nice feature <a href="http://static.springsource.org/spring-framework/docs/3.0.6.RELEASE/reference/html/jdbc.html#jdbc-embedded-database-support">here</a>).</li>
</ul>
<p>First step is useful to separate unit tests, that run without a container or database, from integration tests, that may need (or not, depending on the integration scope) an existing runtime. Second and third steps are useful to build an integration test suite that is independent from an existing runtime.</p>
<p>Independence is critical to ensure a smooth workflow across the development team and the continuous integration engine. If integration tests require an existing application server and database, two developers (or one developer and the CI engine) would clash if running tests at the same time. Independence is also useful to create tests that do not rely on the previous one to finish successfully. Each test may leverage its own clean database, with the input data that is required to test different code branches and achieve reasonable code coverage. Thus, no matter if a previous test failed and left the database in an inconsistent state. This state is discarded, a new input data set is loaded and thus the feedback from subsequent tests will remain meaningful.</p>
<h2>Configuring Failsafe</h2>
<p>Let&#8217;s start by configuring Maven Failsafe plug-in. Failsafe is no more than a fork to the well known Surefire plug-in that provides a mechanism for differentiating unit tests from integration tests.</p>
<p>Although there is people that prefer having integration tests in a separate Maven artifact, I prefer, if the project is not big or has a simple layout, having them in the same artifact and just differentiate both types of tests with a different name pattern.</p>
<p>A possible configuration would be like this:</p>
<pre>&lt;project...&gt;
  ...
  &lt;build&gt;
    ...
    &lt;plugins&gt;
      ...
      &lt;plugin&gt;
        &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
        &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
        &lt;version&gt;2.8.1&lt;/version&gt;
        &lt;configuration&gt;
          &lt;includes&gt;
            &lt;include&gt;**/test/*TestCase.java&lt;/include&gt;
          &lt;/includes&gt;
        &lt;/configuration&gt;
      &lt;/plugin&gt;
      &lt;plugin&gt;
        &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
        &lt;artifactId&gt;maven-failsafe-plugin&lt;/artifactId&gt;
        &lt;version&gt;2.8.1&lt;/version&gt;
        &lt;configuration&gt;
          &lt;includes&gt;
            &lt;include&gt;**/integrationtest/*IntegrationTestCase.java&lt;/include&gt;
          &lt;/includes&gt;
        &lt;/configuration&gt;
        &lt;executions&gt;
          &lt;execution&gt;
            &lt;id&gt;integration-test&lt;/id&gt;
            &lt;goals&gt;
              &lt;goal&gt;integration-test&lt;/goal&gt;
            &lt;/goals&gt;
          &lt;/execution&gt;
          &lt;execution&gt;
            &lt;id&gt;verify&lt;/id&gt;
            &lt;goals&gt;
              &lt;goal&gt;verify&lt;/goal&gt;
            &lt;/goals&gt;
          &lt;/execution&gt;
        &lt;/executions&gt;
      &lt;/plugin&gt;
      ...
    &lt;/plugins&gt;
    ...
  &lt;/build&gt;
  ...
&lt;/project&gt;</pre>
<p>This configuration will trigger the following actions in a Maven build:</p>
<ul>
<li>Surefire will execute, during unit test phase (default binding), only those test classes which are located in *.test packages and which name ends with TestCase.</li>
<li>Failsafe will execute, during integration-test and verify phase (defined bindings), only those test classes which are located in *.integrationtest packages and which name ends with IntegrationTestCase.</li>
</ul>
<h2>Configuring an Embedded Server with Cargo</h2>
<p>Next step is to configure Cargo for provisioning an embedded server that will be used to host the application under test. Cargo is capable of remotely deploy artifacts to a server, or download and install one locally for the test session if we do not have one available. Cargo can also automatically start and stop the servers (both remote and local). With the appropriate bindings, the star-deploy-test-stop flow can be achieved automatically.</p>
<p>A possible configuration, that provisions a Tomcat 7.0.22 runtime, would be like this:</p>
<pre>&lt;project...&gt;
  ...
  &lt;build&gt;
    ...
    &lt;plugins&gt;
      ...
      &lt;plugin&gt;
        &lt;groupId&gt;org.codehaus.cargo&lt;/groupId&gt;
        &lt;artifactId&gt;cargo-maven2-plugin&lt;/artifactId&gt;
        &lt;version&gt;1.1.4&lt;/version&gt;
        &lt;configuration&gt;
          &lt;container&gt;
            &lt;containerId&gt;tomcat7x&lt;/containerId&gt;
            &lt;zipUrlInstaller&gt;
              &lt;url&gt;http://archive.apache.org/dist/tomcat/tomcat-7/v7.0.22/bin/apache-tomcat-7.0.22.zip&lt;/url&gt;
            &lt;/zipUrlInstaller&gt;
          &lt;/container&gt;
          &lt;configuration&gt;
            &lt;properties&gt;
              &lt;cargo.servlet.port&gt;8180&lt;/cargo.servlet.port&gt;
              &lt;cargo.tomcat.ajp.port&gt;8109&lt;/cargo.tomcat.ajp.port&gt;
            &lt;/properties&gt;
          &lt;/configuration&gt;
        &lt;/configuration&gt;
        &lt;executions&gt;
          &lt;!-- start server before integration tests --&gt;
          &lt;execution&gt;
            &lt;id&gt;start-container&lt;/id&gt;
            &lt;phase&gt;pre-integration-test&lt;/phase&gt;
            &lt;goals&gt;
              &lt;goal&gt;start&lt;/goal&gt;
            &lt;/goals&gt;
          &lt;/execution&gt;
          &lt;!-- stop server after integration tests --&gt;
          &lt;execution&gt;
            &lt;id&gt;stop-container&lt;/id&gt;
            &lt;phase&gt;post-integration-test&lt;/phase&gt;
            &lt;goals&gt;
              &lt;goal&gt;stop&lt;/goal&gt;
            &lt;/goals&gt;
          &lt;/execution&gt;
        &lt;/executions&gt;
      &lt;/plugin&gt;
      ...
    &lt;/plugins&gt;
    ...
  &lt;/build&gt;
  ...
&lt;/project&gt;</pre>
<p>This configuration will trigger the following actions in a Maven build:</p>
<ul>
<li>Cargo start goal is bound to pre-integration-test phase. During this phase, Cargo will download a Tomcat 7.0.22 server an configure it to run on ports 8180 and 8109 (not using the default ports is a good idea to prevent clashing another server process, i.e. Jenkins). After that the application under test is deployed.</li>
<li>Cargo stop goal is bound to post-integration-test phase. During this phase, that runs once Failsafe finishes executing the integration tests, Cargo will stop the Tomcat server.</li>
</ul>
<p>At this point we can execute a Maven build up to verify phase that will run the integration tests against the application hosted in the embedded server. Obviously, the Tomcat server process listening at port 8180 should be visible from test nodes, so watch carefully firewall or proxy settings if nodes cannot connect to the application server.</p>
<p>Only one thing is left: we need to pass the hub and target server URLs into the JUnit processes spawned by Failsafe. If you remember from part 2, when we were to execute the tests from the IDE, we added some system properties to the launcher configuration:</p>
<pre>-Dtest.selenium.hub.url=http://xxxxx:4444/wd/hub
-Dtest.target.server.url=http://xxxxx:8080/sdc.samples.selenium</pre>
<p>If we proceed the same way it will not work &#8211; Failsafe does not propagates system properties to the spawned JUnit processes. To get the job done, we need to leverage the argLine parameter:</p>
<pre>mvn verify -DargLine="
\ -Dtest.selenium.hub.url=http://xxxxx:4444/wd/hub
\ -Dtest.target.server.url=http://xxxxx:8180/sdc.samples.selenium"</pre>
<p>Failsafe will take the argLine parameter value and propagate it to each JUnit process. The application will be packaged and deployed and tests will be executed from the nodes available in our test grid.</p>
<h2>Configuring the Build Job in Jenkins</h2>
<p>To configure the build job in Jenkins no special setup is needed. Just add the verify phase to the Maven goals and add Failsafe&#8217;s argLine parameter (either as a regular option or as part of MAVEN_OPTS definition):</p>
<p><a href="http://deors.files.wordpress.com/2012/02/sel5.png"><img class="alignnone size-full wp-image-305" title="sel5" src="http://deors.files.wordpress.com/2012/02/sel5.png?w=584&#038;h=61" alt="" width="584" height="61" /></a></p>
<p>Validate the job configuration by running it from Jenkins dashboard: integration tests should be executed and results shown in Jenkins&#8217; build results page.</p>
<h2>Gathering Code Coverage Metrics with Sonar and JaCoCo</h2>
<p>At this point, gathering code coverage metrics is a simple task:</p>
<ul>
<li>In pom.xml, add a dependency to JaCoCo agent.</li>
<li>In pom.xml, add a command line argument to Tomcat startup to attach JaCoCo agent to it.</li>
<li>In pom.xml, add sonar.jacoco.itReportPath property telling Sonar where the coverage report can be found.</li>
<li>In Jenkins job configuration, be sure the Sonar&#8217;s post build action is enabled.</li>
</ul>
<p>The dependency entry is added to the project&#8217;s pom:</p>
<pre>&lt;project...&gt;
  ...
  &lt;dependencies&gt;
    ... 
    &lt;dependency&gt;
      &lt;groupId&gt;org.jacoco&lt;/groupId&gt;
      &lt;artifactId&gt;org.jacoco.agent&lt;/artifactId&gt;
      &lt;version&gt;0.5.5.201112152213&lt;/version&gt;
      &lt;type&gt;jar&lt;/type&gt;
      &lt;classifier&gt;runtime&lt;/classifier&gt;
      &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    ...
  &lt;/dependencies&gt;
  ...
&lt;/project&gt;</pre>
<p>The command line argument is added to Tomcat startup:</p>
<pre>&lt;project...&gt;
  ...
  &lt;build&gt;
    ...
    &lt;plugins&gt;
      ...
      &lt;plugin&gt;
        &lt;groupId&gt;org.codehaus.cargo&lt;/groupId&gt;
        &lt;artifactId&gt;cargo-maven2-plugin&lt;/artifactId&gt;
        ...
          &lt;configuration&gt;
            &lt;properties&gt;
              &lt;cargo.servlet.port&gt;8180&lt;/cargo.servlet.port&gt;
              &lt;cargo.tomcat.ajp.port&gt;8109&lt;/cargo.tomcat.ajp.port&gt;
              &lt;cargo.jvmargs&gt;-javaagent:${settings.localRepository}/org/jacoco/org.jacoco.agent/0.5.5.201112152213/org.jacoco.agent-0.5.5.201112152213-runtime.jar=destfile=${project.build.directory}/itest.jacoco&lt;/cargo.jvmargs&gt;
            &lt;/properties&gt;
          &lt;/configuration&gt;
        ...
      &lt;/plugin&gt;
      ...
    &lt;/plugins&gt;
    ...
  &lt;/build&gt;
  ...
&lt;/project&gt;</pre>
<p>JaCoCo&#8217;s code coverage report is passed into Sonar:</p>
<pre>&lt;project...&gt;
  ...
  &lt;properties&gt;
    &lt;sonar.jacoco.itReportPath&gt;
      ${project.build.directory}/itest.jacoco
    &lt;/sonar.jacoco.itReportPath&gt;
  &lt;/properties&gt;
  ...
&lt;/project&gt;</pre>
<p>And finally, enable Sonar&#8217;s post build action in Jenkins job configuration page:</p>
<p><a href="http://deors.files.wordpress.com/2012/02/sel6.png"><img class="alignnone size-full wp-image-306" title="sel6" src="http://deors.files.wordpress.com/2012/02/sel6.png?w=584" alt=""   /></a></p>
<p>Once changes in configuration are done, launch the Jenkins job again and after a few minutes you should see the project analyzed in Sonar dashboard, including code coverage for Selenium integration tests. Awesome!</p>
<p><a href="http://deors.files.wordpress.com/2012/02/sel7.png"><img class="alignnone size-full wp-image-307" title="sel7" src="http://deors.files.wordpress.com/2012/02/sel7.png?w=584" alt=""   /></a></p>
<h2>Conclusion</h2>
<p>Praise for Selenium is well deserved. Selenium, through WebDriver and Grid components, provides a powerful mechanism to automate browser tests. Tests can be easily distributed across a grid allowing multi-browser, multi-OS testing. Tests can be easily created and executed within our favorite IDEs and added to a Continuous Integration process, including code coverage metrics for Selenium tests.</p>
<p>Selenium helps to achieve important productivity improvements. The time invested in writing an automated test is rapidly returned by the fact that no effort is needed to re-execute them. Moreover, being automated, it is likely that they will be execute more often that if they were manual, contributing to increase the quality and predictability of our software releases.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/deors.wordpress.com/292/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/deors.wordpress.com/292/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/deors.wordpress.com/292/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/deors.wordpress.com/292/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/deors.wordpress.com/292/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/deors.wordpress.com/292/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/deors.wordpress.com/292/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/deors.wordpress.com/292/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/deors.wordpress.com/292/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/deors.wordpress.com/292/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/deors.wordpress.com/292/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/deors.wordpress.com/292/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/deors.wordpress.com/292/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/deors.wordpress.com/292/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=deors.wordpress.com&amp;blog=21758442&amp;post=292&amp;subd=deors&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://deors.wordpress.com/2012/02/02/selenium-webdriver-grid-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d964b48ba3c3366cc967250087401257?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">deors</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2012/02/sel5.png" medium="image">
			<media:title type="html">sel5</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2012/02/sel6.png" medium="image">
			<media:title type="html">sel6</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2012/02/sel7.png" medium="image">
			<media:title type="html">sel7</media:title>
		</media:content>
	</item>
		<item>
		<title>Test Automation with Selenium WebDriver and Selenium Grid – part 2: Creating and Executing Tests</title>
		<link>http://deors.wordpress.com/2012/02/02/selenium-webdriver-grid-2/</link>
		<comments>http://deors.wordpress.com/2012/02/02/selenium-webdriver-grid-2/#comments</comments>
		<pubDate>Thu, 02 Feb 2012 12:05:08 +0000</pubDate>
		<dc:creator>deors</dc:creator>
				<category><![CDATA[Automation]]></category>
		<category><![CDATA[Code Quality]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Test]]></category>
		<category><![CDATA[Cargo]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[JaCoCo]]></category>
		<category><![CDATA[Jenkins]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Oracle VirtualBox]]></category>
		<category><![CDATA[Selenium]]></category>
		<category><![CDATA[Selenium Grid]]></category>
		<category><![CDATA[Selenium WebDriver]]></category>
		<category><![CDATA[Sonar]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Tomcat]]></category>

		<guid isPermaLink="false">http://deors.wordpress.com/?p=254</guid>
		<description><![CDATA[In part 1 in the series (read it here) I presented Selenium, a widely known tool for browser test automation. Starting with Selenium 2, the most important components from the suite are Selenium WebDriver and Selenium Grid. In part 1 &#8230; <a href="http://deors.wordpress.com/2012/02/02/selenium-webdriver-grid-2/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=deors.wordpress.com&amp;blog=21758442&amp;post=254&amp;subd=deors&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In part 1 in the series (read it <a href="http://deors.wordpress.com/2012/02/02/selenium-webdriver-grid-1/">here</a>) I presented Selenium, a widely known tool for browser test automation.</p>
<p>Starting with Selenium 2, the most important components from the suite are Selenium WebDriver and Selenium Grid. In part 1 I showed how easy is to setup a testing grid with multiple OS and browsers. Now in part 2 I will show how to leverage WebDriver API to create and execute tests.</p>
<p><span id="more-254"></span></p>
<h2>A Brief History of WebDriver</h2>
<p>WebDriver was born under Google sponsorship around 2009 as a totally separated framework from what it was Selenium at the time. WebDriver&#8217;s <em>raison d&#8217;être</em> was to prevent some issues that Selenium 1 and other browser test automation tools had, because of their JavaScript based approach. The sandbox model of JavaScript engines usually limits what stuff can be automated from a script, just to secure the browser and the underlying OS from malicious scripts.</p>
<p>WebDriver is based on different &#8216;drivers&#8217;, understood as components to interact as close as possible with each different browser, may it be an automation interface or a browser extension.</p>
<p>This approach allows better interaction with the browser, closer to how a human being would interact with it. For example, instead of changing the text on a field with JavaScript, the driver is capable of simulating key press events, exactly as it would be if a human was typing the text in the field.</p>
<p>In addition to that, WebDriver API is probably cleaner, simpler to use.</p>
<p>With all of that in mind, both communities decided to merge efforts.</p>
<h2>Preparing the Environment</h2>
<p>Our playground will consist of a simple web application built with JSP, JSTL, Spring Framework/MVC and Hibernate. The IDE in use is Eclipse Indigo SR1 with SpringSource plug-ins and other stuff installed. Apache Maven 2 is used for build automation and dependency management.</p>
<p>If using Maven, preparation is immediate, just add the dependency with selenium-java artifact:</p>
<pre>&lt;dependency&gt;
    &lt;groupId&gt;org.seleniumhq.selenium&lt;/groupId&gt;
    &lt;artifactId&gt;selenium-java&lt;/artifactId&gt;
    &lt;version&gt;2.16.1&lt;/version&gt;
    &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;</pre>
<p>This artifact contains the WebDriver API for Java, along with Selenium 1 API for backwards compatibility. This API exists for other languages as C#, Ruby or Python as well.</p>
<h2>Configuring Test Parameters</h2>
<p>Each test will follow a similar process: connect to the hub, tell it where the target application is, what browser to use and the actual test commands. As a best practice I recommend that both the hub connection information and the target application location are configurable and externally provided. If not, the test code or test configuration (i.e. a properties file) should be updated if the hub or the test server changes. Moreover, it is critical for a successful deployment of a test suite across the team and continuous integration to provide these settings externally.</p>
<p>A pattern suggested is to provide both settings as environment variables or system properties. Code could be like this:</p>
<pre>public class CodesIntegrationTestCase {
    private static final Logger logger =
        LoggerFactory.getLogger(CodesIntegrationTestCase.class);
    private static String SELENIUM_HUB_URL;
    private static String TARGET_SERVER_URL;

    @BeforeClass
    public static void initEnvironment() {
        SELENIUM_HUB_URL = getConfigurationProperty(
           "SELENIUM_HUB_URL",
           "test.selenium.hub.url",
           "http://localhost:4444/wd/hub");
        logger.info("using Selenium hub at: " + SELENIUM_HUB_URL);

        TARGET_SERVER_URL = getConfigurationProperty(
            "TARGET_SERVER_URL",
            "test.target.server.url",
            "http://localhost:8080/sdc.samples.selenium");
        logger.info("using target server at: " + TARGET_SERVER_URL);
    }

    private static String getConfigurationProperty(
            String envKey, String sysKey, String defValue) {
        String retValue = defValue;
        String envValue = System.getenv(envKey);
        String sysValue = System.getProperty(sysKey);
        // system property prevails over environment variable
        if (sysValue != null) {
            retValue = sysValue;
        } else if (envValue != null) {
            retValue = envValue;
        }
        return retValue;
    }</pre>
<h2>Configuring the Browsers</h2>
<p>Next step to write the tests is to decide in which browsers each test will run. Election can be as detailed as needed. You can just decide on the browser family or be precise and request and specific browser version in a certain operating system. Either the case, when the test reaches the hub, it will find an available node with the requested capabilities and delegate the test execution to it.</p>
<p>To do that, just leverage the org.openqa.selenium.remote.DesiredCapabilities class or even better its factory methods.</p>
<p>If a test would need to be executed in a Mozilla Firefox browser, just use this statement:</p>
<pre>DesiredCapabilities browser = DesiredCapabilities.firefox();</pre>
<p>If you need to test inside a Microsoft Internet Explorer browser:</p>
<pre>DesiredCapabilities browser = DesiredCapabilities.internetExplorer();</pre>
<p>In the case you need more control, you can be more specific. For example to request an Opera 11 browser in a Linux OS, you could use:</p>
<pre>DesiredCapabilities browser = DesiredCapabilities.opera();
browser.setVersion("11");
browser.setPlatform(Platform.LINUX);</pre>
<h2>Reusing Test Code for Cross-Browser Compatibility Tests</h2>
<p>In many situations it is desirable that the same test is executed in different browsers and OS mixes. If that is the case, it is a best practice to reuse the test code and provide the browser as a parameter. It is also a best practice to use different test methods for each browser. Thus, in case of test error or failure, you will have immediate feedback on which is browser where the test failed.</p>
<p>A suggested code pattern could be like this:</p>
<pre>    @Test
    public void testIE()
            throws MalformedURLException, IOException {
        DesiredCapabilities browser =
            DesiredCapabilities.internetExplorer();
        testCodesCrud(browser);
    }

    @Test
    public void testFirefox()
            throws MalformedURLException, IOException {
        DesiredCapabilities browser =
            DesiredCapabilities.firefox();
        testCodesCrud(browser);
    }

    @Test
    public void testChrome()
            throws MalformedURLException, IOException {
        DesiredCapabilities browser =
            DesiredCapabilities.chrome();
        testCodesCrud(browser);
    }

    @Test
    public void testOpera()
            throws MalformedURLException, IOException {
        DesiredCapabilities browser =
            DesiredCapabilities.opera();
        testCodesCrud(browser);
    }</pre>
<p>The four test methods, one for a different browser family, is effectively reusing the same test code inside the testCodesCrud() method. The browser is passed as a parameter to the test.</p>
<h2>Contacting the Hub and Initiating the Test</h2>
<p>Next step in the test code is to instantiate a WebDriver to contact with the hub, ask for a browser and initiate the test commands by accessing the application under test in the URL where it is available. It is best practice to always close the driver, for example using a finally block to do that. Closing the driver will, among other things, close the browser process in the remote node.</p>
<p>A suggested pattern for writing the test code would be like this:</p>
<pre>    public void testCodesCrud(DesiredCapabilities browser)
            throws MalformedURLException, IOException {
        WebDriver driver = null;
        try {
            driver = new RemoteWebDriver(
                new URL(SELENIUM_HUB_URL), browser);

            // test starts in Codes entity list page
            driver.get(TARGET_SERVER_URL + "/CodesView.do");

            // rest of test commands come here
        } finally {
            if (driver != null) {
                driver.quit();
            }
        }
    }</pre>
<h2>Interacting with the Browser</h2>
<p>Although the WebDriver API is rich, most of the times the test code will just find elements and interact with them using simple methods as sendKeys() or click(). Elements on a page can be located by name, id, class, tag or XPath expression.</p>
<p>Let&#8217;s imagine that our test would like to verify that the initial listing on the Codes entity contains three values and that those three are &#8220;A&#8221;, &#8220;C&#8221; and &#8220;D&#8221;. The test code would be like this:</p>
<pre>    // confirm initial data list
    List&lt;WebElement&gt; codeElems = driver.findElements(By.name("code"));
    List&lt;String&gt; codes = new ArrayList&lt;String&gt;();
    for (WebElement codeElem : codeElems) {
        codes.add(codeElem.getAttribute("value"));
    }

    assertEquals(3, codes.size());
    assertTrue(codes.contains("A"));
    assertTrue(codes.contains("C"));
    assertTrue(codes.contains("D"));</pre>
<p>To interact with form controls, as buttons, the process is analogous: find the element and issue a simple command to it:</p>
<pre>    // get add button
    WebElement addForm = driver.findElement(By.name("add"));
    WebElement addButton = addForm.findElement(By.name("add"));

    // submit to add a new record
    addButton.click();</pre>
<p>It is a best practice to add some delay time when loading a new page. With this approach, the test is protected from failing if the new page does not load immediately while ensuring that the right page is loaded in a timely manner using a time out:</p>
<pre>    // wait up to 10 seconds for the Codes detail page to load
    (new WebDriverWait(driver, 10)).until(
        new ExpectedCondition&lt;Boolean&gt;() {
            public Boolean apply(WebDriver d) {
                // the expected condition in this case
                // is the new page title 
                return d.getTitle().equals("Codes Detail Page");
            }
        });</pre>
<p>Once the detail page is loaded, there is an empty form to add a new Codes entity. Interacting with this form is easy with the WebElement interface:</p>
<pre>    WebElement detailForm = driver.findElement(By.name("detail"));
    WebElement codeField = detailForm.findElement(By.name("code"));
    codeField.sendKeys("P");
    WebElement valueField = detailForm.findElement(By.name("value"));
    valueField.sendKeys("postponed");
    // confirm add and return to view page
    WebElement okButton = detailForm.findElement(By.name("ok"));
    okButton.click();</pre>
<p>Alternatively, the submit() method from WebElement interface can be used. This method will just submit the form in which the element is located. Thus, the final two statements could be replaced with:</p>
<pre>    ...
    valueField.sendKeys("postponed");
    // confirm add and return to view page
    valueField.submit();</pre>
<p>For the rest of the test code I just combined what is shown before to verify that new Codes entities can be added, updated and deleted, and each time the listed values are consistent.</p>
<h2>Executing the Test</h2>
<p>Once the test is finished, deploy the application into a local Tomcat server using Eclipse WTP. Once the application is up, the unit test can be executed as usual. Don&#8217;t forget to add the hub and target server URLs as environment variables or system properties to the test launcher configuration:</p>
<pre>-Dtest.selenium.hub.url=http://xxxxx:4444/wd/hub
-Dtest.target.server.url=http://xxxxx:8080/sdc.samples.selenium</pre>
<p><a href="http://deors.files.wordpress.com/2012/02/sel2.png"><img class="alignnone size-full wp-image-266" title="sel2" src="http://deors.files.wordpress.com/2012/02/sel2.png?w=584&#038;h=460" alt="" width="584" height="460" /></a></p>
<p>Once the test is executed, if the node boxes are visible you may see how each browser shows, the application is tested and the browser is closed. Like an <a href="http://www.youtube.com/watch?v=J0-n0fTxu7c">automated piano</a>, pages will show, text will be entered and buttons will be pressed, just like if someone were interacting with the mouse and keyboard:</p>
<p><a href="http://deors.files.wordpress.com/2012/02/sel4-1.png"><img class="alignnone size-full wp-image-268" title="sel4-1" src="http://deors.files.wordpress.com/2012/02/sel4-1.png?w=584" alt=""   /></a></p>
<p><a href="http://deors.files.wordpress.com/2012/02/sel4-2.png"><img class="alignnone size-full wp-image-269" title="sel4-2" src="http://deors.files.wordpress.com/2012/02/sel4-2.png?w=584" alt=""   /></a></p>
<p><a href="http://deors.files.wordpress.com/2012/02/sel4-3.png"><img class="alignnone size-full wp-image-270" title="sel4-3" src="http://deors.files.wordpress.com/2012/02/sel4-3.png?w=584" alt=""   /></a></p>
<p><a href="http://deors.files.wordpress.com/2012/02/sel4-4.png"><img class="alignnone size-full wp-image-271" title="sel4-4" src="http://deors.files.wordpress.com/2012/02/sel4-4.png?w=584" alt=""   /></a></p>
<p><a href="http://deors.files.wordpress.com/2012/02/sel4-5.png"><img class="alignnone size-full wp-image-272" title="sel4-5" src="http://deors.files.wordpress.com/2012/02/sel4-5.png?w=584" alt=""   /></a></p>
<p>At the end, test results will be shown in JUnit view inside Eclipse IDE:</p>
<p><a href="http://deors.files.wordpress.com/2012/02/sel3.png"><img class="alignnone size-full wp-image-267" title="sel3" src="http://deors.files.wordpress.com/2012/02/sel3.png?w=584" alt=""   /></a></p>
<h2>Recap</h2>
<p>In this post I&#8217;ve shown how to write and execute browser tests using Selenium WebDriver and Selenium Grid. Test execution is distributed across nodes in the grid, depending on the available browsers while results are collated by the hub process. Test is launched from Eclipse IDE and results are shown in JUnit view, as with any other regular unit test.</p>
<p>In part 3 (read it <a href="http://deors.wordpress.com/2012/02/02/selenium-webdriver-grid-3/">here</a>), I will show how to execute the Selenium test just created under Continuous Integration using Maven, Cargo and Jenkins and how to get insights on the code coverage for those tests with Sonar and JaCoCo.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/deors.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/deors.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/deors.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/deors.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/deors.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/deors.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/deors.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/deors.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/deors.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/deors.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/deors.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/deors.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/deors.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/deors.wordpress.com/254/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=deors.wordpress.com&amp;blog=21758442&amp;post=254&amp;subd=deors&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://deors.wordpress.com/2012/02/02/selenium-webdriver-grid-2/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d964b48ba3c3366cc967250087401257?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">deors</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2012/02/sel2.png" medium="image">
			<media:title type="html">sel2</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2012/02/sel4-1.png" medium="image">
			<media:title type="html">sel4-1</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2012/02/sel4-2.png" medium="image">
			<media:title type="html">sel4-2</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2012/02/sel4-3.png" medium="image">
			<media:title type="html">sel4-3</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2012/02/sel4-4.png" medium="image">
			<media:title type="html">sel4-4</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2012/02/sel4-5.png" medium="image">
			<media:title type="html">sel4-5</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2012/02/sel3.png" medium="image">
			<media:title type="html">sel3</media:title>
		</media:content>
	</item>
		<item>
		<title>Test Automation with Selenium WebDriver and Selenium Grid – part 1: Setting Up the Grid</title>
		<link>http://deors.wordpress.com/2012/02/02/selenium-webdriver-grid-1/</link>
		<comments>http://deors.wordpress.com/2012/02/02/selenium-webdriver-grid-1/#comments</comments>
		<pubDate>Thu, 02 Feb 2012 12:03:18 +0000</pubDate>
		<dc:creator>deors</dc:creator>
				<category><![CDATA[Automation]]></category>
		<category><![CDATA[Code Quality]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Test]]></category>
		<category><![CDATA[Cargo]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[JaCoCo]]></category>
		<category><![CDATA[Jenkins]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Oracle VirtualBox]]></category>
		<category><![CDATA[Selenium]]></category>
		<category><![CDATA[Selenium Grid]]></category>
		<category><![CDATA[Selenium WebDriver]]></category>
		<category><![CDATA[Sonar]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Tomcat]]></category>

		<guid isPermaLink="false">http://deors.wordpress.com/?p=232</guid>
		<description><![CDATA[For a long while I&#8217;ve been &#8220;dying to play&#8221; with Selenium (www.seleniumhq.org and code.google.com/p/selenium/). I&#8217;ve heard and read very good things about this tool from colleagues and from the blogosphere. Selenium is, in short, an open source tool to automate web browser &#8230; <a href="http://deors.wordpress.com/2012/02/02/selenium-webdriver-grid-1/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=deors.wordpress.com&amp;blog=21758442&amp;post=232&amp;subd=deors&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>For a long while I&#8217;ve been &#8220;dying to play&#8221; with Selenium (<a href="http://www.seleniumhq.org" target="_blank">www.seleniumhq.org</a> and <a href="http://code.google.com/p/selenium/" target="_blank">code.google.com/p/selenium/</a>). I&#8217;ve heard and read very good things about this tool from colleagues and from the blogosphere.</p>
<p>Selenium is, in short, an open source tool to automate web browser interactions. A primary use case is, of course, browser test automation.</p>
<p>Selenium has greatly evolved with time, specially since the 2.0 release when the legacy Selenium project merged with Google&#8217;s WebDriver. Nowadays, Selenium offers a wide range of programming languages supported to write the tests, an impressive browser compatibility list, the ability to record tests from user interactions and, above it all in my opinion, the ability to re-execute tests across a grid of machines with various operating systems, browser families and versions.</p>
<p>Although Selenium seems to be primarily chosen for functional/regression test automation, it&#8217;s also a great choice &#8211; precisely because of the grid feature &#8211; for cross-browser compatibility testing: ensuring in an easy, cost-effective way, that our web applications are usable in all sorts of operating systems and browsers.</p>
<p>In this and forthcoming posts in a short series I will share my experiences setting up a Selenium Grid, building some automated tests for a simple Spring application, re-executing them from Eclipse IDE and finally re-executing them in continuous integration (including code coverage) with Maven, Cargo, Jenkins, Sonar and JaCoCo.</p>
<p><span id="more-232"></span></p>
<h2>Setting Up the Grid</h2>
<p>First of all I wanted to start by building the grid: a number of virtual machines with different operating systems and browsers ready to be used to re-execute Selenium tests. Yes, you can re-execute the tests locally but then it would be limited to your OS and the browsers installed in your PC. Thinking on mid-to-large projects, it makes more sense to have some spare capacities that can be shared across developers, with a wider coverage of OS-browser mixes.</p>
<p>A Selenium Grid is very easy to create and configure. In my case, I took an old dual-core PC upgraded to 4 GB of RAM and Oracle VirtualBox. Running as &#8216;headless&#8217; virtual machines with remote display activated, I created three virtual machines:</p>
<ol>
<li>Selenium Slave1. Windows XP 32-bit box, 1 GB RAM. This box has IE 8 and Chrome 16 browsers installed on it and will act as a node for test execution.</li>
<li>Selenium Slave2. Ubuntu 11.10 32-bit box, 1 GB RAM. This box has Firefox 9 and Opera 11.61 browsers installed on it and will act as a node for test execution.</li>
<li>Selenium Hub. Ubuntu 11.10 32-bit box, 1 GB RAM. This box will act as the hub, the controller of the grid.</li>
</ol>
<p>Once I installed all chosen browsers, I downloaded the Selenium Server component from their website, exactly the file <a href="http://code.google.com/p/selenium/downloads/detail?name=selenium-server-standalone-2.16.1.jar&amp;can=1&amp;q=" target="_blank">selenium-server-standalone-2.16.1.jar</a>, and saved it in a handy place, as c:\selenium-2.16.1 or $HOME/selenium-2.16.1. I also downloaded and installed JDK 7 update 2 32-bit in each box.</p>
<p>For the Windows box I also needed to download the chromedriver component. chromedriver is a standalone executable needed to automate interactions with Google&#8217;s browser that is developed separately in another project hosted in Google Code here: <a href="http://code.google.com/p/chromedriver/" target="_blank">code.google.com/p/chromedriver/</a>. I downloaded the latest release at <a href="http://code.google.com/p/chromedriver/downloads/detail?name=chromedriver_win_18.0.1022.0.zip&amp;can=2&amp;q=" target="_blank">chromedriver_win_18.0.1022.0.zip</a> and extracted it under c:\selenium-2.16.1 as well. Finally I added c:\selenium-2.16.1 to the box PATH (it should be accessible to the server process).</p>
<h2>Launching the Hub</h2>
<p>Once the three boxes were ready, I launched the hub process. Our tests will interact with the hub, asking for available capabilities in a certain OS, browser and version. The different nodes (even the hub itself if it has spare capacity and browsers available) will register with this hub and will be available for future test executions. Capabilities can be optimized for parallel processing, for example 5 Chrome browsers, 2 Firefox browsers on some box and 2 Safari browsers on some other.</p>
<p>To launch the hub process simply issue a command like this (or place it in a shell/batch script for later):</p>
<pre>java -jar selenium-2.16.1/selenium-server-standalone-2.16.1.jar
\ -role hub -port 4444</pre>
<p>The port parameter is optional and actually 4444 is the default port for the hub role. After a few seconds, the process will start the daemon and will wait for the nodes to register and tests to come.</p>
<h2>Registering the Nodes</h2>
<p>For the nodes, the process is quite similar but you will need to pass the hub URL and what browsers are available.</p>
<p>In our environment, the Windows XP box has IE 8 and Chrome installed. Therefore the launch command would be like this:</p>
<pre>java -jar selenium-2.16.1\selenium-server-standalone-2.16.1.jar
\ -role node -port 5555 -hub http://xxxxx.61:4444/grid/register
\ -browser "browserName=internet explorer,version=8,platform=WINDOWS"
\ -browser browserName=chrome,platform=WINDOWS</pre>
<p>The port parameter is again optional and 5555 is the default port for the node role.</p>
<p>Note how the browser parameter is used (more than once if needed) to tell the hub about the available browsers. Note as well that you may need to &#8216;escape&#8217; the browser string value if there are spaces. Also noteworthy, you may add version information but it is not required. In my opinion IE version is really critical for cross-browser matters but in other browsers it is not so important.</p>
<p>Now it&#8217;s the turn for the second node. In this case the command will look like this:</p>
<pre>java -jar selenium-2.16.1/selenium-server-standalone-2.16.1.jar
\ -role node -port 5555 -hub http://xxxxx.61:4444/grid/register
\ -browser browserName=firefox,platform=LINUX
\ -browser browserName=opera,platform=LINUX</pre>
<p>Finally, I verified that the nodes were properly registered. The hub has a simple console with basic information about the available nodes at the URL:</p>
<pre>http://xxxxx.61:4444/grid/console</pre>
<p>The console output will look like this:</p>
<p><a href="http://deors.files.wordpress.com/2012/01/sel1.png"><img class="alignnone size-full wp-image-236" title="sel1" src="http://deors.files.wordpress.com/2012/01/sel1.png?w=584" alt=""   /></a></p>
<p>And that&#8217;s all. We&#8217;re done setting up the grid!</p>
<h2>Recap</h2>
<p>In this post I&#8217;ve discussed a bit about Selenium and shown how easy is to set up a grid for test execution with Selenium Grid. In part 2 (read it <a href="http://deors.wordpress.com/2012/02/02/selenium-webdriver-grid-2/">here</a>) I will explore Selenium WebDriver for writing and launching web UI automated tests.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/deors.wordpress.com/232/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/deors.wordpress.com/232/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/deors.wordpress.com/232/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/deors.wordpress.com/232/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/deors.wordpress.com/232/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/deors.wordpress.com/232/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/deors.wordpress.com/232/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/deors.wordpress.com/232/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/deors.wordpress.com/232/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/deors.wordpress.com/232/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/deors.wordpress.com/232/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/deors.wordpress.com/232/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/deors.wordpress.com/232/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/deors.wordpress.com/232/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=deors.wordpress.com&amp;blog=21758442&amp;post=232&amp;subd=deors&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://deors.wordpress.com/2012/02/02/selenium-webdriver-grid-1/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d964b48ba3c3366cc967250087401257?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">deors</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2012/01/sel1.png" medium="image">
			<media:title type="html">sel1</media:title>
		</media:content>
	</item>
		<item>
		<title>First Steps with Micro Cloud Foundry</title>
		<link>http://deors.wordpress.com/2012/01/27/micro-cloud-foundry/</link>
		<comments>http://deors.wordpress.com/2012/01/27/micro-cloud-foundry/#comments</comments>
		<pubDate>Fri, 27 Jan 2012 15:52:22 +0000</pubDate>
		<dc:creator>deors</dc:creator>
				<category><![CDATA[Cloud Computing]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Oracle VirtualBox]]></category>
		<category><![CDATA[VMware Cloud Foundry]]></category>

		<guid isPermaLink="false">http://deors.wordpress.com/?p=204</guid>
		<description><![CDATA[Micro Cloud Foundry is a complete Cloud Foundry installation shipped in a ready to use Virtual Machine. With Micro Cloud Foundry you can work locally in your applications and test how they work integratedly with Cloud Foundry services. Using Micro &#8230; <a href="http://deors.wordpress.com/2012/01/27/micro-cloud-foundry/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=deors.wordpress.com&amp;blog=21758442&amp;post=204&amp;subd=deors&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Micro Cloud Foundry is a complete Cloud Foundry installation shipped in a ready to use Virtual Machine.</p>
<p>With Micro Cloud Foundry you can work locally in your applications and test how they work integratedly with Cloud Foundry services.</p>
<p>Using Micro Cloud Foundry during development is highly recommended for any serious work. It is not practical to have multiple people working on the same application and constantly deploying to the same public or private Cloud Foundry instance (e.g. hosted in Amazon EC2 or hosted in a VMware vSphere environment). Instead, developers would use local Micro Cloud Foundry instances for build and test and then a dedicated Micro Cloud Foundry or Cloud Foundry instance for integration testing.</p>
<p>In this post I will show how to get, configure and start to work with Micro Cloud Foundry.</p>
<p><span id="more-204"></span></p>
<h2>How to Obtain a Micro Cloud Foundry</h2>
<p>Micro Cloud Foundry instances are free but their distribution is controlled. The process starts by applying for a Micro Cloud Foundry instance at:</p>
<p style="text-align:center;"><a href="http://cloudfoundry.com/micro">http</a><a href="http://cloudfoundry.com/micro">://</a><a href="http://cloudfoundry.com/micro">cloudfoundry.com/micro</a></p>
<p>You  will need to provide a unique domain name in the form:</p>
<p style="text-align:center;">&lt;my-domain&gt;.cloudfoundry.me</p>
<p>If the name for the domain is available, you will get it assigned to your account along with a configuration token that will be needed to configure the Micro Cloud Foundry instance.</p>
<h2>Configuring Micro Cloud Foundry</h2>
<p>Next step is to download Micro Cloud Foundry and start it.</p>
<p>Micro Cloud Foundry comes ready to be used with VMware products but can be used as well with other virtualization tools. In my case I prefer to work with Oracle VirtualBox, so I just created a new empty VM with these settings:</p>
<ul>
<li>OS Ubuntu 64-bits</li>
<li>1 GB RAM</li>
<li>2 CPU</li>
<li>Bridged Adapter (Intel/PRO 1000 MT Desktop)</li>
</ul>
<p>Then, attach the Micro Cloud Foundry hard disk from the downloaded file (it has the VMDK extension) to the VM and start it. After a few seconds, Micro Cloud Foundry will show its configuration screen.</p>
<p><a href="http://deors.files.wordpress.com/2012/01/mcf1.png"><img class="alignnone size-full wp-image-206" title="mcf1" src="http://deors.files.wordpress.com/2012/01/mcf1.png?w=584&#038;h=498" alt="" width="584" height="498" /></a></p>
<p>Configuration steps are:</p>
<ul>
<li>Select 1 to start configuration</li>
<li>Enter the administrator password twice (it will be assigned to the &#8220;root&#8221; and &#8220;vcap&#8221; users in the underlying Ubuntu)</li>
<li>Select 1 to configure DHCP</li>
<li>Enter the proxy configuration (if needed)</li>
<li>Enter the configuration token that you received a moment ago to confirm the domain name</li>
</ul>
<p><a href="http://deors.files.wordpress.com/2012/01/mcf2.png"><img class="alignnone size-full wp-image-207" title="mcf2" src="http://deors.files.wordpress.com/2012/01/mcf2.png?w=584&#038;h=498" alt="" width="584" height="498" /></a></p>
<p>After finishing configuration, DNS settings are propagated. DNS settings are needed for the clients to connect to this Micro Cloud Foundry instance.</p>
<p>Pay attention if using NAT and also to firewall software because the clients may not be able to connect to Micro Cloud Foundry. Also pay attention to DHCP’s with short lease time. If the instance IP is changing too quickly, DNS settings may not get properly updated.</p>
<p><a href="http://deors.files.wordpress.com/2012/01/mcf3.png"><img class="alignnone size-full wp-image-208" title="mcf3" src="http://deors.files.wordpress.com/2012/01/mcf3.png?w=584&#038;h=498" alt="" width="584" height="498" /></a></p>
<p>After DNS finishes, Micro Cloud Foundry individual services are installed and started. Ready to go!</p>
<p><a href="http://deors.files.wordpress.com/2012/01/mcf4.png"><img class="alignnone size-full wp-image-209" title="mcf4" src="http://deors.files.wordpress.com/2012/01/mcf4.png?w=584&#038;h=498" alt="" width="584" height="498" /></a></p>
<p><a href="http://deors.files.wordpress.com/2012/01/mcf51.png"><img class="alignnone size-full wp-image-215" title="mcf5" src="http://deors.files.wordpress.com/2012/01/mcf51.png?w=584&#038;h=498" alt="" width="584" height="498" /></a></p>
<p>If you feel curious, issuing a &#8217;12&#8242; command into Micro Cloud Foundry console will allow you access to the underlying Ubuntu server. Lots of possibilities in there, right?</p>
<h2>Deployment to Micro Cloud Foundry</h2>
<p>Deployment process to Micro Cloud Foundry mirrors the process for the public Cloud Foundry instance. The only real difference is in the target API:</p>
<p style="padding-left:30px;">&gt;vmc target http://api.sdcassets.cloudfoundry.me<br />
&gt;vmc register<br />
&gt;vmc login<br />
&gt;vmc create-service mysql vmcfirst-db<br />
&gt;vmc push vmcfirst</p>
<p>The &#8216;register&#8217; command is needed because we are not a registered user in this Micro Cloud Foundry instance. We may register as many users as needed in our instance.</p>
<p>The process can be done using the Eclipse plug-in as shown in my previous post for the public Cloud Foundry instance <a title="here" href="http://deors.wordpress.com/2011/11/04/vmware-cloud-foundry/">here</a>.</p>
<p><a href="http://deors.files.wordpress.com/2012/01/mcf81.png"><img class="alignnone size-full wp-image-218" title="mcf8" src="http://deors.files.wordpress.com/2012/01/mcf81.png?w=584&#038;h=438" alt="" width="584" height="438" /></a></p>
<p>If using the command line, remember to issue the push command from the directory where you have your exploded WAR, for example as generated by Maven package goal.</p>
<p>In a few seconds, the application should be up and running in your Micro Cloud Foundry. Enjoy!</p>
<h2>Conclusion</h2>
<p>As easy as it gets. All the power of the Cloud Foundry platform at your hands to play with.</p>
<p>With Micro Cloud Foundry, you can successfully build a development team targeting Cloud Foundry. Privacy and security concerns relax as you may have it running concealed in your own premises or just live in your PC.</p>
<p>It&#8217;s so easy that is hard to say &#8216;no&#8217; and don&#8217;t give it a try. What are you waiting for? Chuck Norris&#8217; &#8220;I-approve-this-cloud&#8221; ad?</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/deors.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/deors.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/deors.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/deors.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/deors.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/deors.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/deors.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/deors.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/deors.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/deors.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/deors.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/deors.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/deors.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/deors.wordpress.com/204/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=deors.wordpress.com&amp;blog=21758442&amp;post=204&amp;subd=deors&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://deors.wordpress.com/2012/01/27/micro-cloud-foundry/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d964b48ba3c3366cc967250087401257?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">deors</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2012/01/mcf1.png" medium="image">
			<media:title type="html">mcf1</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2012/01/mcf2.png" medium="image">
			<media:title type="html">mcf2</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2012/01/mcf3.png" medium="image">
			<media:title type="html">mcf3</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2012/01/mcf4.png" medium="image">
			<media:title type="html">mcf4</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2012/01/mcf51.png" medium="image">
			<media:title type="html">mcf5</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2012/01/mcf81.png" medium="image">
			<media:title type="html">mcf8</media:title>
		</media:content>
	</item>
		<item>
		<title>2012: New year and new look</title>
		<link>http://deors.wordpress.com/2012/01/18/2012-new-year-and-new-look/</link>
		<comments>http://deors.wordpress.com/2012/01/18/2012-new-year-and-new-look/#comments</comments>
		<pubDate>Wed, 18 Jan 2012 14:17:29 +0000</pubDate>
		<dc:creator>deors</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://deors.wordpress.com/?p=188</guid>
		<description><![CDATA[A new year, and a new look. This one is lighter, simpler, I think. Hope you like it! &#8212;&#8212;&#8212;- Nuevo año, y estrenamos nuevo look. Este es más claro y sencillo, creo. ¡Espero que os guste!<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=deors.wordpress.com&amp;blog=21758442&amp;post=188&amp;subd=deors&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A new year, and a new look. This one is lighter, simpler, I think. Hope you like it!</p>
<p>&#8212;&#8212;&#8212;-</p>
<p>Nuevo año, y estrenamos nuevo <em>look</em>. Este es más claro y sencillo, creo. ¡Espero que os guste!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/deors.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/deors.wordpress.com/188/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/deors.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/deors.wordpress.com/188/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/deors.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/deors.wordpress.com/188/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/deors.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/deors.wordpress.com/188/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/deors.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/deors.wordpress.com/188/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/deors.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/deors.wordpress.com/188/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/deors.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/deors.wordpress.com/188/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=deors.wordpress.com&amp;blog=21758442&amp;post=188&amp;subd=deors&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://deors.wordpress.com/2012/01/18/2012-new-year-and-new-look/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d964b48ba3c3366cc967250087401257?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">deors</media:title>
		</media:content>
	</item>
		<item>
		<title>2011 in review</title>
		<link>http://deors.wordpress.com/2012/01/02/2011-in-review/</link>
		<comments>http://deors.wordpress.com/2012/01/02/2011-in-review/#comments</comments>
		<pubDate>Mon, 02 Jan 2012 12:16:15 +0000</pubDate>
		<dc:creator>deors</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[annual report]]></category>

		<guid isPermaLink="false">http://deors.wordpress.com/?p=181</guid>
		<description><![CDATA[The WordPress.com stats helper monkeys prepared a 2011 annual report for this blog. Here&#8217;s an excerpt: A San Francisco cable car holds 60 people. This blog was viewed about 3,500 times in 2011. If it were a cable car, it &#8230; <a href="http://deors.wordpress.com/2012/01/02/2011-in-review/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=deors.wordpress.com&amp;blog=21758442&amp;post=181&amp;subd=deors&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The WordPress.com stats helper monkeys prepared a 2011 annual report for this blog.</p>
<p><a href="/2011/annual-report/"><img src="http://www.wordpress.com/wp-content/mu-plugins/annual-reports/img/emailteaser.jpg" alt="" width="100%" /></a></p>
<p>Here&#8217;s an excerpt:</p>
<blockquote><p>A San Francisco cable car holds 60 people. This blog was viewed about <strong>3,500</strong> times in 2011. If it were a cable car, it would take about 58 trips to carry that many people.</p></blockquote>
<p><a href="/2011/annual-report/">Click here to see the complete report.</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/deors.wordpress.com/181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/deors.wordpress.com/181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/deors.wordpress.com/181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/deors.wordpress.com/181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/deors.wordpress.com/181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/deors.wordpress.com/181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/deors.wordpress.com/181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/deors.wordpress.com/181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/deors.wordpress.com/181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/deors.wordpress.com/181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/deors.wordpress.com/181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/deors.wordpress.com/181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/deors.wordpress.com/181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/deors.wordpress.com/181/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=deors.wordpress.com&amp;blog=21758442&amp;post=181&amp;subd=deors&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://deors.wordpress.com/2012/01/02/2011-in-review/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d964b48ba3c3366cc967250087401257?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">deors</media:title>
		</media:content>

		<media:content url="http://www.wordpress.com/wp-content/mu-plugins/annual-reports/img/emailteaser.jpg" medium="image" />
	</item>
		<item>
		<title>Red Hat OpenShift: Freedom of Choice</title>
		<link>http://deors.wordpress.com/2011/12/13/red-hat-openshift/</link>
		<comments>http://deors.wordpress.com/2011/12/13/red-hat-openshift/#comments</comments>
		<pubDate>Tue, 13 Dec 2011 20:23:38 +0000</pubDate>
		<dc:creator>deors</dc:creator>
				<category><![CDATA[Cloud Computing]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[JBoss]]></category>
		<category><![CDATA[JBoss Tools]]></category>
		<category><![CDATA[OpenShift]]></category>
		<category><![CDATA[Red Hat]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://deors.wordpress.com/?p=157</guid>
		<description><![CDATA[1         Introduction After we finished writing the post on VMware Cloud Foundry platform, it seemed natural to write a follow-up on Red Hat OpenShift. OpenShift is a Java-based Platform-as-a-Service (PaaS) offering from Red Hat, the ‘giant’ of Open Source Software &#8230; <a href="http://deors.wordpress.com/2011/12/13/red-hat-openshift/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=deors.wordpress.com&amp;blog=21758442&amp;post=157&amp;subd=deors&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h1>1         Introduction</h1>
<p>After we finished writing the post on VMware Cloud Foundry platform, it seemed natural to write a follow-up on Red Hat OpenShift. OpenShift is a Java-based Platform-as-a-Service (PaaS) offering from Red Hat, the ‘giant’ of Open Source Software with a well-deserved reputation that comes from a wide range of products including operating systems (Fedora, Red Hat Enterprise Linux), application servers / middleware (JBoss AS, JBoss ESB), frameworks (Hibernate, Seam) and tools (JBoss Tools, Arquillian).</p>
<p>As a PaaS offering, the ultimate goal of OpenShift is to reduce the effort needed to write and deploy highly scalable and highly available Java applications. Under your dedicated “application space” the platform components run to ensure your application is able to respond to user’s requests, but isolating your application code from the infrastructure and all the complexity usually associated with complex, distributed deployments.</p>
<p>Let’s jump into OpenShift!</p>
<p><span id="more-157"></span></p>
<div>
<h1>2         Red Hat OpenShift</h1>
</div>
<p>OpenShift was born after Red Hat’s acquisition of Makara in 2010. Makara is a state-of-the-art technology for building highly scalable solutions that was integrated with Red Hat flagships RHEL and JBoss to become the core of the OpenShift platform.</p>
<p>The first fact that really got our attention and positively increased our interest in the platform – above the usual PaaS stuff – is the statement used as the title for the post: Freedom of choice. No matter if you are a Java developer and your favorite framework is Spring, Seam or just the Java EE specification; no matter if you prefer Ruby, PHP, Perl or Python. OpenShift supports all these technologies.</p>
<p>OpenShift as an offering comes in three flavors: Express, Flex and Power. Express is a free to use platform for Java, Ruby, PHP, Perl or Python technologies, easy to setup and easy to use. Flex is a full cloud management solution that operates on top of Amazon EC2, dynamically managing clusters and applications, scaling up and down as needed. Power is the most flexible solution in which you can go down to the OS level and build up cloud services on any Linux-based solution.</p>
<p>For the rest of this post we will show how to start working with OpenShift Express, prepare an existing Java with Spring application and deploy it to the cloud. We will be using Eclipse IDE Java EE bundle on a Windows workstation to work on the application and test it locally, plus OpenShift command-line tools to configure and manage the cloud deployment.</p>
<div>
<h1>3         Preparing the Tool Set</h1>
</div>
<p>OpenShift client tools are a collection of Ruby-based scripts. With them you can interact with OpenShift and with your application.</p>
<p>According to Express setup instructions page <a href="https://openshift.redhat.com/app/express#win">here</a>, you need to install Cygwin (<a href="http://www.cygwin.com/">http://www.cygwin.com/</a>), some Cygwin packages (including Ruby and Git) plus RubyGems and then, finally, install Red Hat OpenShift gems.</p>
<p>But we are Windows geeks, so there is no point in going through Cygwin to interact with OpenShift. Actually, this is one of the many advantages of Ruby: The same Ruby script can be executed from a Linux shell, Windows shell or inside the Java Virtual Machine.</p>
<p>So, first step, if you do not have a Ruby runtime already installed, is to go to <a href="http://www.rubyinstaller.org/">http://www.rubyinstaller.org/</a> and download the Ruby Zipped distribution. Then, decompress it to a folder that I will refer as %RUBY_HOME%. From a command prompt, move to %RUBY_HOME%/bin directory and issue the following commands:</p>
<p style="padding-left:30px;">&gt;set http_proxy=&lt;your-proxy-info&gt;<br />
<em>          Needed if you are behind a proxy, use the right one for your network or skip this command</em><br />
&gt;gem install rhc<br />
<em>          Install the Red Hat OpenShift gem</em></p>
<p>You will also need a Git client to upload changes to your OpenShift application space. Git is a popular software configuration management tool and it is used by OpenShift to track changes on artifacts uploaded to the application space. Go to <a href="http://code.google.com/p/msysgit/">http://code.google.com/p/msysgit/</a> and download the Git Zipped distribution. Then, decompress it to a folder that I will refer as %GIT_HOME%. I recommend reading a bit about Git and basic commands so you are in good shape to interact with your remote repository at OpenShift.</p>
<p>I also recommend adding both %RUBY_HOME%/bin and %GIT_HOME%/bin to the path.</p>
<div>
<h1>4         Creating a Domain and the Application Space</h1>
</div>
<p>Once we have installed the needed tools, it’s time to create a domain and an application space. A domain is a unique identifier for all your applications. Inside the domain we will have one or many application spaces, and each one will have an associated Git repository to where we will push our updates to the deployed application. Each push will trigger the necessary actions for doing so automatically.</p>
<p>Both the domain and application identifiers are part of the application URL, so choose wisely. The format is:</p>
<p style="padding-left:30px;">http://&lt;app-name&gt;-&lt;domain-name&gt;.rhcloud.com</p>
<p>To create the domain issue the following command:</p>
<p style="padding-left:30px;">&gt;rhc-create-domain -n &lt;domain-name&gt; -l &lt;login-email-address&gt;</p>
<p>The login email address identifies you and you will be prompted to enter your password. Once introduced, the console will show your SSH key identification. It will be saved in your %HOME%/.ssh folder and used from now on to secure communications to your domain. The default login information is saved in %HOME%/.openshift/ express.conf so you do not need to provide your login email address each time you issue a command to control your domain.</p>
<p>Next step is to create the application space. For that, issue the following commands:</p>
<p style="padding-left:30px;">&gt;cd &lt;project-home-directory&gt;<br />
<em>          You will need to create a directory where the application will be locally stored</em><br />
&gt;rhc-create-app -a &lt;app-name&gt; -t jbossas-7.0<br />
<em>          Provide the application name and the type of the application</em></p>
<p>This command will create the remote Git repository and add the application URL to the DNS so users may access it from the Internet. The remote Git repository URL is showed in the command output, in the case you need to supply it to another tool.</p>
<p>With this we have created a JBoss AS 7.0 Java application. OpenShift is taking care of provisioning the server runtime and needed resources. Other types include Ruby (rack-1.1) or PHP (php-5.3) applications. In all cases the platform provides everything needed to start running the application. You can check the list of available types in OpenShift documentation <a href="http://docs.redhat.com/docs/en-US/OpenShift_Express/2.0/html/User_Guide/sect-User_Guide-Application_Development-Creating_Applications.html">here</a>.</p>
<div>
<h1>5         Deployment to the Cloud</h1>
</div>
<p>Now that our environment is ready, let’s discuss about what changes need to be done on an existing Java with Spring application to be deployed there.</p>
<p>The reference application is a very simple one: web interface using JSP and JSTL, plus Spring 3 and Hibernate. It is currently configured to use an embedded HSQLDB database for data persistent storage. The application is working locally deployed in a JBoss AS 7.0.2 runtime.</p>
<p><a href="http://deors.files.wordpress.com/2011/12/rhc1.png"><img class="alignnone size-full wp-image-159" title="rhc1" src="http://deors.files.wordpress.com/2011/12/rhc1.png?w=584" alt=""   /></a></p>
<p><a href="http://deors.files.wordpress.com/2011/12/rhc2.png"><img class="alignnone size-full wp-image-160" title="rhc2" src="http://deors.files.wordpress.com/2011/12/rhc2.png?w=584" alt=""   /></a></p>
<h2>5.1        Adding Support for MySQL</h2>
<p>The first adaptation that we are going to do is to add support for MySQL to our application.</p>
<p>Each application in OpenShift may have services associated to it. Each service is named a Cartridge. For our needs we are going to add a MySQL database cartridge to the application. To do that, remember the given application name and issue the following command:</p>
<p style="padding-left:30px;">&gt;rhc-ctl-app -a &lt;app-name&gt; -e add-mysql-5.1</p>
<p>The console will show a message confirming the creation of the MySQL database, the root user credentials, the database name (should be the same as the application name) and the connection URL.</p>
<h2>5.2        Updating Spring configuration</h2>
<p>Our next step is to update the Spring configuration thus the application can make use of the MySQL database. To do that, you may replace the existing data source configuration with the URL and credentials received when the MySQL cartridge was created or rely on some environment variables that are created by OpenShift platform. Using environment variables is the recommended way to configure database access. This way it is easy to test the application locally just by providing values to a locally available MySQL database:</p>
<p><a href="http://deors.files.wordpress.com/2011/12/rhc3.png"><img class="alignnone size-full wp-image-161" title="rhc3" src="http://deors.files.wordpress.com/2011/12/rhc3.png?w=584" alt=""   /></a></p>
<p>The environment variables used are self-explanatory:</p>
<pre style="padding-left:30px;">OPENSHIFT_DB_HOST
OPENSHIFT_DB_PORT
OPENSHIFT_APP_NAME
OPENSHIFT_DB_USERNAME
OPENSHIFT_DB_PASSWORD</pre>
<h2>5.3        Running the Application</h2>
<p>Once the changes have been made it is time to commit all the files and make our first push to OpenShift.</p>
<p>Assuming that you’ve placed all application files in the project home directory used when the application was created, just issue the following commands to commit all files and push them to the remote Git repository:</p>
<p style="padding-left:30px;">&gt;git commit -a -m &#8220;initial version&#8221;<br />
&gt;git push</p>
<p>The contents will be uploaded and then a Maven build process will trigger. Sources will be compiled, packaged and deployed in a few seconds and after that, the application is ready to be used!</p>
<p><a href="http://deors.files.wordpress.com/2011/12/rhc4.png"><img class="alignnone size-full wp-image-162" title="rhc4" src="http://deors.files.wordpress.com/2011/12/rhc4.png?w=584" alt=""   /></a></p>
<h2>5.4        Useful Commands to Control your Applications</h2>
<p>These are some useful command that will allow you to control your applications:</p>
<p style="padding-left:30px;">&gt;rhc-user-info<br />
<em>          Show basic information about applications available in your domain:<br />
names, types, Git URL, application URL and cartridges<br />
</em>&gt;rhc-ctl-app -a &lt;app-name&gt; -c status<br />
<em>          Show the application status, including a tail from its log</em><br />
&gt;rhc-ctl-app -a &lt;app-name&gt; -c start|stop|reload|restart<br />
<em>          Starts, stops, reloads and restarts the application<br />
</em>&gt;rhc-snapshot -a &lt;app-name&gt; -s &lt;file-name&gt;.tgz<br />
<em>          Downloads the application files, including full logs, for troubleshooting</em></p>
<div>
<h1>6         JBoss Tools Support for OpenShift</h1>
</div>
<p>Recently Red Hat announced a new release of their popular JBoss Tools suite for Eclipse that included support for OpenShift. If you do not feel comfortable while working with command line tools or just prefer the improved experience of having everything at one click distance in your favorite IDE, then this section is for you.</p>
<p>Let’s assume that we already have an application deployed to OpenShift and a blank Eclipse workspace. First, let’s install the OpenShift support from JBoss Tools. For example, for Indigo, add the following Eclipse update site and add JBoss OpenShift Express Tools feature:</p>
<p style="padding-left:30px;"><a href="http://download.jboss.org/jbosstools/updates/development/indigo">http://download.jboss.org/jbosstools/updates/development/indigo</a></p>
<p><a href="http://deors.files.wordpress.com/2011/12/rhc5.png"><img class="alignnone size-full wp-image-163" title="rhc5" src="http://deors.files.wordpress.com/2011/12/rhc5.png?w=584" alt=""   /></a></p>
<p>Once installed, we will have available a new wizard named OpenShift Express Application. Let’s create a new project of this type:</p>
<p><a href="http://deors.files.wordpress.com/2011/12/rhc6.png"><img class="alignnone size-full wp-image-164" title="rhc6" src="http://deors.files.wordpress.com/2011/12/rhc6.png?w=584" alt=""   /></a></p>
<p>Next, enter your OpenShift credentials and select the domain and application to import it into Eclipse.</p>
<p><a href="http://deors.files.wordpress.com/2011/12/rhc71.png"><img class="alignnone size-full wp-image-172" title="rhc7" src="http://deors.files.wordpress.com/2011/12/rhc71.png?w=584" alt=""   /></a></p>
<p><a href="http://deors.files.wordpress.com/2011/12/rhc8.png"><img class="alignnone size-full wp-image-166" title="rhc8" src="http://deors.files.wordpress.com/2011/12/rhc8.png?w=584" alt=""   /></a></p>
<p>Then, review the application details and specify, if desired, the target folder for the project. You may as well create a new JBoss server runtime if you do not have already one in your workspace. Once done, the Git remote repository for the application will be cloned into your workspace:</p>
<p><a href="http://deors.files.wordpress.com/2011/12/rhc9.png"><img class="alignnone size-full wp-image-167" title="rhc9" src="http://deors.files.wordpress.com/2011/12/rhc9.png?w=584" alt=""   /></a></p>
<p>Now, to verify that everything is working fine, let’s make a trivial change, commit it and push it to OpenShift for deployment:</p>
<p><a href="http://deors.files.wordpress.com/2011/12/rhc10.png"><img class="alignnone size-full wp-image-168" title="rhc10" src="http://deors.files.wordpress.com/2011/12/rhc10.png?w=584" alt=""   /></a></p>
<p><a href="http://deors.files.wordpress.com/2011/12/rhc11.png"><img class="alignnone size-full wp-image-169" title="rhc11" src="http://deors.files.wordpress.com/2011/12/rhc11.png?w=584" alt=""   /></a></p>
<p>Once the push is finished the updated application will be redeployed:</p>
<p><a href="http://deors.files.wordpress.com/2011/12/rhc12.png"><img class="alignnone size-full wp-image-170" title="rhc12" src="http://deors.files.wordpress.com/2011/12/rhc12.png?w=584" alt=""   /></a></p>
<p>Easy, right?</p>
<div>
<h1>7         Conclusion</h1>
</div>
<p>Red Hat OpenShift is a Cloud platform based on Red Hat Enterprise Linux and JBoss Application Server that allows Java, Ruby, PHP or Python web applications run on Cloud premises with high flexibility and scalability. Existing applications will need only minor configuration changes to be ready for OpenShift. Moreover, OpenShift can be easily integrated with the popular Eclipse IDE for developers productivity increase.</p>
<p>In the forthcoming months we will surely have confirmation on enterprise-ready commercial offerings sitting on this great platform, and hopefully it will make the jump to private infrastructures as well.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/deors.wordpress.com/157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/deors.wordpress.com/157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/deors.wordpress.com/157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/deors.wordpress.com/157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/deors.wordpress.com/157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/deors.wordpress.com/157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/deors.wordpress.com/157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/deors.wordpress.com/157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/deors.wordpress.com/157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/deors.wordpress.com/157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/deors.wordpress.com/157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/deors.wordpress.com/157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/deors.wordpress.com/157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/deors.wordpress.com/157/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=deors.wordpress.com&amp;blog=21758442&amp;post=157&amp;subd=deors&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://deors.wordpress.com/2011/12/13/red-hat-openshift/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d964b48ba3c3366cc967250087401257?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">deors</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/12/rhc1.png" medium="image">
			<media:title type="html">rhc1</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/12/rhc2.png" medium="image">
			<media:title type="html">rhc2</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/12/rhc3.png" medium="image">
			<media:title type="html">rhc3</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/12/rhc4.png" medium="image">
			<media:title type="html">rhc4</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/12/rhc5.png" medium="image">
			<media:title type="html">rhc5</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/12/rhc6.png" medium="image">
			<media:title type="html">rhc6</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/12/rhc71.png" medium="image">
			<media:title type="html">rhc7</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/12/rhc8.png" medium="image">
			<media:title type="html">rhc8</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/12/rhc9.png" medium="image">
			<media:title type="html">rhc9</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/12/rhc10.png" medium="image">
			<media:title type="html">rhc10</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/12/rhc11.png" medium="image">
			<media:title type="html">rhc11</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/12/rhc12.png" medium="image">
			<media:title type="html">rhc12</media:title>
		</media:content>
	</item>
		<item>
		<title>VMware Cloud Foundry: A Cloud Primer</title>
		<link>http://deors.wordpress.com/2011/11/04/vmware-cloud-foundry/</link>
		<comments>http://deors.wordpress.com/2011/11/04/vmware-cloud-foundry/#comments</comments>
		<pubDate>Fri, 04 Nov 2011 13:31:17 +0000</pubDate>
		<dc:creator>deors</dc:creator>
				<category><![CDATA[Cloud Computing]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Spring IDE]]></category>
		<category><![CDATA[SpringSource Tool Suite]]></category>
		<category><![CDATA[VMware Cloud Foundry]]></category>

		<guid isPermaLink="false">http://deors.wordpress.com/?p=133</guid>
		<description><![CDATA[1         Introduction It’s cloudy, today. But I’m not speaking about the weather in northern hemisphere autumn. Cloud Computing, two words that cannot be explained with just a sentence, is now a reality, born to change our (digital) &#8230; <a href="http://deors.wordpress.com/2011/11/04/vmware-cloud-foundry/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=deors.wordpress.com&amp;blog=21758442&amp;post=133&amp;subd=deors&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h1>1         Introduction</h1>
<p>It’s cloudy, today. But I’m not speaking about the weather in northern hemisphere autumn. Cloud Computing, two words that cannot be explained with just a sentence, is now a reality, born to change our (digital) lives.</p>
<p>Cloud Computing may mean different things to different people. For some, it would be having their personal documents, photos and music synchronized “in the cloud” and accessible through their PC or mobile device. For others, it would be being able to run their favorite games and to do their favorite stuff anywhere, anytime. It may be a cost-effective, agile hosting solution, an elastic production environment for databases and application servers, and many, many other things. Google Docs, Picasa, iCloud, Facebook, Twitter, Foursquare, Amazon EC2…</p>
<p>In this article, though, we will be discussing about Cloud Computing as a platform where developers can deploy their highly scalable, highly available solutions. We call this Platform-as-a-Service, or PaaS for short. PaaS also means a lot of things but for us is forgetting about dealing with the OS, the application server, the disc or the memory in the server. You just have your “application space”, where you can upload your solutions, execute them, monitor how they behave and control the amount of resources available to them.</p>
<p>You don’t know where your application physically is, the type of host server, operating system configuration or even how the application server is configured at all. You may certainly know about some or all of this, but it is really not needed to achieve your targets: develop your idea and make it available to your clients (no matter how much or where they are) in a hassle.</p>
<p>VMware Cloud Foundry is one of such platforms.</p>
<p><span id="more-133"></span></p>
<div>
<h1>2         VMware Cloud Foundry</h1>
</div>
<p>Cloud Foundry, <a href="http://www.cloudfoundry.com/">www.cloudfoundry.com</a>, is an open platform sponsored by VMware, born to support multiple frameworks, application servers and even multiple cloud providers. You may think on it as a core product that may be used as a foundation for more advanced cloud services.</p>
<p>Cloud Foundry is open source. This means that you can get and contribute to the platform, build it and run it in your own host. As an open source project it lives at <a href="http://www.cloudfoundry.org/">www.cloudfoundry.org</a>.</p>
<p>From Cloud Foundry site you may download a virtual machine with the live platform (the Micro Cloud Foundry) for your own use or request an account in the public, Internet-wide Cloud Foundry platform. Either one or the other, you will get the ability to run Java with Spring, Ruby on Rails and Sinatra, Groovy, Grails or Scala applications and leverage MySQL, Redis or MongoDB data services.</p>
<p>For the rest of this article we will show how to start working with Cloud Foundry, prepare an existing Java with Spring application and deploy it to the cloud. We will be using Eclipse IDE Java EE bundle with Spring IDE installed on it and the public Cloud Foundry instance, so really no special setup is needed to start working on it.</p>
<div>
<h1>3         Get Ready! Eclipse the Cloud!</h1>
</div>
<p>The first step is to request an account in Cloud Foundry site. Currently Cloud Foundry is in beta status and in theory access is granted as soon as VMware grows the existing public premises, thus the ‘request an invite’ label. In practice, access is granted quickly and you will receive an initial password by mail.</p>
<h2>3.1        Changing the Initial Password with Cloud Foundry Ruby gems</h2>
<p>My recommendation is to change that password. Cloud Foundry can be controlled through Ruby gems or through Eclipse plug-ins. Although the Eclipse plug-ins are the easiest way to work on the code, deploy and test applications, some tasks needs the Ruby scripts, so let’s start by installing them.</p>
<p>As I use Windows, I downloaded the Zipped distribution from <a href="http://www.rubyinstaller.org/">http://www.rubyinstaller.org/</a> and place it in a folder that I will refer as %RUBY_HOME%. From a command prompt, move to %RUBY_HOME%/bin directory (yes, it’s Windows, but you can use forward slashes as well) and issue the following commands:</p>
<p>&gt;set http_proxy=&lt;your-proxy-info&gt;<br />
<em>     Needed if you are behind a proxy, use the right one for your network or skip this command</em><br />
&gt;gem install vmc<br />
<em>     Install the VMware Cloud Foundry gem</em><br />
&gt;vmc target api.cloudfoundry.com<br />
<em>     This is the public Cloud Foundry instance</em><br />
&gt;vmc login<br />
<em>     Enter the credentials received by mail</em><br />
&gt;vmc password<br />
<em><em>     </em>Enter the new password twice and it’s done!</em></p>
<h2>3.2        Install the Cloud Foundry support into Eclipse IDE</h2>
<p>Next step is to install the Cloud Foundry plug-ins to control our application space from Eclipse IDE. To do that, the easiest way is, inside the IDE, go to Eclipse Marketplace (<em>Help -&gt; Eclipse Marketplace</em> menu), search for “Cloud Foundry” and install the feature appropriate for the Eclipse version (Helios or Indigo are supported):</p>
<p><a href="http://deors.files.wordpress.com/2011/11/vmw1.png"><img class="alignnone size-full wp-image-135" title="vmw1" src="http://deors.files.wordpress.com/2011/11/vmw1.png?w=584" alt=""   /></a></p>
<p>Once installed, create a new server inside Eclipse. You will now have a new server type available:</p>
<p><a href="http://deors.files.wordpress.com/2011/11/vmw2.png"><img class="alignnone size-full wp-image-136" title="vmw2" src="http://deors.files.wordpress.com/2011/11/vmw2.png?w=584" alt=""   /></a></p>
<p>Enter your credentials (don’t forget the new password) and keep selected the public Cloud Foundry instance:</p>
<p><a href="http://deors.files.wordpress.com/2011/11/vmw31.png"><img class="alignnone size-full wp-image-155" title="vmw3" src="http://deors.files.wordpress.com/2011/11/vmw31.png?w=584" alt=""   /></a></p>
<p>You can at this moment select the applications to be deployed into your application space, but for now we will not add anything there. Click the <em>Finish</em> button to save the server and return to the workbench.</p>
<div>
<h1>4         Deployment to the Cloud</h1>
</div>
<p>Now that our environment is ready to support Cloud Foundry, let’s discuss about what changes need to be done on an existing Java with Spring application to be deployed there.</p>
<p>The reference application is a very simple one: web interface using JSP and JSTL, plus Spring MVC and Hibernate. It is currently configured to use an embedded HSQLDB database for data persistent storage.</p>
<p><a href="http://deors.files.wordpress.com/2011/11/vmw4.png"><img class="alignnone size-full wp-image-138" title="vmw4" src="http://deors.files.wordpress.com/2011/11/vmw4.png?w=584" alt=""   /></a></p>
<p><a href="http://deors.files.wordpress.com/2011/11/vmw5.png"><img class="alignnone size-full wp-image-139" title="vmw5" src="http://deors.files.wordpress.com/2011/11/vmw5.png?w=584" alt=""   /></a></p>
<p><a href="http://deors.files.wordpress.com/2011/11/vmw6.png"><img class="alignnone size-full wp-image-140" title="vmw6" src="http://deors.files.wordpress.com/2011/11/vmw6.png?w=584" alt=""   /></a></p>
<h2>4.1        Adding Support for MySQL</h2>
<p>The first adaptation that we are going to do is to add support for MySQL to our application. Open the server configuration page in Eclipse (double-click on server name, this is the server created before in 3.2) and move to the <em>Applications</em> tab:</p>
<p><a href="http://deors.files.wordpress.com/2011/11/vmw7.png"><img class="alignnone size-full wp-image-141" title="vmw7" src="http://deors.files.wordpress.com/2011/11/vmw7.png?w=584" alt=""   /></a></p>
<p>To add the application, click the button on the <em>Application</em> header, select the application from the available list and click <em>Finish</em>. In the next dialog, you will need to assign a name to the application. This name should not be in use in the public instance. You may as well select the memory assigned to the application. In our case the default 512 MB are Ok:</p>
<p><a href="http://deors.files.wordpress.com/2011/11/vmw8.png"><img class="alignnone size-full wp-image-142" title="vmw8" src="http://deors.files.wordpress.com/2011/11/vmw8.png?w=584" alt=""   /></a></p>
<p>Now we have the application ready to be deployed, but still not services are associated to it:</p>
<p><a href="http://deors.files.wordpress.com/2011/11/vmw9.png"><img class="alignnone size-full wp-image-143" title="vmw9" src="http://deors.files.wordpress.com/2011/11/vmw9.png?w=584" alt=""   /></a></p>
<p>Now click the button on the <em>Services</em> header. Give a name to the service and select “MySQL database service” in the drop-down list:</p>
<p><a href="http://deors.files.wordpress.com/2011/11/vmw10.png"><img class="alignnone size-full wp-image-144" title="vmw10" src="http://deors.files.wordpress.com/2011/11/vmw10.png?w=584" alt=""   /></a></p>
<p>Finally, drag the service from the <em>Services</em> header to the <em>Application Services</em> header to bind it to the application:</p>
<p><a href="http://deors.files.wordpress.com/2011/11/vmw11.png"><img class="alignnone size-full wp-image-145" title="vmw11" src="http://deors.files.wordpress.com/2011/11/vmw11.png?w=584" alt=""   /></a></p>
<h2>4.2        Updating Spring configuration</h2>
<p>Our next step is to update the Spring configuration thus the application can make use of the MySQL database. This is a very simple step, as actually the platform is able to inject the data source at runtime. To do that, replace the data source bean definition for the following:</p>
<pre>&lt;cloud:data-source id="dataSource"/&gt;</pre>
<p>And add this schema to the XML:</p>
<pre>xmlns:cloud="http://schema.cloudfoundry.org/spring"
 xsi:schemaLocation="…&lt;your existing schemas&gt;…http://schema.cloudfoundry.org/spring http://schema.cloudfoundry.org/spring/cloudfoundry-spring-0.6.xsd”</pre>
<h2>4.3        Running the Application</h2>
<p>Surprisingly, that’s all. We are ready to deploy the application into Cloud Foundry. Just run the application as you would do with any regular server and after a few seconds you will see your application living in the cloud!</p>
<p><a href="http://deors.files.wordpress.com/2011/11/vmw12.png"><img class="alignnone size-full wp-image-146" title="vmw12" src="http://deors.files.wordpress.com/2011/11/vmw12.png?w=584" alt=""   /></a></p>
<p><a href="http://deors.files.wordpress.com/2011/11/vmw13.png"><img class="alignnone size-full wp-image-147" title="vmw13" src="http://deors.files.wordpress.com/2011/11/vmw13.png?w=584" alt=""   /></a></p>
<p><a href="http://deors.files.wordpress.com/2011/11/vmw14.png"><img class="alignnone size-full wp-image-148" title="vmw14" src="http://deors.files.wordpress.com/2011/11/vmw14.png?w=584" alt=""   /></a></p>
<p><a href="http://deors.files.wordpress.com/2011/11/vmw15.png"><img class="alignnone size-full wp-image-149" title="vmw15" src="http://deors.files.wordpress.com/2011/11/vmw15.png?w=584" alt=""   /></a></p>
<h2>4.4        Basic Monitoring</h2>
<p>The deployed application can be monitored, at least up to some extent, from the server page in Eclipse. The page will get updated with some basic metrics as instances in use, CPU usage, memory usage, disk usage and live time:</p>
<p><a href="http://deors.files.wordpress.com/2011/11/vmw16.png"><img class="alignnone size-full wp-image-150" title="vmw16" src="http://deors.files.wordpress.com/2011/11/vmw16.png?w=584" alt=""   /></a></p>
<div>
<h1>5         Conclusion</h1>
</div>
<p>It is very easy to start working with Cloud Foundry platform. Your existing code would run there with little or no changes at all. Configuration is also very straightforward.</p>
<p>Although in their current beta status, Cloud Foundry is a very interesting platform, powerful and flexible. It is difficult to say how much time will be needed until it is ready for enterprise-wide deployments with thousands of users and wide geographical dispersion, but surely we will see commercial offerings based on the platform in the following months.</p>
<p>Jump into the cloud! Are you ready?</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/deors.wordpress.com/133/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/deors.wordpress.com/133/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/deors.wordpress.com/133/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/deors.wordpress.com/133/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/deors.wordpress.com/133/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/deors.wordpress.com/133/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/deors.wordpress.com/133/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/deors.wordpress.com/133/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/deors.wordpress.com/133/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/deors.wordpress.com/133/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/deors.wordpress.com/133/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/deors.wordpress.com/133/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/deors.wordpress.com/133/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/deors.wordpress.com/133/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=deors.wordpress.com&amp;blog=21758442&amp;post=133&amp;subd=deors&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://deors.wordpress.com/2011/11/04/vmware-cloud-foundry/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d964b48ba3c3366cc967250087401257?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">deors</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/11/vmw1.png" medium="image">
			<media:title type="html">vmw1</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/11/vmw2.png" medium="image">
			<media:title type="html">vmw2</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/11/vmw31.png" medium="image">
			<media:title type="html">vmw3</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/11/vmw4.png" medium="image">
			<media:title type="html">vmw4</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/11/vmw5.png" medium="image">
			<media:title type="html">vmw5</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/11/vmw6.png" medium="image">
			<media:title type="html">vmw6</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/11/vmw7.png" medium="image">
			<media:title type="html">vmw7</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/11/vmw8.png" medium="image">
			<media:title type="html">vmw8</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/11/vmw9.png" medium="image">
			<media:title type="html">vmw9</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/11/vmw10.png" medium="image">
			<media:title type="html">vmw10</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/11/vmw11.png" medium="image">
			<media:title type="html">vmw11</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/11/vmw12.png" medium="image">
			<media:title type="html">vmw12</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/11/vmw13.png" medium="image">
			<media:title type="html">vmw13</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/11/vmw14.png" medium="image">
			<media:title type="html">vmw14</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/11/vmw15.png" medium="image">
			<media:title type="html">vmw15</media:title>
		</media:content>

		<media:content url="http://deors.files.wordpress.com/2011/11/vmw16.png" medium="image">
			<media:title type="html">vmw16</media:title>
		</media:content>
	</item>
		<item>
		<title>Code Generation using Annotation Processors in the Java language – part 3: Generating Source Code</title>
		<link>http://deors.wordpress.com/2011/10/31/annotation-generators/</link>
		<comments>http://deors.wordpress.com/2011/10/31/annotation-generators/#comments</comments>
		<pubDate>Mon, 31 Oct 2011 21:34:59 +0000</pubDate>
		<dc:creator>deors</dc:creator>
				<category><![CDATA[Automation]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Annotation Processors]]></category>
		<category><![CDATA[Annotations]]></category>
		<category><![CDATA[Code Generation]]></category>
		<category><![CDATA[MDD]]></category>
		<category><![CDATA[MDE]]></category>
		<category><![CDATA[Model-Driven Development]]></category>
		<category><![CDATA[Model-Driven Engineering]]></category>
		<category><![CDATA[Velocity]]></category>

		<guid isPermaLink="false">http://deors.wordpress.com/?p=126</guid>
		<description><![CDATA[This post is the third and final part in my series about Code Generation using Annotation Processors in the Java language. In part 1 (read it here) we introduced what Annotations are in the Java language and some of their common &#8230; <a href="http://deors.wordpress.com/2011/10/31/annotation-generators/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=deors.wordpress.com&amp;blog=21758442&amp;post=126&amp;subd=deors&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This post is the third and final part in my series about Code Generation using Annotation Processors in the Java language. In part 1 (read it <a href="http://deors.wordpress.com/2011/09/26/annotation-types/">here</a>) we introduced what Annotations are in the Java language and some of their common uses. In part 2 (read it <a href="http://deors.wordpress.com/2011/10/08/annotation-processors/">here</a>) we introduced Annotation Processors, how to build them and how to run them.</p>
<p>Now, in part 3, we are going to show how an Annotation Processor can be used to generate source code.</p>
<h2><span id="more-126"></span>Code Generation using Annotation Processors in the Java language – part 3: Generating Source Code</h2>
<p>Generating source code is easy. Generating the right code is not. And doing it in an elegant and efficient way can be a cumbersome task!</p>
<p>Fortunately, in the last years Model-Driven Engineering (1) (MDE, sometimes referred also as Model-Driven Development or Model-Driven Architecture) has helped to evolve a practice that was more art than science – task for ninja coders – into a mature methodology strongly based on proven processes and tools.</p>
<p>Model-Drive Engineering is much more than generating source code, although we can think of it as a natural entry point to MDE methodologies.</p>
<p>Annotation Processors is one of the many tools that we may use to generate source code.</p>
<h4>Model and Meta-model in MDE</h4>
<p>Before going into the details on how to generate source code using Annotation Processors, there is a couple of concepts that we would like to present, as we will be referring to them in the following slides: models and meta-models.</p>
<p>One of the pillars of MDE is the construction of abstractions. We model the software system that we intent to build at different levels of detail and with different approaches. When one level of abstraction is modeled, we can start to model the next one and the next, ending with a complete, deployable product.</p>
<p>In this context, a model is no more than the abstraction that we use to represent our system, whatever level of detail we are using.</p>
<p>The meta-model, then, are the rules that we use to write our models. You can think of it as the schema or semantics of models.</p>
<h4>Generating source code with Annotation Processors</h4>
<p>From what we have seen until now, Annotations are an excellent way for defining a meta-model and creating models. Annotation Types will act as meta-models, while a set of Annotations in a given piece of code will act as a model.</p>
<p>We can leverage this model to generate configuration files or to write new source files that are derived from one existing. For example, create a remoting proxy or a data access object from an annotated bean.</p>
<p>The central piece in this approach is the Annotation Processor. A processor will be able to read annotations found in source code – that is, extract the model – and do whatever we need to do with it – open a file, put contents on it. The Java Compiler will take care of validating the model (annotations should match the defined types).</p>
<h4>The Filer</h4>
<p>As discussed in part 2, every processor have access to a processing environment that points to some interesting utilities. One of them is the Filer.</p>
<p>The <strong>javax.annotation.processing.Filer</strong> (2) interface contract defines some methods for creating source files, class files or generic resources. By using the Filer we can be sure of using the right directories and that we are not losing valuable generated items in our file system.</p>
<p>This concern is critical if we want to write generators that honors -d and -s options in javac or directories defined in a Maven POM.</p>
<p>The following example shows how to create a Java source file inside an Annotation Processor. The generated class name will be the same as the annotated class name plus the string “BeanInfo”, as if we were generating a Bean information class:</p>
<pre style="padding-left:30px;"> if (e.getKind() == ElementKind.CLASS) {
     TypeElement classElement = (TypeElement) e;
     PackageElement packageElement =
         (PackageElement) classElement.getEnclosingElement();

     JavaFileObject jfo = processingEnv.getFiler().createSourceFile(
         classElement.getQualifiedName() + "BeanInfo");

     BufferedWriter bw = new BufferedWriter(jfo.openWriter());
     bw.append("package ");
     bw.append(packageElement.getQualifiedName());
     bw.append(";");
     bw.newLine();
     bw.newLine();
     // rest of generated class contents</pre>
<h4>Don’t Generate Like my Brother</h4>
<p>The previous example is simple, interesting, but a mess!</p>
<p>We are mixing the logic of getting the information we need from annotations (the model) with the logic that writes the generated file (the view).</p>
<p>It is very difficult to write a decent generator in that way. If we need something more complex the task can be cumbersome, error prone and hard to maintain.</p>
<p>We need, therefore, a more elegant approach:</p>
<div>
<ul>
<li>Separate clearly model from view.</li>
<li>Use templates to ease the task of writing down the generated file.</li>
</ul>
</div>
<p>Let&#8217;s see as an example of this approach how to leverage Apache Velocity to build generators the way we want.</p>
<h4>A Brief History of Velocity</h4>
<p><a href="http://velocity.apache.org/">Velocity</a>, a project from the Apache Software Foundation, is a template engine written in Java that produces all types of text files by mixing a template with data from Java objects.</p>
<p>Velocity has been used historically to render views following the popular MVC pattern, or as a substitute to XSLT to transform data in XML files.</p>
<p>Velocity has its own language named the Velocity Template Language (VTL) that is key to produce rich and easy to read templates. In VTL we can define variables, control flow and iterations and access information contained in Java objects in a simple and intuitive way.</p>
<p>Below you can see a fragment of a Velocity Template:</p>
<pre style="padding-left:30px;"> <strong>#foreach($field in $fields)</strong>
     /**
      * Returns the ${field.simpleName} property descriptor.
      *
      * @return the property descriptor
      */
     public PropertyDescriptor ${field.simpleName}PropertyDescriptor() {
         PropertyDescriptor theDescriptor = null;
         return theDescriptor;
     }
 #end
 #foreach($method in $methods)
     /**
      * Returns the <strong>${method.simpleName}</strong>() method descriptor.
      *
      * @return the method descriptor
      */
     public MethodDescriptor ${method.simpleName}MethodDescriptor() {
         MethodDescriptor descriptor = null;</pre>
<p>As you can see, VTL is very straightforward and easy to understand. Highlighted in bold, you can see two typical VTL constructs: iterating a collection of objects and print some property from each element found in the collection.</p>
<h4>The Velocity Generator Approach</h4>
<p>Now that we have decided to use Velocity to enhance our generator, we have to redesign it to follow this schema:</p>
<div>
<ul>
<li>Write the template that will be used to generate the code.</li>
<li>The Annotation Processor will read from the round environment the annotated elements and save them in easy to access Java objects – a map for fields, a map for methods, the class and package names and so forth.</li>
<li>The Annotation Processor will initialize the Velocity context.</li>
<li>The Annotation Processor will load the Velocity template.</li>
<li>The Annotation Processor will create the source file (using the Filer) and pass a writer to it to the Velocity Template, along with the Context.</li>
<li>The Velocity engine will generate the source code.</li>
</ul>
</div>
<p>By following this approach you will find that the processor/generator code is clear, well structured and easy to understand and maintain.</p>
<p>Let&#8217;s proceed step by step.</p>
<h4>Step 1: Write the Template</h4>
<p>For the sake of simplicity we are not going to show a full BeanInfo generator, just a subset of the fields and methods that are actually required will be built with our Processor.</p>
<p>Let&#8217;s create a file named <strong>beaninfo.vm</strong> and place it under the <strong>src/main/resources</strong> of the Maven processor artifact. An example of the contents for the template are:</p>
<pre>package ${packageName};

import java.beans.MethodDescriptor;
import java.beans.ParameterDescriptor;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public class ${className}BeanInfo
    extends java.beans.SimpleBeanInfo {

    /**
     * Gets the bean class object.
     *
     * @return the bean class
     */
    public static Class getBeanClass() {

        return ${packageName}.${className}.class;
    }

    /**
     * Gets the bean class name.
     *
     * @return the bean class name
     */
    public static String getBeanClassName() {

        return "${packageName}.${className}";
    }

    /**
     * Finds the right method by comparing name &amp; number of parameters in the class
     * method list.
     *
     * @param classObject the class object
     * @param methodName the method name
     * @param parameterCount the number of parameters
     *
     * @return the method if found, &lt;code&gt;null&lt;/code&gt; otherwise
     */
    public static Method findMethod(Class classObject, String methodName, int parameterCount) {

        try {
            // since this method attempts to find a method by getting all
            // methods from the class, this method should only be called if
            // getMethod cannot find the method
            Method[] methods = classObject.getMethods();
            for (Method method : methods) {
                if (method.getParameterTypes().length == parameterCount
                    &amp;&amp; method.getName().equals(methodName)) {
                    return method;
                }
            }
        } catch (Throwable t) {
            return null;
        }
        return null;
    }
#foreach($field in $fields)

    /**
     * Returns the ${field.simpleName} property descriptor.
     *
     * @return the property descriptor
     */
    public PropertyDescriptor ${field.simpleName}PropertyDescriptor() {

        PropertyDescriptor theDescriptor = null;
        return theDescriptor;
    }
#end
#foreach($method in $methods)

    /**
     * Returns the ${method.simpleName}() method descriptor.
     *
     * @return the method descriptor
     */
    public MethodDescriptor ${method.simpleName}MethodDescriptor() {

        MethodDescriptor descriptor = null;

        Method method = null;
        try {
            // finds the method using getMethod with parameter types
            // TODO parameterize parameter types
            Class[] parameterTypes = {java.beans.PropertyChangeListener.class};
            method = getBeanClass().getMethod("${method.simpleName}", parameterTypes);

        } catch (Throwable t) {
            // alternative: use findMethod
            // TODO parameterize number of parameters
            method = findMethod(getBeanClass(), "${method.simpleName}", 1);
        }

        try {
            // creates the method descriptor with parameter descriptors
            // TODO parameterize parameter descriptors
            ParameterDescriptor parameterDescriptor1 = new ParameterDescriptor();
            parameterDescriptor1.setName("listener");
            parameterDescriptor1.setDisplayName("listener");
            ParameterDescriptor[] parameterDescriptors = {parameterDescriptor1};
            descriptor = new MethodDescriptor(method, parameterDescriptors);

        } catch (Throwable t) {
            // alternative: create a plain method descriptor
            descriptor = new MethodDescriptor(method);
        }

        // TODO parameterize descriptor properties
        descriptor.setDisplayName("${method.simpleName}(java.beans.PropertyChangeListener)");
        descriptor.setShortDescription("Adds a property change listener.");
        descriptor.setExpert(false);
        descriptor.setHidden(false);
        descriptor.setValue("preferred", false);

        return descriptor;
    }
#end
}</pre>
<p>Note that for this template to work, we will need to pass to Velocity the following information:</p>
<ul>
<li>packageName: the full package name of the generated class</li>
<li>className: the name of the generated class</li>
<li>fields: a collection containing the fields in the source class; for each field we will need:</li>
<ul>
<li>simpleName: the name of the field</li>
<li>type: the type (not used in the example)</li>
<li>description: self-explanatory (not used in the example)</li>
<li>&#8230;</li>
</ul>
<li>methods: a collection containing the methods in the source class; for each method we will need:</li>
<ul>
<li>simpleName: the name of the method</li>
<li>arguments: the method arguments (not used in the example)</li>
<li>returnType: the method return type (not used in the example)</li>
<li>description: self-explanatory (not used in the example)</li>
<li>&#8230;</li>
</ul>
</ul>
<p>All this information (the model) will be extracted from annotations found in the source class and stored in JavaBeans to be passed to Velocity.</p>
<h4>Step 2: The Processor Reads the Model</h4>
<p>Let&#8217;s create the Processor and don&#8217;t forget to annotate it to process a BeanInfo annotation type, as explained in part 2:</p>
<pre style="padding-left:30px;">@SupportedAnnotationTypes("example.annotations.beaninfo.BeanInfo")
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class BeanInfoProcessor
    extends AbstractProcessor {</pre>
<p>The process method will need to extract information needed to build the model from the annotations and the source class itself. You can use JavaBeans to store as much information as needed, but in this example we will leverage <strong>javax.lang.model.element</strong> types as we are not planning to send too much details to Velocity (but would need, in the case we were going to build a full BeanInfo generator):</p>
<pre>            String fqClassName = null;
            String className = null;
            String packageName = null;
            Map&lt;String, VariableElement&gt; fields = new HashMap&lt;String, VariableElement&gt;();
            Map&lt;String, ExecutableElement&gt; methods = new HashMap&lt;String, ExecutableElement&gt;();

            for (Element e : roundEnv.getElementsAnnotatedWith(BeanInfo.class)) {

                if (e.getKind() == ElementKind.CLASS) {

                    TypeElement classElement = (TypeElement) e;
                    PackageElement packageElement = (PackageElement) classElement.getEnclosingElement();

                    processingEnv.getMessager().printMessage(
                        Diagnostic.Kind.NOTE,
                        "annotated class: " + classElement.getQualifiedName(), e);

                    fqClassName = classElement.getQualifiedName().toString();
                    className = classElement.getSimpleName().toString();
                    packageName = packageElement.getQualifiedName().toString();

                } else if (e.getKind() == ElementKind.FIELD) {

                    VariableElement varElement = (VariableElement) e;

                    processingEnv.getMessager().printMessage(
                        Diagnostic.Kind.NOTE,
                        "annotated field: " + varElement.getSimpleName(), e);

                    fields.put(varElement.getSimpleName().toString(), varElement);

                } else if (e.getKind() == ElementKind.METHOD) {

                    ExecutableElement exeElement = (ExecutableElement) e;

                    processingEnv.getMessager().printMessage(
                        Diagnostic.Kind.NOTE,
                        "annotated method: " + exeElement.getSimpleName(), e);

                    methods.put(exeElement.getSimpleName().toString(), exeElement);
                }
            }</pre>
<h4>Step 3: Initialize the Velocity Context and Load the Template</h4>
<p>The following code snippet show how to initialize the Velocity context and load the template:</p>
<pre>            if (fqClassName != null) {

                Properties props = new Properties();
                URL url = this.getClass().getClassLoader().getResource("velocity.properties");
                props.load(url.openStream());

                VelocityEngine ve = new VelocityEngine(props);
                ve.init();

                VelocityContext vc = new VelocityContext();

                vc.put("className", className);
                vc.put("packageName", packageName);
                vc.put("fields", fields);
                vc.put("methods", methods);

                Template vt = ve.getTemplate("beaninfo.vm");</pre>
<p>The velocity configuration file, named in this example<strong> velocity.properties</strong>, should be placed under <strong>src/main/resources</strong> folder. An example of its contents is below:</p>
<pre>runtime.log.logsystem.class = org.apache.velocity.runtime.log.SystemLogChute

resource.loader = classpath
classpath.resource.loader.class = org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader</pre>
<p>This set of properties configures a log for Velocity and a classpath-based resource loader to find the template.</p>
<h4>Step 4: Create the New Source and Generate the Contents</h4>
<p>Finally, let&#8217;s create a new source file and run the template using this new file as the target. The following code snippet shows how to do it:</p>
<pre>                JavaFileObject jfo = processingEnv.getFiler().createSourceFile(
                    fqClassName + "BeanInfo");

                processingEnv.getMessager().printMessage(
                    Diagnostic.Kind.NOTE,
                    "creating source file: " + jfo.toUri());

                Writer writer = jfo.openWriter();

                processingEnv.getMessager().printMessage(
                    Diagnostic.Kind.NOTE,
                    "applying velocity template: " + vt.getName());

                vt.merge(vc, writer);

                writer.close();</pre>
<h4>Step 5: Package and run</h4>
<p>Finally, register the processor (remember the service configuration file shown in part 2) package it and invoke it from a client project compilation command, Eclipse or Maven build.</p>
<p>Assuming the following client class:</p>
<pre>package example.velocity.client;
import example.annotations.beaninfo.BeanInfo;
@BeanInfo public class Article {
    @BeanInfo private String id;
    @BeanInfo private int department;
    @BeanInfo private String status;
    public Article() {
        super();
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public int getDepartment() {
        return department;
    }
    public void setDepartment(int department) {
        this.department = department;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    @BeanInfo public void activate() {
        setStatus("active");
    }
    @BeanInfo public void deactivate() {
        setStatus("inactive");
    }
}</pre>
<p>When we issue the <strong>javac</strong> command, we can see in the console that annotated elements are found and the BeanInfo class is generated:</p>
<pre>Article.java:6: Note: annotated class: example.annotations.velocity.client.Article
public class Article {
       ^
Article.java:9: Note: annotated field: id
    private String id;
                   ^
Article.java:12: Note: annotated field: department
    private int department;
                ^
Article.java:15: Note: annotated field: status
    private String status;
                   ^
Article.java:53: Note: annotated method: activate
    public void activate() {
                ^
Article.java:59: Note: annotated method: deactivate
    public void deactivate() {
                ^
Note: creating source file: file:/c:/projects/example.annotations.velocity.client/src/main/java/example/annotations/velocity/client/ArticleBeanInfo.java
Note: applying velocity template: beaninfo.vm
Note: example\annotations\velocity\client\ArticleBeanInfo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.</pre>
<p>If we check in the sources directory we will find there the BeanInfo class as expected. Mission accomplished!</p>
<h4>Conclusion</h4>
<p>During this series we have learned the basis about how to generate source code by leveraging the Annotation Processor framework in Java 6:</p>
<div>
<ul>
<li>We have learned what are Annotations and Annotation Types and what are the common uses for them.</li>
<li>We have learned what are Annotation Processors, how to write them and how to execute them from different tools – the Java Compiler, Eclipse and Maven.</li>
<li>We have discussed a bit about Model-Drive Engineering and code generation.</li>
<li>We have shown how Annotation Processors can be used to create source code generators that are fully integrated with the Java Compiler.</li>
<li>We have shown how to leverage existing generation frameworks as Apache Velocity to create elegant, powerful and maintainable source code generators using Annotation Processors.</li>
</ul>
</div>
<p>Now it is time to apply this to your projects. Think Generate!</p>
<p>—</p>
<p>(1) If you want to know more about MDE, visit <a href="http://en.wikipedia.org/wiki/Model-driven_engineering">this article</a> in Wikipedia and follow the references.</p>
<p>(2) The Filer API documentation can be reviewed online <a href="http://download.oracle.com/javase/6/docs/api/javax/annotation/processing/Filer.html">here</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/deors.wordpress.com/126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/deors.wordpress.com/126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/deors.wordpress.com/126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/deors.wordpress.com/126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/deors.wordpress.com/126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/deors.wordpress.com/126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/deors.wordpress.com/126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/deors.wordpress.com/126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/deors.wordpress.com/126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/deors.wordpress.com/126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/deors.wordpress.com/126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/deors.wordpress.com/126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/deors.wordpress.com/126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/deors.wordpress.com/126/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=deors.wordpress.com&amp;blog=21758442&amp;post=126&amp;subd=deors&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://deors.wordpress.com/2011/10/31/annotation-generators/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d964b48ba3c3366cc967250087401257?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">deors</media:title>
		</media:content>
	</item>
	</channel>
</rss>
