<?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>Detour</title>
	<atom:link href="http://dturanski.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://dturanski.wordpress.com</link>
	<description>Yet another blog</description>
	<lastBuildDate>Mon, 15 Feb 2010 05:08:37 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='dturanski.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Detour</title>
		<link>http://dturanski.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://dturanski.wordpress.com/osd.xml" title="Detour" />
	<atom:link rel='hub' href='http://dturanski.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Service Location with Spring Integration</title>
		<link>http://dturanski.wordpress.com/2010/02/14/service-location-with-spring-integration/</link>
		<comments>http://dturanski.wordpress.com/2010/02/14/service-location-with-spring-integration/#comments</comments>
		<pubDate>Sun, 14 Feb 2010 18:51:04 +0000</pubDate>
		<dc:creator>David Turanski</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://dturanski.wordpress.com/?p=41</guid>
		<description><![CDATA[Introduction A recent client runs a large distributed system that processes global data in near real-time. Because of high data volumes, the architecture requires that each host (physical or virtual) be allocated to one or more geographic regions. Geographic data is maintained in memory and this architecture allows the system to easily scale without exceeding [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dturanski.wordpress.com&amp;blog=6237458&amp;post=41&amp;subd=dturanski&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>A recent client runs a large distributed system that processes global data in near real-time.  Because of high data volumes, the architecture requires that each host (physical or virtual) be allocated to one or more geographic regions. Geographic data is maintained in memory and this architecture allows the system to easily scale without exceeding the physical memory of each host.  I was asked to prototype a light weight services framework that would route each service request to an appropriate host.  In this case, the client was also interested in using plain old RMI for remote invocation.</p>
<p>The general approach is to assign servers based on some domain-specific criteria. For example, if geographic data can be associated to a Region ID, then we can assign hosts to Regions. This is generally a many-to-many relationship as each host can service multiple regions (presumably a small subset) and a region may be serviced by multiple hosts (to support dynamic scaling).  Given a service method invocation, the region ID may be derived from examining the input parameters.  In the simplest case, one of the parameters contains a value for the Region ID. The general problem is more complex involving some complex data mapping involving business rules, etc. For the prototype, I used an annotation @Locator to mark the parameter (or field) containing the Region ID.</p>
<p>Once we have a strategy for determining the Region ID for each service invocation, we can implement a Service Locator to resolve the physical host address and port and route the request to that endpoint.  Besides partitioning by geographic region, it&#8217;s easy to see how this concept could be applied to an domain based affinity scheme.</p>
<p><img src="http://dturanski.files.wordpress.com/2010/02/servicelocator1.jpg?w=450"></p>
<h2>Design Considerations</h2>
<p> The high level design goals include:</p>
<ul>
<li>Utilize lightweight remoting with support for multiple protocols (e.g. http, RMI)</li>
<li>Centralize configuration of host to endpoint mapping. The assignment of hosts to regions is expected to be very dynamic and controlled by the operations team</li>
<li>Centralize the service locator. Given the potential complexity of service location rules and data dependencies, the Service Locator should be a centralized resource</li>
<li>Allow for simple configuration.  It should be easy to add new services</li>
<li>Provide service versioning. Allow for the availability of different versions and allow clients to specify compatible version(s)</li>
</ul>
<p><a href="http://static.springsource.org/spring/docs/2.0.8/reference/remoting.html">Spring Remoting</a> comes immediately to mind but does not meet the design goals.  It is fairly simple to extend Spring&#8217;s <code>RmiProxyFactoryBean</code> to inject different endpoints at runtime. A Service Locator implementation can be injected into the extended proxy to provide a URL for each invocation.  This approach requires a proxy to be configured for each service type and, on the server side, A corresponding Service Exporter.  This violates the <em>simple configuration</em> goal. In addition, accessing a central Service Locator requires an extra round trip on the network for each service request.  There is a possibility to use caching, but this quickly leads to unnecessary complexity.</p>
<p>An alternative, is to go the ESB route and use content based routing. I initially considered Mule, but apparently Mule does not provide an inbound RMI adapter.  I envisioned a similar approach: basically the client invokes a server side proxy that routes each service request to a target endpoint.  Using Spring Remoting alone would require configuring a separate endpoint for each Interface type.  This would eventually become unmanageable.</p>
<p>In the end, <a href="http://www.springsource.org/spring-integration">Spring Integration</a> (SI) provided an interesting solution.  </p>
<h2>Implementation</h2>
<p>SI provides a <code>GatewayProxyFactoryBean</code> commonly used to transform a method invocation on any interface to a Message. A <code>SimpleMessagingGateway</code> is used to send a message with a payload containing the method parameters over a request channel and send the return value as a response message over a reply channel.  SI also provides messaging over RMI using <code>RmiOutboundGateway</code> and <code>RmiInboundGateway</code>.  These components were the basic building blocks for the solution. </p>
<p>What I was going for is an RPC based approach in which the server and client side share a common interface.  It is important to note that SI in general, and the <code>GatewayProxyFactoryBean</code> in particular is not designed for this purpose.  Spring Remoting already provides an RPC-like implementation.  SI is an implementation of Gregor Hohpe&#8217;s <a href="http://www.eaipatterns.com/">Enterprise Integration Patterns</a> which is based on message based communications.  As previously mentioned, I discarded Spring Remoting because the configuration would be complex and hard to manage.</p>
<p>A better approach is to convert each service invocation to a Message. In SI, a Message is an abstraction that contains Headers and a Payload. The message headers are represented as a Map and the Payload can be any object.  Once the service invocation is transformed to a message, it is possible to process service request messages using a common endpoint and message handlers to do perform the remote invocations and routing.  Once the message is routed to the correct host,  an operation on the service implementation, a POJO, is invoked and the result is returned via the reply channels.  </p>
<p>At first, the <code>GatewayProxyFactoryBean</code> (GPFB) appeared to be very close to what I wanted, but not quite.  I needed the identical message payloads to what GPFB provides (the method arguments in the request message and the return value in the reply message) but I needed to enrich the message header with the service interface class name, the method name and the requested service version range.  It turns out that the GPFB does set the method name in the message history headers, but it is very difficult to determine the service interface.  </p>
<p>The latter is a characteristic of dynamic proxies in general. In Spring the Proxy Factory Bean&#8217;s <code>getObject()</code> method returns the proxy. The name of the proxy class is something like <code>$Proxy1</code> so you can&#8217;t get the type directly by calling <code>getClass().getName()</code> (there is a way to discover the class name using reflection but it is much more involved).  Also, it is difficult to get a reference to the actual Spring factory bean and query it&#8217;s <code>interface</code> property (where are the leaky abstractions when you need them?).  Any attempt to extend the GPFB to provide the interface type proved futile.  So that is clearly the wrong approach.  But it gave me an idea&#8230;</p>
<p>I implemented my own Proxy Factory Bean (using the GPFB source as a template). This creates a dynamic proxy for the service interface. When a method is invoked on the proxy, it can create a message with the required attributes in the message header and the set the message payload to the method parameters and send that message to an inbound gateway.  As it turns out, I did not even need to create a message.  The GPFB does all this for you.  Internally, GPFB uses a <code>SimpleMessagingGateway</code> injected with an <code>InboundMessageMapper</code> and an <code>OutboundMessageMapper</code>.  The inbound message mapper is very smart.  For example if your payload (method parameters) consists of a <code>Map</code> followed by an object that is not a Map and you annotate the Map with @Headers  (an SI annotation) then it will create the message for you, adding the map entries to the message header.  I created the following interface:</p>
<div style="border:black solid 1px;background:#EEEEEE;">
<p><code>public interface GatewayAdapter {<br />
	/**<br />
	 * Creates a Message<br />
	 * @param headers - message headers<br />
	 * @param payload - message payload<br />
	 * @return - the result of the service request<br />
	 */<br />
   public Object invokeServiceRequest(@Headers Map headers, Object payload);<br />
}</code>
</div>
<p>And used the GPFB to wire it into an SI messaging gateway and injected that into my proxy factory bean, <code>GatewayAdapterProxyFactoryBean</code>.  </p>
<p>The Spring configuration for this looks like (click to enlarge):<br />
  <a href="http://dturanski.files.wordpress.com/2010/02/gateway-config1.png"><img src="http://dturanski.files.wordpress.com/2010/02/gateway-config1.png?w=450&#038;h=135" alt="" title="gateway-config" width="450" height="135" class="aligncenter size-full wp-image-107" /></a></p>
<p>The message gets sent via RMI (RmiOutboundGateway) to determine the service endpoint and add the service URL to the message header.  For the prototype, I wrote a <code>AnnotationAwareServiceLocator</code> to determine the endpoint URL and a <code>ServiceURLHeaderEnricher</code> and an <code>AnnotationAwareServiceLocatorMessageProcessor</code> to process the message.</p>
<p>The SI configuration for this is:<br />
 <a href="http://dturanski.files.wordpress.com/2010/02/service-locator-config1.png"><img src="http://dturanski.files.wordpress.com/2010/02/service-locator-config1.png?w=450&#038;h=135" alt="" title="service-locator-config" width="450" height="135" class="aligncenter size-full wp-image-107" /></a></p>
<p>The must now be routed to the service host via RMI. The <code>RmiOutboundGateway</code> can do this however, out of the box I would have to statically configure an outbound RMI channel for every service endpoint.  Instead, I opted to write a <code>DynamicRmiOutboundGateway</code>. This is a simple wrapper around the <code>RmiOutboundGateway</code> to configure it programmatically from the message header attributes.  The prototype implementation creates a new instance of <code>RmiOutboundGateway</code> for each request and would benefit from caching them.</p>
<p>At the service host the message is received over an <code>RmiInboundGateway</code> (These all run in one JVM and are configured with different ports) and handled by a Service Activator which also implements the <code>GatewayAdapter</code> interface to extract the message payload and header.  At this point, we need to obtain an instance of the service class from the application context and invoke the named method.  The <code>ServiceGatewayAdapter</code> uses reflection to do this (Sorry about the crappy layout. Any WordPress tips are appreciated).</p>
<div style="border:black solid 1px;background:#EEEEEE;">
<code><br />
<font size="smallest"><br />
public class ServiceGatewayAdapter implements GatewayAdapter, ApplicationContextAware {<br />
    private volatile ApplicationContext context;<br />
    private static Logger logger = Logger.getLogger(ServiceGatewayAdapter.class);</p>
<p>    @Override<br />
	public Object invokeServiceRequest(Map headers,<br />
			Object payload) {<br />
		 Object result = null;<br />
		 String serviceInterface =<br />
(String) headers.get(ServiceInvokerHeaderKeys.SERVICE_INTERFACE_KEY);<br />
		 String methodName =<br />
(String) headers.get(ServiceInvokerHeaderKeys.METHOD_NAME_KEY);<br />
		 if (logger.isDebugEnabled()){<br />
		   logger.debug(" received service request serviceInterface : [" + serviceInterface + "]"<br />
                                       + " method : [" + methodName + "]");<br />
		   logger.debug("Payload :" + payload);<br />
		 }<br />
		 try {</p>
<p>			/*<br />
			 * Get the implementation for the requested interface from the<br />
                         *application context and invoke the requested method<br />
			 * using reflection<br />
			 */<br />
			Class serviceClass = Class.forName(serviceInterface);<br />
			Object service = context.getBean(serviceClass);<br />
			Method method = ReflectionUtils.getMethod(serviceClass, methodName, payload);<br />
			result = method.invoke(service, (Object[])payload);</p>
<p>		 } catch (BeansException e) {<br />
			throw new RuntimeException(e);<br />
		} catch (ClassNotFoundException e) {<br />
			throw new RuntimeException(e);<br />
		} catch (IllegalArgumentException e) {<br />
			throw new RuntimeException(e);<br />
		} catch (IllegalAccessException e) {<br />
			throw new RuntimeException(e);<br />
		} catch (InvocationTargetException e) {<br />
			throw new RuntimeException(e);<br />
		}<br />
		return result;<br />
	}</p>
<p>	@Override<br />
	public void setApplicationContext(ApplicationContext context)<br />
			throws BeansException {<br />
		this.context = context;</p>
<p>	}<br />
}<br />
 </font><br />
</code>
</div>
<p>You can download the <a href="http://www.dturanski.com/service-location-with-spring-integration.zip">source code</a>, build it with maven (or m2eclipse) and run the <code>GatewayProxyTest</code>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dturanski.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dturanski.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dturanski.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dturanski.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dturanski.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dturanski.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dturanski.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dturanski.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dturanski.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dturanski.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dturanski.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dturanski.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dturanski.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dturanski.wordpress.com/41/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dturanski.wordpress.com&amp;blog=6237458&amp;post=41&amp;subd=dturanski&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://dturanski.wordpress.com/2010/02/14/service-location-with-spring-integration/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/52d0b036ccbae9bdf920042f3a3b176f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">David</media:title>
		</media:content>

		<media:content url="http://dturanski.files.wordpress.com/2010/02/servicelocator1.jpg" medium="image" />

		<media:content url="http://dturanski.files.wordpress.com/2010/02/gateway-config1.png" medium="image">
			<media:title type="html">gateway-config</media:title>
		</media:content>

		<media:content url="http://dturanski.files.wordpress.com/2010/02/service-locator-config1.png" medium="image">
			<media:title type="html">service-locator-config</media:title>
		</media:content>
	</item>
		<item>
		<title>The Return of Domain Specific Languages</title>
		<link>http://dturanski.wordpress.com/2009/02/21/the-return-of-domain-specific-languages/</link>
		<comments>http://dturanski.wordpress.com/2009/02/21/the-return-of-domain-specific-languages/#comments</comments>
		<pubDate>Sat, 21 Feb 2009 15:43:34 +0000</pubDate>
		<dc:creator>David Turanski</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[DSL]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://dturanski.wordpress.com/?p=31</guid>
		<description><![CDATA[Domain Specific Languages (DSL) are among the hottest new trends in computer science. A DSL is a programming language designed for a specific problem domain. This topic is getting a lot of attention these days because a DSL can greatly simplify programming by providing semantics that more naturally express automated solutions for the associated domain. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dturanski.wordpress.com&amp;blog=6237458&amp;post=31&amp;subd=dturanski&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Domain_Specific_Language">Domain Specific Languages (DSL)</a> are among the hottest new trends in computer science.  A DSL is a programming language designed for a specific problem domain.  This topic is getting a lot of attention these days because a DSL can greatly simplify programming by providing semantics that more naturally express automated solutions for the associated domain. A DSL can be thought of as a domain-specific 4GL, much easier to program in than a general purpose programming language, or 3GL, such as Java, C++, etc.   But is this really a new idea?</p>
<p>In the late 1950s, when computing was in its infancy, DSLs were actually state of the art. In 1957, my father, the late William Joseph Turanski and his colleage, Anatol W. Holt, were employed at the Univac Applications Research Center of the Remington Rand Univac division of the Sperry Rand Corporation (now Unisys).  Their primary focus was the development of a Generalized Programming (GP) system (renamed FLEXIMATIC by the marketing dudes).  This was basically the first general high level language compiler.  Being a completely new field, computer scientists were still trying to devise basic &#8220;naming aids&#8221; such as symbolic addressing, mnemonic devices, and convenient notations, that could be efficiently parsed by a computer and correctly mapped to computer instructions.  However, compilers for specific types of computing problems were commonplace.</p>
<p>Holt describes the situation in <a href="http://portal.acm.org/citation.cfm?id=368851&amp;dl=ACM&amp;coll=ACM">General Purpose Programming Systems</a>, a technical report he authored, dated October 30, 1957, based on a talk given before the ACM in Houston, in June 1957 (I own a hard copy).  In reference to GP, he states:</p>
<div id="attachment_36" class="wp-caption aligncenter" style="width: 295px"><img src="http://dturanski.files.wordpress.com/2009/02/holt_technical_report.jpg?w=285&#038;h=300" alt="General Purpose Programming Systems by Anatol W. Holt October 30, 1957" title="holt_technical_report" width="285" height="300" class="size-medium wp-image-36" /><p class="wp-caption-text">General Purpose Programming Systems by Anatol W. Holt October 30, 1957</p></div>
<p>&#8220;The system differs from other compilers,&#8230;, in that it aims to provide the programmer with a set of services equally applicable to the solution of any problem &#8211; services, in other words, which are claimed to be altogether &#8220;general purpose&#8221;.  Therefore the system contains no special design features which make it better adapted to one area of computation than another.&#8221;</p>
<p>One can infer from this, that designing a general purpose language was a very challenging proposition.  Similar to developing a general solution in mathematics or science, you first start with specific working examples and try to determine what they have in common to arrive at a generalization.  Such was the state of computing in 1950s.  There were specific language compilers developed for commercial use in various mathematics and business domains, but the general solution was still being worked out.   Holt describes the state of the art:</p>
<p>&#8220;In the development of most compiling systems, the designers begin with a special range of problems for which they intend their systems to be useful.  They invent special notations which they consider naturally adapted to the area of problems in question, and they construct a translating mechanism with just enough generality to cope with these notations.&#8221;</p>
<p>This is a pretty fair description of a modern DSL.  But of course this model didn&#8217;t scale very well.  As Holt observes,</p>
<p>&#8220;While&#8230;special notation for a given area of problems&#8230; may be very useful and important&#8230;, the ability to add arbitrary, new notation is even more important than any given set of special notations. &#8230; we cannot even hope&#8230;to subdivide the entire universe of problems into fixed areas, each with a well-adapted notation.  For example, if I have devised on notation satisfactory for business problems and another notation satisfactory for algebra,  I am still unable to write convenient coding for problems which&#8230;involve a lot of data handling and algebraic computation.&#8221;<br />
<div id="attachment_32" class="wp-caption aligncenter" style="width: 310px"><img src="http://dturanski.files.wordpress.com/2009/02/turanski_holt.jpg?w=300&#038;h=213" alt="William Turanski and Anatol Holt at the Univac 1, circa 1957" title="turanski_holt" width="300" height="213" class="size-medium wp-image-32" /><p class="wp-caption-text">William Turanski and Anatol Holt at the Univac 1, circa 1957</p></div><br />
In the conclusion, Holt writes:</p>
<p>&#8220;In summary, &#8230;I claim that it is possible to construct a general purpose compiler&#8230;The theoretical foundations for such compiling systems are now being developed at Remington Rand.  Early examples, such as GP for UNIVAC 1, demonstrate the practical utility of a system designed from this point of view.&#8221;</p>
<p>The rest is history. Sadly my father died as a result of an automobile accident while en route to the Algol 60 conference in Paris.  Algol was of course a forerunner to modern languages such as C and Java.  I&#8217;m sure, if alive today, he would have appreciated that the wheel has once again come full circle.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dturanski.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dturanski.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dturanski.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dturanski.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dturanski.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dturanski.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dturanski.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dturanski.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dturanski.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dturanski.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dturanski.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dturanski.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dturanski.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dturanski.wordpress.com/31/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dturanski.wordpress.com&amp;blog=6237458&amp;post=31&amp;subd=dturanski&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://dturanski.wordpress.com/2009/02/21/the-return-of-domain-specific-languages/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/52d0b036ccbae9bdf920042f3a3b176f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">David</media:title>
		</media:content>

		<media:content url="http://dturanski.files.wordpress.com/2009/02/holt_technical_report.jpg?w=285" medium="image">
			<media:title type="html">holt_technical_report</media:title>
		</media:content>

		<media:content url="http://dturanski.files.wordpress.com/2009/02/turanski_holt.jpg?w=300" medium="image">
			<media:title type="html">turanski_holt</media:title>
		</media:content>
	</item>
		<item>
		<title>Migrating from Rails to Grails</title>
		<link>http://dturanski.wordpress.com/2009/01/19/rails2grails/</link>
		<comments>http://dturanski.wordpress.com/2009/01/19/rails2grails/#comments</comments>
		<pubDate>Mon, 19 Jan 2009 18:58:31 +0000</pubDate>
		<dc:creator>David Turanski</dc:creator>
				<category><![CDATA[programming]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[I have been developing with Java for over 10 years and over the last couple of years got interested in Ruby and Rails. I have developed a few Rails applications mostly for personal use and use Ruby extensively on the job for utilities that I used write in Perl. So I am a huge fan [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dturanski.wordpress.com&amp;blog=6237458&amp;post=1&amp;subd=dturanski&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I have been developing with Java for over 10 years and over the last couple of years got interested in Ruby and Rails. I have developed a few Rails applications mostly for personal use and use Ruby extensively on the job for utilities that I used write in Perl. </p>
<p>So I am a huge fan of Ruby and Rails, and then along came Grails. Grails is an implementation of Rails written in Groovy. Derived from Java syntax, Groovy is easy for Java developers to pick up. In addition, Grails uses familiar Java frameworks under the covers, most notably Spring and Hibernate. Recently SpringSource acquired G2one, the company behind Grails and some interesting work has been happening to integrate <a href="http://graemerocher.blogspot.com/2008/12/grails-spring-integration.html">Grails and Spring integration</a>.  Reading the Grails documents and various posts, it was clear to me that Grails down-plays its Rails heritage.  I expected some significant differences so I thought it would be interesting to port a Rails application to Grails. </p>
<p>I started with the <a href="http://guides.rails.info/getting_started_with_rails.html">Rails tutorial</a> which guides you through a simple blog application. I used Mysql 5 for the database and got it up and running in no time. The application allows you to post blog entries and comments on the entries. Two tables are created, <code>posts</code> and <code>comments</code>. Of course there is a one-to-many relationship, so a post has many comments and a comment belongs to a post. </p>
<p>I basically wanted to retain the existing database tables and create the application with Grails. In the process, I discovered some of the key differences between these two frameworks. </p>
<p>The first step is to install Grails. It&#8217;s best to stick with the stable release. Being adventurous, I decided to check out the latest code from the svn trunk and build it myself. This is currently version 1.0.5. The latest stable version is 1.0.4. There is also a 1.1 beta release. Version 1.0.5, and 1.1 beta are buggy and caused some problems with object relational mapping. I eventually resigned myself to using 1.0.4, and everything worked as expected. </p>
<p>To create the blog application, type<br />
<code>grails create-app blog</code><br />
This is analogous to the <code>rails</code> command. It creates the directory structure for your application and sets up a default configuration.</p>
<p>Next, configure the data source for Mysql. Edit grails-app/conf/Datasource.groovy, so that it looks something like this (changes are bolded):</p>
<div style="border:black solid 1px;background:#EEEEEE;">
<code><br />
dataSource<br />
{<br />
&nbsp;&nbsp;pooled = true<br />
&nbsp;&nbsp;<b>driverClassName = "com.mysql.jdbc.Driver"</b><br />
&nbsp;&nbsp;<b>username = "root"</b><br />
&nbsp;&nbsp;<b>password = "mysql"</b><br />
&nbsp;&nbsp;<b>dialect = "org.hibernate.dialect.MySQL5Dialect"</b><br />
}<br />
</code><br />
<code><br />
hibernate {<br />
&nbsp;&nbsp;cache.use_second_level_cache=true<br />
&nbsp;&nbsp;cache.use_query_cache=true<br />
&nbsp;&nbsp;cache.provider_class=<br />
'com.opensymphony.oscache.hibernate.OSCacheProvider'<br />
}<br />
// environment specific settings<br />
environments {<br />
&nbsp;&nbsp;&nbsp;&nbsp;development {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dataSource {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>//dbCreate = "create-drop"</b><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>url = "jdbc:mysql://localhost/blog_development"</b><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;test {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dataSource {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//dbCreate = "update"<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;url = "jdbc:mysql://localhost/blog_test"<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;production {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dataSource {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//dbCreate = "update"<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;url = "jdbc:mysql://localhost/blog_production"<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;}<br />
}<br />
</code>
</div>
<p>Note that like Rails, Grails provides development, test, and production environments. This configuration provides access to the Mysql database I created with Rails. Note the <code><b>dbCreate</b></code> property is commented out. The default behavior for the development environment is to drop and re-create the tables every time you run Grails. In this case, I want to retain the schema and the existing data. Removing this property prevents Grails from destroying the database. </p>
<p>Next, you need to provide the declared driver class. This is the standard JDBC driver for Mysql in this case and is provided in <code><b>mysql-connector-java-5.0.8-bin.jar</b></code>, for example.  Install this in the application <code>lib</code> directory.</p>
<p>Now, create the domain classes. These are somewhat analogous to the Rails model (ActiveRecord) classes. Grails provides <a href="http://grails.org/GORM">Grails ORM (GORM)</a> which uses Hibernate under the covers.  GORM provides some nice features, and a nice DSL, but is somewhat incompatible with Rails in its &#8220;convention over configuration.&#8221;  Key differences include:</p>
<ul>
<li>No pluralization of table names</li>
<li>Automatic record versioning for optimistic locking</li>
<li>No timestamping records by default. Timestamping uses different field names by default</li>
<li>DB column names with underscores are converted to camelCase field names by default</li>
</ul>
<p>So after some experimentation, the Rails compatible domain classes, providing the same features as in the <a href="http://guides.rails.info/getting_started_with_rails.html">Rails tutorial</a> , are</p>
<div style="border:black solid 1px;background:#EEEEEE;">
<code><br />
class Post {<br />
&nbsp;&nbsp;String title<br />
&nbsp;&nbsp;String name<br />
&nbsp;&nbsp;String content<br />
&nbsp;&nbsp;Date lastUpdated<br />
&nbsp;&nbsp;Date dateCreated<br />
</code><code><br />
&nbsp;&nbsp;static constraints = {<br />
&nbsp;&nbsp;&nbsp;&nbsp;title(minSize:5, blank:false)<br />
&nbsp;&nbsp;&nbsp;&nbsp;name(blank:false)<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;static hasMany = [ comments : Comment]<br />
</code><code><br />
&nbsp;&nbsp;static mapping  = {<br />
&nbsp;&nbsp;&nbsp;&nbsp;version false<br />
&nbsp;&nbsp;&nbsp;&nbsp;table  'posts'<br />
&nbsp;&nbsp;&nbsp;&nbsp;columns {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;content type : 'text'<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;lastUpdated column:'updated_at'<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dateCreated column:'created_at'<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;}<br />
}<br />
</code>
</div>
<p></p>
<div style="border:black solid 1px;background:#EEEEEE;">
<code><br />
class Comment {<br />
&nbsp;&nbsp;String commenter<br />
&nbsp;&nbsp;String body<br />
&nbsp;&nbsp;Date lastUpdated<br />
&nbsp;&nbsp;Date dateCreated<br />
</code><code><br />
&nbsp;&nbsp;static mapping  = {<br />
&nbsp;&nbsp;&nbsp;&nbsp;version false<br />
&nbsp;&nbsp;&nbsp;&nbsp;table   'comments'<br />
</code><code><br />
&nbsp;&nbsp;&nbsp;&nbsp;columns {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;body type: 'text'<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;lastUpdated column:'updated_at'<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dateCreated column:'created_at'<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;}<br />
</code><code><br />
&nbsp;&nbsp;static belongsTo = [post: Post]<br />
}<br />
</code>
</div>
<p>Notice the boilerplate code required here. The timestamp fields are Grails defaults and will be automatically updated as appropriate. Unlike, Rails, they must be explicitly declared and mapped to the Rails conventional column names.</p>
<p>Versioning is turned off, as the tables do not include version columns. (I am a big fan of optimistic locking, but this is KISS). The <code>constraints</code> closure in the <code>Post</code> class demonstrates how field validation is done in Grails, similar to the Rails tutorial.</p>
<p>I struggled for a while attempting to refactor this code into a base class. I eventually gave up. GORM provides some conventions around mapping inherited domain classes. Also, I couldn&#8217;t figure out how to get the <code>mapping</code> closure to execute the base class mapping.  It is likely due to my lack of Groovy and GORM expertise, so I suspect there is an easy way to do this. </p>
<p>From this point, it is fairly straight forward. Execute the commands:<br />
<code>grails generate-all post</code><br />
<code>grails generate-all comment</code></p>
<p>to generate the controller and view scaffolding code. Then<br />
<code>grails run-app</code><br />
and you should be good to go. </p>
<p>As a final step, Grails scaffolding creates inputs for dateCreated and lastUpdated. This also behaves differently then Rails. So I went in and edited the view pages, e.g., <code>grails-app/views/post/create.gsp and removed the date fields. </p>
<div id="attachment_18" class="wp-caption alignnone" style="width: 460px"><img src="http://dturanski.files.wordpress.com/2009/01/rails_blog.png?w=450&#038;h=312" alt="The blog application on Rails" title="rails_blog" width="450" height="312" class="size-full wp-image-18" /><p class="wp-caption-text">The blog application on Rails</p></div><br />
<br />
<div id="attachment_19" class="wp-caption alignnone" style="width: 460px"><img src="http://dturanski.files.wordpress.com/2009/01/blog_grails.png?w=450&#038;h=312" alt="The blog application on Grails" title="blog_grails" width="450" height="312" class="size-full wp-image-19" /><p class="wp-caption-text">The blog application on Grails</p></div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dturanski.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dturanski.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dturanski.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dturanski.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dturanski.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dturanski.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dturanski.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dturanski.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dturanski.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dturanski.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dturanski.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dturanski.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dturanski.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dturanski.wordpress.com/1/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dturanski.wordpress.com&amp;blog=6237458&amp;post=1&amp;subd=dturanski&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://dturanski.wordpress.com/2009/01/19/rails2grails/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/52d0b036ccbae9bdf920042f3a3b176f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">David</media:title>
		</media:content>

		<media:content url="http://dturanski.files.wordpress.com/2009/01/rails_blog.png" medium="image">
			<media:title type="html">rails_blog</media:title>
		</media:content>

		<media:content url="http://dturanski.files.wordpress.com/2009/01/blog_grails.png" medium="image">
			<media:title type="html">blog_grails</media:title>
		</media:content>
	</item>
	</channel>
</rss>
