<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JavaBeat &#187; Groovy</title>
	<atom:link href="http://www.javabeat.net/category/web-frameworks/groovy/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Wed, 22 May 2013 01:42:58 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Creating JSON using Groovy</title>
		<link>http://www.javabeat.net/2012/06/creating-json-using-groovy/</link>
		<comments>http://www.javabeat.net/2012/06/creating-json-using-groovy/#comments</comments>
		<pubDate>Fri, 22 Jun 2012 17:54:10 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4446</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>I wrote previously about parsing JSON in Groovy. In this article I show a simple example of creating JSON using Groovy. I had to learn about creating JSON using Groovy as I would be using JSON as the response format in the REST API which might be developed sometime in future. Creating JSON using Groovy [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p>I wrote <a href="http://www.javabeat.net/2012/04/parsing-json-using-groovy/" title="Parsing JSON using Groovy">previously</a> about parsing JSON in Groovy. In this article I show a simple example of creating JSON using Groovy. I had to learn about creating JSON using Groovy as I would be using JSON as the response format in the REST API which might be developed sometime in future. </p>
<h2>Creating JSON using Groovy</h2>
<p>Groovy 1.8 introduced json package for parsing and building JSON data. JsonSlurper is used for parsing JSON and <a href="http://groovy.codehaus.org/gapi/index.html?groovy/json/JsonBuilder.html" title="JsonBuilder" target="_blank">JsonBuilder</a> is used for creating JSON in Groovy. </p>
<p>Lets see a very simple example of <strong>creating a JSON using named arguments</strong>:</p>
<pre class="brush: java; title: ; notranslate">
def jsonBuilder = new groovy.json.JsonBuilder()
jsonBuilder.book(
    isbn: '0321774094',
    title: 'Scala for the Impatient',
    author: 'Cay S. Horstmann',
    publisher: 'Addison-Wesley Professional',
)
println(&quot;Using just named arguments&quot;)
println(jsonBuilder.toPrettyString())
</pre>
<p>The output:</p>
<pre class="brush: bash; title: ; notranslate">
Using just named arguments
{
  &quot;book&quot;: {
    &quot;isbn&quot;: &quot;0321774094&quot;,
    &quot;title&quot;: &quot;Scala for the Impatient&quot;,
    &quot;author&quot;: &quot;Cay S. Horstmann&quot;,
    &quot;publisher&quot;: &quot;Addison-Wesley Professional&quot;
  }
}
</pre>
<p><strong>Creating JSON using an instance of some class</strong><br />
For this lets define a class which would be a container for our data:</p>
<pre class="brush: java; title: ; notranslate">
class MyBook{
    def isbn
    def title
    def author
    def publisher
}
</pre>
<p>and the code which would create JSON from an instance of MyBook is</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
def myBook = new MyBook(isbn: '0321774094',
                        title: 'Scala for the Impatient',
                        author: 'Cay S. Horstmann',
                        publisher: 'Addison-Wesley Professional')
jsonBuilder(book: myBook)
println(&quot;Using an object&quot;)
println(jsonBuilder.toPrettyString())
</pre>
<p>The output:</p>
<pre class="brush: bash; title: ; notranslate">
Using an object
{
    &quot;book&quot;: {
        &quot;title&quot;: &quot;Scala for the Impatient&quot;,
        &quot;publisher&quot;: &quot;Addison-Wesley Professional&quot;,
        &quot;isbn&quot;: &quot;0321774094&quot;,
        &quot;author&quot;: &quot;Cay S. Horstmann&quot;
    }
}
</pre>
<p><strong>Creating JSON using a list of instances</strong></p>
<pre class="brush: java; title: ; notranslate">
def myBook = new MyBook(isbn: '0321774094',
  title: 'Scala for the Impatient',
  author: 'Cay S. Horstmann',
  publisher: 'Addison-Wesley Professional')

def myBook2 = new MyBook(isbn: '0976694085',
  title: 'Pragmatic Ajax: A Web 2.0 Primer',
  author: 'Justin Gehtland, Ben Galbraith, Dion Almaer',
  publisher: 'Pragmatic Bookshelf')

def myBook3 = new MyBook(isbn: '1934356050',
  title: 'Pragmatic Thinking and Learning: Refactor Your Wetware',
  author: 'Andy Hunt',
  publisher: 'Pragmatic Bookshelf')

def myBookList = [myBook,myBook2,myBook3]

jsonBuilder(books: myBookList)
println(&quot;Using list of objects&quot;)
println(jsonBuilder.toPrettyString())
</pre>
<p>The output for this would be:</p>
<pre class="brush: bash; title: ; notranslate">
Using list of objects
{
  &quot;books&quot;: [
    {
      &quot;title&quot;: &quot;Scala for the Impatient&quot;,
      &quot;publisher&quot;: &quot;Addison-Wesley Professional&quot;,
      &quot;isbn&quot;: &quot;0321774094&quot;,
      &quot;author&quot;: &quot;Cay S. Horstmann&quot;
    },
    {
      &quot;title&quot;: &quot;Pragmatic Ajax: A Web 2.0 Primer&quot;,
      &quot;publisher&quot;: &quot;Pragmatic Bookshelf&quot;,
      &quot;isbn&quot;: &quot;0976694085&quot;,
      &quot;author&quot;: &quot;Justin Gehtland, Ben Galbraith, Dion Almaer&quot;
    },
    {
      &quot;title&quot;: &quot;Pragmatic Thinking and Learning: Refactor Your Wetware&quot;,
      &quot;publisher&quot;: &quot;Pragmatic Bookshelf&quot;,
      &quot;isbn&quot;: &quot;1934356050&quot;,
      &quot;author&quot;: &quot;Andy Hunt&quot;
    }
  ]
}
</pre>
<p>For more details visit the API <a href="http://groovy.codehaus.org/gapi/groovy/json/JsonBuilder.html" target="_blank">here</a> and a good article <a href="http://java.dzone.com/articles/groovy-180-%E2%80%93-meet-jsonbuilder" title="JsonBuilder" target="_blank">here</a>.</p>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Fweb-frameworks%2Fgroovy%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/category/web-frameworks/groovy/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/category/web-frameworks/groovy/feed/" data-count="vertical" data-text="Groovy" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/06/creating-json-using-groovy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A simple Location and Weather mashup using Gaelyk Framework</title>
		<link>http://www.javabeat.net/2012/06/obtaining-weather-information-using-the-weather-underground-api-gaelyk-sample/</link>
		<comments>http://www.javabeat.net/2012/06/obtaining-weather-information-using-the-weather-underground-api-gaelyk-sample/#comments</comments>
		<pubDate>Tue, 12 Jun 2012 19:50:31 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Web Frameworks]]></category>
		<category><![CDATA[Gaelyk]]></category>
		<category><![CDATA[Google App Engine]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4270</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In our sample Gaelyk application here we stopped at just obtaining the location information. In this post lets update that application to fetch the Weather information as well. For the weather information we make use of the Weather Underground API which provides a lot of features like geolocation information, current weather conditions, forecast weather conditions [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In our sample Gaelyk application <a href="http://www.javabeat.net/2012/06/developing-groovy-based-web-application-and-deploying-to-google-app-engine/" title="Developing Groovy based web application and deploying to Google App Engine">here</a> we stopped at just obtaining the location information. In this post lets update that application to fetch the Weather information as well. </p>
<p>For the weather information we make use of the <a href="http://www.wunderground.com/?apiref=174b6ad6f944d555" title="Weather Underground API" target="_blank">Weather Underground API</a> which provides a lot of features like geolocation information, current weather conditions, forecast weather conditions among others. You need to <a href="http://www.wunderground.com/?apiref=174b6ad6f944d555" target="_blank">sign up</a> to obtain the API KEY. </p>
<p>The URL to request the data is:</p>
<pre class="brush: xml; title: ; notranslate">

http://api.wunderground.com/api/

KEY/FEATURE/[FEATURE…]/[SETTING…]/q/
QUERY.FORMAT
</pre>
<p>where,<br />
KEY- API key which you can obtain after sign up<br />
FEATURE- The feature you are interested in: geolocation, conditions, astronomy, radar and so on. One can provide multiple feature data to be retrieved.<br />
FORMAT- The format for the return data- XML or JSON<br />
QUERY- This is the query to be used for retrieving the data- can be city name, pin code, latitude-longitude and others. </p>
<p>For our application we can make use of the following version of the URL:</p>
<pre class="brush: xml; title: ; notranslate">

http://api.wunderground.com/api/

${weatherKey}/conditions/q/
${locationInformation.cityName}.json
</pre>
<p>where,<br />
${weatherKey}- will be replaced by the actual weather key<br />
${locationInformation.cityName} will be replaced by actual city name.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Lets create a template- <strong>weather.gtpl</strong> for showing the Weather information. This template will be added to <strong>src/main/webapp/WEB-INF/includes</strong>.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;!-- weather.gtpl --&gt;
&lt;h3&gt;Weather as of ${request.forecastDate}&lt;/h3&gt;
&lt;div class=&quot;span3&quot;&gt;
    &lt;ul&gt;
        &lt;li&gt;
            &lt;strong&gt;Weather&lt;/strong&gt;: 
            ${request.weather}
        &lt;/li&gt;
        &lt;li&gt;
            &lt;strong&gt;Temperature&lt;/strong&gt;: 
            ${request.temperature}
        &lt;/li&gt;
        &lt;li&gt;
            &lt;strong&gt;Wind&lt;/strong&gt;: 
            ${request.wind}
        &lt;/li&gt;
        &lt;li&gt;
            &lt;strong&gt;Relative Humidity&lt;/strong&gt;: 
            ${request.relativeHumidity}
        &lt;/li&gt;
    &lt;/ul&gt;
    More details 
      &lt;a href=&quot;${request.moreUrl}&quot; 
         target=&quot;_blank&quot;&gt;here&lt;/a&gt;
&lt;/div&gt;
&lt;div class=&quot;span2&quot;&gt;
    &lt;img src=&quot;${request.icon}&quot; 
         alt=&quot;${request.iconDesc}&quot; /&gt;
&lt;/div&gt;
</pre>
<p>And this will be included in the src/main/webapp/WEB-INF/pages/index.gtpl as:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;% include '/WEB-INF/includes/header.gtpl' %&gt;
&lt;div class=&quot;row&quot;&gt;
     &lt;!-- Older code here--&gt;
    &lt;div class=&quot;span6&quot;&gt;
        &lt;% include '/WEB-INF/includes/weather.gtpl' %&gt;
    &lt;/div&gt;
&lt;/div&gt;
&lt;% include '/WEB-INF/includes/footer.gtpl' %&gt;
</pre>
<p>Now we need to fetch the required information in the Groovlet and set it in the request object. This can be performed in the <strong>src/main/webapp/WEB-INF/groovy/index.groovy</strong>.</p>
<pre class="brush: java; title: ; notranslate">
//index.groovy
//Code from the previous sample- removed for clarity
//Fetch the weather information
def weatherKey=&quot;YOUR API KEY HERE&quot;
def weatherUrl = &quot;&quot;&quot;http://api.wunderground.com/api/
                ${weatherKey}/conditions/q/
                ${locationInformation.cityName}.json&quot;&quot;&quot;
def xmlSlurper = new XmlSlurper()
def weatherInformation = null
if (memcache[locationInformation.cityName] != null){
    weatherInformation = 
        memcache[locationInformation.cityName]
}
else{
    weatherInformation = 
        jsonSlurper.parseText(new URL(weatherUrl).text)
    //caching the weather for each hour
    memcache.put(locationInformation.cityName,
                 weatherInformation,
                 Expiration.byDeltaSeconds(3599))
}

def currentObservation = 
    weatherInformation.current_observation
request.forecastDate = 
    currentObservation.observation_time_rfc822
request.weather = 
    currentObservation.weather
request.temperature = 
    currentObservation.temperature_string
request.wind = 
    currentObservation.wind_string
request.relativeHumidity = 
    currentObservation.relative_humidity
request.moreUrl = 
    currentObservation.ob_url
request.icon = 
    currentObservation.icon_url
request.iconDesc = 
    currentObservation.icon

forward '/WEB-INF/pages/index.gtpl'

</pre>
<p>Once completed your application will look like:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2012/06/weather_updated.png"><img src="http://www.javabeat.net/wp-content/uploads/2012/06/weather_updated-300x84.png" alt="" width="300" height="84" class="aligncenter size-medium wp-image-4271" /></a></p>
<p>If you want to play around with this code and also the previous sample developed <a href="http://www.javabeat.net/2012/06/developing-groovy-based-web-application-and-deploying-to-google-app-engine/" title="Developing Groovy based web application and deploying to Google App Engine">here</a> you can fork the git repo <a href="https://github.com/sanaulla123/my-place" title="Github Repo" target="_blank">here</a> and clone the repo locally. Once you are done with that just execute <strong>gradlew gaeRun</strong> on your command line to run this application. </p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/06/obtaining-weather-information-using-the-weather-underground-api-gaelyk-sample/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Exiting Blocks and Methods in Groovy</title>
		<link>http://www.javabeat.net/2011/04/exiting-blocks-and-methods-in-groovy/</link>
		<comments>http://www.javabeat.net/2011/04/exiting-blocks-and-methods-in-groovy/#comments</comments>
		<pubDate>Tue, 26 Apr 2011 00:11:34 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=683</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>This article is based on Groovy in Action, Second Edition, to be published on Summer 2011. It is being reproduced here by permission from Manning Publications. Manning publishes MEAP (Manning Early Access Program,) eBooks and pBooks. MEAPs are sold exclusively through Manning.com. All pBook purchases include free PDF, mobi and epub. When mobile formats become [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><em>This article is based on <a href="http://www.manning.com/koenig2/" target="_blank">Groovy in Action, Second Edition</a>, to be published on Summer 2011. It is being reproduced here by permission from <a href="http://www.manning.com" target="_blank">Manning Publications</a>. Manning publishes MEAP (Manning Early Access Program,) eBooks and pBooks. MEAPs are sold exclusively through Manning.com. All pBook purchases include free PDF, mobi and epub. When mobile formats become available all customers will be contacted and upgraded. Visit Manning.com for more information. [ <span style="color: red;"><span style="text-decoration: underline;"><strong>Use promotional code 'java40beat' and get 40% discount on eBooks and pBooks</strong></span> </span>]</em></p>
<p><center></p>
<h1>Exiting Blocks and Methods</h1>
<p></center></p>
<h2>Introduction</h2>
<p>Although it’s nice to have code that reads like a simple list of instructions with no jumping around, it’s often vital that control is passed from the current block or method to the enclosing block or the calling method—or sometimes even further up the call stack. Just like in Java, Groovy allows this to happen in an expected, orderly fashion with return, break, and continue statements and, in emergency situations, with exceptions. Let’s take a closer look.</p>
<h2>Normal termination: return/break/continue</h2>
<p>The general logic of return, break, and continue is similar to Java. One difference is that the return keyword is optional for the last expression in a method or closure. If it is omitted, the return value is that of the last expression. Methods with an explicit return type of void do not return a value, whereas closures always return a value.</p>
<p>Listing 1 shows how the current loop is shortcut with continue and prematurely ended with break. As in Java, there is an optional label.</p>
<p><span style="color: red;">Listing 1 Simple break and continue</span></p>
<pre>def a = 1
while (true) { //#1 Do forever
	a++
	break //#2 Forever is over now
}
assert a == 2
for (i in 0..10) {
	if (i==0) continue //#3 Proceed with 1
	a++
	if (i > 0) break //#4 Premature loop end
}
assert a==3
Using break and continue is sometimes considered smelly. However, they can be useful for controlling the workflow in services that run in an endless loop or for breaking apart complex conditional logic, such as this:
for(i in whatever){
if (filterA) continue // skip if filter matches
if (conditionB) break // exit loop if condition matches
// normal case here
}</pre>
<p>Similarly, returning from multiple points in the method is frowned upon in some circles but other people find it can greatly increase the readability of methods that might be able to return a result early. We encourage you to figure out what you find most readable and discuss it with whomever else is going to be reading your code—consistency is as important as anything else.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>As a final note on return handling, remember that, when closures are used with iteration methods such as each, a return statement within the closure returns from the closure rather than the method.</p>
<h2>Exceptions: throw/try-catch-finally</h2>
<p>Exception handling is exactly the same as in Java and follows the same logic. Just as in Java, you can specify a complete try-catch-finally sequence of blocks, or just try-catch, or just try-finally. Note that, unlike various other control structures, braces are required around the block bodies whether or not they contain more than one statement. The only difference between Java and <strong>Groovy</strong> in terms of exceptions is that declarations of exceptions in the method signature are optional, even for checked exceptions. Listing 2 shows the usual behavior.</p>
<p><span style="color: red;">Listing 2 Throw, try, catch, and finally</span></p>
<pre>def myMethod() {
	throw new IllegalArgumentException()
}
def log = []
try {
	myMethod()
} catch (Exception e) {
	log << e.toString()
} finally {
	log << 'finally'
}
assert log.size() == 2</pre>
<p>In accordance with optional typing in the rest of <strong>Groovy</strong>, a type declaration is optional in the catch expression. And, like in Java, you can declare multiple catches.</p>
<p>There are no compile-time or runtime warnings from <strong>Groovy</strong> when checked exceptions are not declared. When a checked exception is not handled, it is propagated up the execution stack like a RuntimeException in Java.</p>
<p>It is worth noting an issue relating to exceptions. When using a <strong>Groovy</strong> class from Java, you need to be careful—the <strong>Groovy</strong> methods will not declare that they throw any checked exceptions unless you’ve explicitly added the declaration even though they might throw checked exceptions at runtime. Unfortunately, the Java compiler attempts to be clever and will complain if you try to catch a checked exception in Java when it believes there’s no way that the exception can be thrown. If you run into this and need to explicitly catch a checked exception generated in <strong>Groovy</strong> code, you may need to add a throws declaration to the Groovy code just to keep javac happy.</p>
<h2>Summary</h2>
<p>This article covered one of Groovy’s control structures: exiting blocks and methods early. We haven’t seen any big surprises: everything turned out to be like Java, enriched with a bit of Groovy flavor. The only structural difference is the for loop. Exception handling is very similar to Java, minus the requirement to declare checked exceptions.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/04/exiting-blocks-and-methods-in-groovy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Objects in Groovy</title>
		<link>http://www.javabeat.net/2011/04/objects-in-groovy/</link>
		<comments>http://www.javabeat.net/2011/04/objects-in-groovy/#comments</comments>
		<pubDate>Tue, 26 Apr 2011 00:10:25 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=680</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>This article is based on Groovy in Action, Second Edition, to be published on Summer 2011. It is being reproduced here by permission from Manning Publications. Manning publishes MEAP (Manning Early Access Program,) eBooks and pBooks. MEAPs are sold exclusively through Manning.com. All pBook purchases include free PDF, mobi and epub. When mobile formats become [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><em>This article is based on <a href="http://www.manning.com/koenig2/" target="_blank">Groovy in Action, Second Edition</a>, to be published on Summer 2011. It is being reproduced here by permission from <a href="http://www.manning.com" target="_blank">Manning Publications</a>. Manning publishes MEAP (Manning Early Access Program,) eBooks and pBooks. MEAPs are sold exclusively through Manning.com. All pBook purchases include free PDF, mobi and epub. When mobile formats become available all customers will be contacted and upgraded. Visit Manning.com for more information. [ <span style="color: red;"><span style="text-decoration: underline;"><strong>Use promotional code 'java40beat' and get 40% discount on eBooks and pBooks</strong></span> </span>]</em></p>
<h2>Introduction</h2>
<p>In <strong>Groovy</strong>, everything is an object. It is, after all, an object-oriented language. <strong>Groovy</strong> doesn’t have the slight fudge factor of Java, which is object-oriented apart from some built-in types. In order to explain the choices made by <strong>Groovy</strong>’s designers, we’ll first go over some basics of Java’s type system. We will then explain how <strong>Groovy</strong> addresses the difficulties presented and, finally, examine how <strong>Groovy</strong> and Java can still interoperate with ease due to automatic boxing and unboxing where necessary.</p>
<h2>Java’s type system—primitives and references</h2>
<p>Java distinguishes between primitive types (such as boolean, short, int, float, double, char, and byte) and reference types (such as Object and String). There is a fixed set of primitive types and these are the only types that have value semantics, where the value of a variable of that type is the actual number (or character, or true/false value). You cannot create your own value types in Java.</p>
<p>Reference types (everything apart from primitives) have reference semantics; the value of a variable of that type is only a reference to an object. Readers with a C/C++ background may wish to think of a reference as a pointer—it’s a similar concept. If you change the value of a reference type variable that has no effect on the object it was previously referring to, you’re just making the variable refer to a different object or to no object at all. The reverse is true too: changing the contents of an object doesn’t affect the value of a variable referring to that object.</p>
<p>You cannot call methods on values of primitive types, and you cannot use them where Java expects objects of type java.lang.Object. For each primitive type, Java has a wrapper type&#8211;a reference type that stores a value of the primitive type in an object. For example, the wrapper for int is java.lang.Integer.</p>
<p>On the other hand, operators such as * in 3*2 or a*b are not supported for arbitrary1 reference types, but only for primitive types (with the notable exception of +, which is also supported for strings).</p>
<p>The <strong>Groovy</strong> code in listing 1 calls methods on seemingly primitive types (first, with a literal declaration and, then, on a variable), which is not allowed in Java, where you need to explicitly create the integer wrapper to convince the compiler. While calling + on strings is allowed in Java, calling the – (minus) operator is not. <strong>Groovy</strong> allows both.</p>
<p><span style="color: red;">Listing 1 <strong>Groovy</strong> allows methods to be called on types that are declared like primitive types in Java</span></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">(60 * 60 * 24 * 365).toString(); // invalid Java
int secondsPerYear = 60 * 60 * 24 * 365;
secondsPerYear.toString(); // invalid Java
new Integer(secondsPerYear).toString();
assert &quot;abc&quot; - &quot;a&quot; == &quot;bc&quot; // invalid Java</pre></td></tr></table></div>

<p>The <strong>Groovy</strong> way looks more consistent and involves some language sophistication that we are going to explore next.</p>
<h2>Groovy’s answer—everything’s an object</h2>
<p>In order to make <strong>Groovy</strong> fully object oriented and because, at the JVM level, Java does not support object-oriented operations such as method calls on primitive types, <strong>Groovy</strong> designers decided to do away with primitive types. When <strong>Groovy</strong> needs to store values that would have used Java’s primitive types, <strong>Groovy</strong> uses the wrapper classes already provided by the Java platform. Table 1 provides a complete list of these wrappers.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/04/122.jpg"><img class="aligncenter size-medium wp-image-1220" title="1" src="http://www.javabeat.net/wp-content/uploads/2011/04/122-300x259.jpg" alt="" width="300" height="259" /></a>Any time you see what looks like a primitive literal value (for example, the number 5, or the Boolean value true) in <strong>Groovy</strong> source code, that’s a reference to an instance of the appropriate wrapper class. For the sake of brevity and familiarity, <strong>Groovy</strong> allows you to declare variables as if they were primitive type variables. Don’t be fooled—the type used is really the wrapper type. Strings and arrays are not listed in table 1 because they are already reference types and not primitive types—no wrapper is needed.</p>
<p>While we have the Java primitives under the microscope, so to speak, it’s worth examining the numeric literal formats that Java and <strong>Groovy</strong> each use. They are slightly different because <strong>Groovy</strong> allows instances of java.math.BigDecimal and java.math.BigInteger to be specified using literals in addition to the usual binary floating-point types. Table 2 gives examples of each of the literal formats available for numeric types in <strong>Groovy</strong>.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/04/216.jpg"><img class="aligncenter size-medium wp-image-1221" title="2" src="http://www.javabeat.net/wp-content/uploads/2011/04/216-300x106.jpg" alt="" width="300" height="106" /></a><a href="http://www.javabeat.net/wp-content/uploads/2011/04/38.jpg"><img class="aligncenter size-medium wp-image-1222" title="3" src="http://www.javabeat.net/wp-content/uploads/2011/04/38-300x199.jpg" alt="" width="300" height="199" /></a>Notice how <strong>Groovy</strong> decides whether to use a BigInteger or a BigDecimal to hold a literal with a G suffix depending on the presence or absence of a decimal point. Furthermore, notice how BigDecimal is the default type of non-integer literals; BigDecimal will be used unless you specify a suffix to force the literal to be a Float or a Double.</p>
<h2>Interoperating with Java—automatic boxing and unboxing</h2>
<p>Converting a primitive value into an instance of a wrapper type is called boxing in Java and other languages that support the same notion. The reverse action—taking an instance of a wrapper and retrieving the primitive value—is called unboxing. <strong>Groovy</strong> performs these operations automatically for you where necessary. This is primarily the case when you call a Java method from <strong>Groovy</strong>. This automatic boxing and unboxing is known as autoboxing.</p>
<p>You’ve already seen that <strong>Groovy</strong> is designed to work well with Java; so, what happens when a Java method takes primitive parameters or returns a primitive return type? How can you call that method from <strong>Groovy</strong>? Consider the existing method in the java.lang.String class: int indexOf (int ch). You can call this method from <strong>Groovy</strong> like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">assert ’ABCDE’.indexOf(67) == 2</pre></td></tr></table></div>

<p>From <strong>Groovy</strong>’s point of view, we’re passing an Integer containing the value 67 (the Unicode value for the letter C), even though the method expects a parameter of primitive type int. <strong>Groovy</strong> takes care of the unboxing. The method returns a primitive type int that is boxed into an Integer as soon as it enters the world of <strong>Groovy</strong>. That way, we can compare it to the Integer with value 2 back in the <strong>Groovy</strong> script.</p>
<p>Figure 1 shows the process of going from the <strong>Groovy</strong> world to the Java world and back.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/04/46.jpg"><img class="aligncenter size-medium wp-image-1219" title="4" src="http://www.javabeat.net/wp-content/uploads/2011/04/46-300x172.jpg" alt="" width="300" height="172" /></a></p>
<p><center><span style="color: red;">Figure 1 Autoboxing in action: An Integer parameter is unboxed to an int for the Java method call, and an int return value is boxed into an Integer for use in <strong>Groovy</strong>.</span></center>All of this is transparent—you don’t need to do anything in the <strong>Groovy</strong> code to enable it. Now that you understand autoboxing, the question of how to apply operators to objects becomes interesting. We’ll explore this question next.</p>
<h2>No intermediate unboxing</h2>
<p>If in 1 + 1 both numbers are objects of type Integer, you may be wondering whether those Integers unboxed to execute the plus operation on primitive types.</p>
<p>The answer is no: <strong>Groovy</strong> is more object-oriented than Java. It executes this expression as 1.plus(1), calling the plus() method of the first Integer object, and passing3 the second Integer object as an argument. The method call returns an Integer object of value 2.</p>
<p>This is a powerful model. Calling methods on objects is what object-oriented languages should do. It opens the door for applying the full range of object-oriented capabilities to those operators.</p>
<h2>Summary</h2>
<p>Let’s summarize. No matter how literals (numbers, strings, and so forth) appear in <strong>Groovy</strong> code, they are always objects. Only at the border to Java are they boxed and unboxed. Operators are shorthand for method calls.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/04/objects-in-groovy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introduction to Groovy Server Pages (GSP)</title>
		<link>http://www.javabeat.net/2011/02/introduction-to-groovy-server-pages-gsp/</link>
		<comments>http://www.javabeat.net/2011/02/introduction-to-groovy-server-pages-gsp/#comments</comments>
		<pubDate>Fri, 18 Feb 2011 13:12:25 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Groovy Server Pages]]></category>
		<category><![CDATA[GSP]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=550</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Introduction This article is about Groovy Server Pages basic concepts. Groovy Server Pages (GSP) is a view technology which can be used for designing web application using Grails Framework. Developing GSP are very much similar to that of designing web pages with Active Server Pages (ASP) and Java Server Pages (JSP) but coding is very [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>Introduction</h2>
<p>This article is about Groovy Server Pages basic concepts. Groovy Server Pages <strong>(GSP) </strong>is a view technology which can be used for designing web application using Grails Framework. Developing <strong>GSP</strong> are very much similar to that of designing web pages with Active Server Pages <strong>(ASP)</strong> and Java Server Pages <strong> (JSP)</strong> but coding is very much simpler and easier than both of them.<br />
Users are provided with facility of having static, dynamic as well as mix of both contents at a time in  a single application.<br />
The output can be dynamically rendered to different forms like : HTML, XML, text and any other format based on Web client request object.If you are beginner in learning groovy, please read <a href="http://www.javabeat.net/articles/16-introduction-to-groovy-scripting-language-1.html">Introduction to Groovy &#8211; Scripting Language</a>.</p>
<h2>Advantages of using GSP using Grails</h2>
<ol>
<li>A <strong>GSP</strong> uses Groovy GString for evaluation of expression generally using ${&#8230;.} but whereas in <strong>JSP EL</strong> expressions are used for the same purpose but they are restricted only to object navigation to overcome this disadvantage JSTL functions can to be written for creating static helper methods, registering them through a taglib descriptor, adding a taglib declaration and finally implementing them using the function.</li>
<li>A developer has been provided with Logical and Iterative tags in <strong>GSP</strong> with safe navigation operator and Elvis operator which<br />
can be implemented easily to fetch the needed results according to their requirement. For example these operators can be implemented in this manner:</p>
<ul>
<ul>
<li>Safe navigation operator :<br />
${book.pages?.no()}</li>
</ul>
</ul>
</li>
<li>Elvis operator : ${totalpages ?: 100}</li>
<li></li>
<li>A <strong>GSP</strong>has ability for invoking methods through Grails dynamic tags which makes it easier to produce well-formed markup:&lt;!&#8211; With a regular tag

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;!-- With a regular tag --&gt;
          &lt;a href=&quot;&lt;g:createLink action=&quot;list&quot; /&gt;&quot;&gt;Click here&lt;/a&gt;
          &lt;!-- As a method call --&gt;
           &lt;a href=&quot;${createLink(action:'list')}&quot;&gt;Click here&lt;/a&gt;</pre></td></tr></table></div>

</li>
<li>Creating and testing custom tag libraries using GSP are very easier then JSP since there is no need for developer to code tld files and taglib declarations.</li>
</ol>
<h2>Basic Setup</h2>
<ol>
<ol>
<li>Install Java SDK 1.4 or above and set the JAVA_HOME environment variable to the location of that SDK.</li>
</ol>
</ol>
<p>The minimum required version of the SDK depends on which version of <strong>Grails</strong> you are using:</p>
<ul>
<ul>
<li>Java SDK 1.4+ for Grails 1.0.x and 1.1.x</li>
</ul>
</ul>
<ul>
<li>Java SDK 1.5+ for Grails 1.2 or greater</li>
</ul>
<ul>
<li>Download the latest <strong>Grails</strong> release and set the GRAILS_HOME and Path environment variable to the extracted archive folder and Grails bin folder respectively.</li>
<li>An integrated development environment like NetBeans 6.5 or above, Eclipse 3.1 or above and plugins has to be download, IntelliJ IDEA, or UltraEdit.</li>
</ul>
<h2>A Simple Example for rendering different outputs to an HTML page</h2>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;html&gt;
	&lt;head&gt;
		&lt;title&gt;GSP&lt;/title&gt;
	&lt;/head&gt;
	&lt;body&gt;
		Welcome!
		&lt;% print 'Welcome!' %&gt; ------------&gt; print method
		&lt;% out &lt;&lt; 'Welcome' %&gt; ------------&gt; out object
		&lt;%= '!' %&gt; ------------&gt; Scriplet
		${'Welcome!'} ------------&gt; GString (Groovy String) style 
	&lt;/body&gt;
&lt;/html&gt;</pre></td></tr></table></div>

<p>Output:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/02/1.jpg"><img class="aligncenter size-medium wp-image-1016" title="1" src="http://www.javabeat.net/wp-content/uploads/2011/02/1-300x224.jpg" alt="" width="300" height="224" /></a></p>
<h2>Comments</h2>
<p>There are three ways of commenting code in <strong>GSP</strong>.</p>
<ul>
<li><strong>HTML Style:</strong> The code commented using this style will be seen in source code as well as data will be sent to browser, but its impact over the output will be disabled.<br />
Example:&lt;!&#8211; out &lt;&lt;code&#8211;!&gt;</li>
<li><strong>JSP Style:</strong> It can be used for commenting a single line of code.<br />
Example:<br />
&lt;%&#8211; out &lt;&lt;code &#8211;%&gt;</li>
<li><strong>GSP Style:</strong> It can be used for commenting larger/multiple block of code.<br />
Example:<br />
%{&#8211; code &#8211;}%</li>
</ul>
<h2>Variables and Scope</h2>
<p>A user can declare variable with in a Scriplet block in this manner: &lt;% vname %&gt; and the same can be accessed using &lt;%= vname %&gt;.</p>
<p><strong>Please note:</strong> vname indicates variable name.</p>
<p>Example to declare a variable of date category can be done like this &lt;%d = new Date() %&gt; and to access the same we can use &lt;%= d %&gt;.</p>
<h3>Predefined Variables and Scope</h3>
<ul>
<li><strong> request:</strong> This variable can be used as one of argument for invoking other service methods like doGet, doPost, etc.. of underlying Servlet in the project since this variable is the instance of HttpServletRequest interface which extends ServletRequest interface to provide request information for HTTP Servlets.</li>
<li><strong>response: </strong>This variable is the instance of HttpServletResponse interface which extends ServletResponse interface and can be<br />
used for sending HTTP specific response for other service methods like doGet, doPost, etc&#8230; This variable can also access different methods of HTTP cookies and header information of web application.</li>
<li><strong>out: </strong>This variable is the instance of responeWriter and can be used for sending response to output stream.</li>
<li><strong>session:</strong> This variable is the instance of HttpSession and can be used for maintaining history of the visitor of that web-site since a unique id per visit is maintained for every web application.</li>
<li><strong>params:</strong> Is a map object which can be used for retrieving request parameters.</li>
<li><strong>flash: </strong>Is a temporary storage map object which can be used for working with flash scope. It maintains key value pairs within session which points to next request value and this value will be cleared out once the request is executed by an application.</li>
<li><strong>application:</strong> It defines a set of methods for communicating with Servlet container through a Servlet. It is instance of<br />
javax.servlet.ServletContext.</li>
<li><strong>applicationContext: </strong>Is the instance of Spring ApplicationContext which extends ListableBeanFactory,  HierarchicalBeanFactory, MessageSource, ApplicationEventPublisher, ResourcePatternResolver classes to provide configuration for an application. This object is read-only but can be reloaded if needed.</li>
<li><strong>grailsApplication:</strong>This object is the instance of GrailsApplication which extends ApplicationContextAware class<br />
and can be used to analysis artifacts of Grails Application since user can<br />
access metadata i.e., information regarding controllers, domain classes etc..</li>
<li><strong>webRequest:</strong> Is instance of GrailsWebRequest.</li>
</ul>
<h2>Looping</h2>
<p>Looping in GSP can be achieved in two ways.</p>
<ul>
<li>By <strong>Embedding code</strong> between Scriplet i.e..,  &lt;% %&gt;. For<br />
example consider a scenario where user wants to iterate through a list of two values i.e., User1 and User2 then same can be achieved through below mentioned sample code :</li>
<li>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;html&gt;
&lt;head&gt; &lt;title&gt; GSP &lt;/title&gt;&lt;/head&gt;
&lt;body&gt;
&lt;% [&quot;User1&quot;,User2&quot;&quot;].each { num -&gt; %&gt; 
&lt;p&gt;&lt;%=&quot;Welcome ${num}!&quot; %&gt;&lt;/p&gt;
&lt;%}%&gt;
&lt;/body&gt;
&lt;/html&gt;</pre></td></tr></table></div>

</li>
</ul>
<p>Output:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/02/2.jpg"><img class="aligncenter size-medium wp-image-1017" title="2" src="http://www.javabeat.net/wp-content/uploads/2011/02/2-300x224.jpg" alt="" width="300" height="224" /></a></p>
<ul>
<ul>
<li><strong>Logical Branching</strong> is another way for looping.<br />
For example if the user wants to compare two variable values then the same can be<br />
done as mentioned below.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;html&gt;
&lt;head &gt;
&lt;title&gt; Looping Branching&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;% def a =10 %&gt; ------------&gt; declaring variable can be done by 'def' also.
&lt;% def b =20 %&gt;
&lt;% if (a==b) %&gt;
the given numbers are equal
&lt;% else %&gt;
the given numbers are not equal
&lt;/body&gt;
&lt;/html&gt;</pre></td></tr></table></div>

</li>
</ul>
</ul>
<p>Output:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/02/3.jpg"><img class="aligncenter size-medium wp-image-1019" title="3" src="http://www.javabeat.net/wp-content/uploads/2011/02/3-300x226.jpg" alt="" width="300" height="226" /></a></p>
<p>&nbsp;</p>
<h2>Page Directives:</h2>
<p>By default all the <strong>JSP</strong> page directives are supported by <strong>GSP</strong> and user are provided with facility for creating their own tags according to the requirement by using <strong> GSP Tags</strong>. The <strong>import </strong>directive can be used for importing the necessary classes into a page but by default all the <strong>Groovy</strong> and <strong>GSP tags</strong> are available.<br />
&lt;%@page<br />
import =&#8217;groovy.sql.Sql&#8217; %&gt;<br />
The <strong>contentType</strong> directive allows response to render to any other format than HTML i.e.., output can be render as a plain text or XML format.<br />
&lt;%@page<br />
contentType=&#8217;text/html; charset=UTF-8 %&gt;</p>
<h2>Scripting:</h2>
<p>A multiple line/block of code can be enclosed between Scriplet i.e.., &lt;% &#8230;&#8230;. %&gt;.</p>
<h3>A Sample example of Scripting:</h3>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;head&gt;
&lt;title&gt;Scriptlet Demo&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;% def var = 'test'
if (var == 'test') out&lt;&lt; 'scriptlet demo' %&gt;
&lt;/body&gt;
&lt;/html&gt;</pre></td></tr></table></div>

<p>Output:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/02/4.jpg"><img class="aligncenter size-medium wp-image-1015" title="4" src="http://www.javabeat.net/wp-content/uploads/2011/02/4-300x225.jpg" alt="" width="300" height="225" /></a></p>
<h2>Conclusion:</h2>
<p>This article is all about basic concepts of <strong>Groovy Server Pages (GSP)</strong> and explain concepts like Output Rendering, Comments, Variable declarations, Predefined Variables as well as Scope, Looping, Page directives and Scripting with the related demos.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/02/introduction-to-groovy-server-pages-gsp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Groovy for Domain-Specific Languages</title>
		<link>http://www.javabeat.net/2010/10/groovy-for-domain-specific-languages/</link>
		<comments>http://www.javabeat.net/2010/10/groovy-for-domain-specific-languages/#comments</comments>
		<pubDate>Fri, 08 Oct 2010 00:35:38 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=1668</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Groovy for Domain-Specific Languages The Java virtual machine runs on everything from the largest mainframe to the smallest microchip and supports every conceivable application. But Java is a complex and sometimes arcane language to develop with. Groovy allows us to build targeted singlepurpose minilanguages, which can run directly on the JVM alongside regular Java code. [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><H1><CENTER><b>Groovy</b> for Domain-Specific Languages</CENTER></H1><br />
<P>The Java virtual machine runs on everything from the largest mainframe to the smallest<br />
microchip and supports every conceivable application. But Java is a complex and<br />
sometimes arcane language to develop with. <b>Groovy</b> allows us to build targeted singlepurpose<br />
minilanguages, which can run directly on the JVM alongside regular Java code.</P><br />
<P>This book provides a comprehensive tutorial on designing and developing mini<b>Groovy</b>based<br />
Domain-Specific Languages. It is a complete guide to the development of several<br />
miniDSLs with a lot of easy-to-understand examples. This book will help you to gain all<br />
of the skills needed to develop your own <b>Groovy</b>-based DSLs.</P><br />
<P><I><b>Groovy</b> for Domain-Specific Languages</I> guides the reader from the basics through to the<br />
more complex meta-programming features of <b>Groovy</b>. The focus is on how the <b>Groovy</b><br />
language can be used to construct domain-specific minilanguages. Practical examples are<br />
used throughout to demystify these seemingly complex language features and to show<br />
how they can be used to create simple and elegant DSLs. The examples include a quick<br />
and simple <b>Groovy</b> DSL to interface with Twitter.</P><br />
<P>The book concludes with a chapter focusing on integrating <b>Groovy</b>-based DSL in such a<br />
way that the scripts can be readily incorporated into the reader&#8217;s own Java applications.<br />
The overall goal of this book is to take Java developers through the skills and knowledge<br />
they need to start building effective <b>Groovy</b>-based DSLs to integrate into their<br />
own applications.</P></p>
<ul>
<li>Buy <a href="http://astore.amazon.com/javabeat-20?_encoding=UTF8&#038;node=33" target="_blank">Groovy Books</a> in <a href="http://astore.amazon.com/javabeat-20" target="_blank">Java Books</a> Store</li>
</ul>
<p><H1>What This Book Covers</H1><br />
<P>Chapter 1, <I>Introduction to DSL and <b>Groovy</b></I>, discusses how DSLs can be used in place of<br />
general-purpose languages to represent different parts of a system. You will see how<br />
adding DSLs to your applications can open up the development process to other<br />
stakeholders in the development process. You&#8217;ll also see how, in extreme cases, the<br />
stakeholders themselves can even become co-developers of the system by using DSLs<br />
that let them represent their domain expertise in code.</P><br />
<P>Chapter 2, <I><b>Groovy</b> Quick Start</I>, covers a whistle-stop tour of the <b>Groovy</b> language. It also<br />
touches on most of the significant features of the language as a part of this tour.</P><br />
<P>Chapter 3, <I><b>Groovy</b> Closures</I>, covers closures in some depth. It covers all of the important<br />
aspects of working with closures. You can explore the various ways to call a closure and<br />
the means of passing parameters. You will see how to pass closures as parameters to<br />
methods, and how this construct can allow us to add miniDSL syntax to our code.</P><br />
<P>Chapter 4, <I>Example DSL: GeeTwitter</I>, focuses on how we can start with an existing Javabased<br />
APiand evolve it into a simple user-friendly DSL that can be used by almost<br />
anybody. You&#8217;ll learn the importance of removing boilerplate code and how you can<br />
structure our DSL in such a way that the boilerplate is invisible to our DSL users.</P><br />
<P>Chapter 5, <I>Power <b>Groovy</b> DSL Features</I>, covers all of the important features of the<br />
<b>Groovy</b> language, and looks in depth at how some of these features can be applied to<br />
developing DSLs.</P><br />
<P>Chapter 6, <I>Existing <b>Groovy</b> DSLs</I>, discusses some existing <b>Groovy</b> DSLs that are in<br />
current use and are free to download.</P><br />
<P>Chapter 7, <I>Building a Builder</I>, explains how <b>Groovy</b> provides two useful support classes<br />
that make it much simpler to implement our own builders than if we use the MOP. You&#8217;ll<br />
see how to use BuilderSupport and FactoryBuilderSupport to create our own<br />
builder classes.</P><br />
<P>Chapter 8, <I>Implementing a Rules DSL</I>, takes a look at <b>Groovy</b> bindings to see how they<br />
can be used in our DSL scripts. By placing closures strategically in the binding, you can<br />
emulate named blocks of code. You can also provide built-in methods and other<br />
shorthand by including closures and named Boolean values in the binding. These<br />
techniques can be used to a great effect to write DSL scripts that can be read and<br />
understood by stakeholders outside of the programming audience.</P><br />
<P>Chapter 9, <I>Integrating it all</I>, covers the many different ways in which you can integrate<br />
<b>Groovy</b> code into Java. You&#8217;ll explore the issues around tightly integrating the two<br />
languages at compile time. You&#8217;ll see how this can lead to dependency issues arising<br />
when Java code references <b>Groovy</b> classes and vice versa. You&#8217;ll take a look at how you<br />
can use dependency injection frameworks like Spring to resolve some of these issues.</P><br />
<H1><CENTER>Building a Builder</CENTER></H1><br />
<P>Builders are a powerful feature of <b>Groovy</b>. The <b>Groovy</b> libraries contain an<br />
expanding set of Builders for everything from XML and HTML markup to managing<br />
systems via JMX. Even so you will always come across circumstances where the<br />
semantics of a builder would be useful in your own application.</P><br />
<P>We&#8217;ve seen how to build a rudimentary builder by using the <b>Groovy</b> MOP and<br />
pretended methods in Chapter 5. Thankfully, the <b>Groovy</b> libraries provide us with<br />
easier means of developing our own builders. In this chapter, we will look at some of<br />
the ways in which we can use <b>Groovy</b> and the MOP to create our own builder classes.</P><br />
<UL><br />
<LI>To begin with, we will recap the <b>Groovy</b> features that enable the <b>Groovy</b><br />
builder pattern in order to understand how they work.</LI><br />
<LI>We will look at how to build a rudimentary builder with features from the<br />
<b>Groovy</b> MOP.</LI><br />
<LI>We will implement our own database seed data Builder by using two of<br />
the builder support classes provided in <b>Groovy</b>: BuilderSupport and<br />
FactoryBuilderSupport.</LI><br />
</UL><br />
<H1>Builder code structure</H1><br />
<P>The real beauty of <b>Groovy</b>&#8216;s builder paradigm is the way in which it maps the<br />
naturally nested block structure of the language to the construction process.<br />
The process of defining parent-child relationships between objects through nested<br />
code blocks is well-established through other markup languages, such as<br />
XML and HTML.</P><br />
<P>The transition from writing XML or HTML to the <b>Groovy</b>Markup equivalent<br />
is an easy one. To make use of a builder, we don&#8217;t need to have any intimate<br />
understanding of the <b>Groovy</b> MOP or of how the builder is implemented. We<br />
just need to know how to write the builder code so that it conforms to the correct<br />
language semantics. The code structure of the builder pattern relies on just a few<br />
<b>Groovy</b> language features.</P><br />
<UL><br />
<LI>Closure method calls: The distinctively nested block structure in the builder<br />
pattern is facilitated by <b>Groovy</b>&#8216;s special handling of closures when they are<br />
passed as method parameters. This allows the closure block to be declared<br />
inline after the other method call parameters.</LI><br />
<LI>Closure method resolution: When a method is invoked within the body of a<br />
closure and that method does not exist in the closure instance, <b>Groovy</b> uses<br />
a resolve strategy to determine which object (if any) should be tried to locate<br />
that method.</LI><br />
<LI>Pretended methods: The <b>Groovy</b> MOP allows us to respond to method<br />
calls that do not exist in a class—in other words to &#8220;pretend&#8221; that these<br />
methods exist.</LI><br />
<LI>Named parameters: When we pass a map parameter to a method, we can<br />
declare the individual map elements alongside the other method parameters,<br />
giving the effect of a named parameter list.</LI><br />
<LI>Closure delegate: Changing the delegate of a closure allows another class to<br />
handle its method calls. When we change the delegate to a builder class, this<br />
allows the builder to orchestrate how the method calls are handled.</LI><br />
</UL><br />
<H2>Closure method calls</H2><br />
<P>When we declare a <b>Groovy</b> method that accepts a closure as its last parameter,<br />
<b>Groovy</b> allows us to define the body of the inline closure immediately after the<br />
method call containing the other parameters. A method call followed by an inline<br />
closure block has all the appearance of being a named block of code. It&#8217;s when we<br />
nest these method calls within each other that we get the distinctive builder-style<br />
code blocks.</P><br />
<P>This style of coding is not unique to builders. We can nest other method calls in<br />
the same way. In the following example, we have three methods defined within a<br />
script: <B>method1(), method2(),</B> and <B>method3()</B>. Nesting calls to these methods gives us<br />
some code that is very similar to a builder block, but is not actually a builder block.<br />
The cool thing about the builder pattern is that it uses this existing feature from the<br />
language and turns it into a whole new coding paradigm.</P><br />
<P><CENTER><IMG SRC="images/2010/10/Building-a-Builder/1.jpg"/></CENTER></P><br />
<P>The success of building our own b uilder class by using the <b>Groovy</b> MOP depends<br />
largely o n understanding the sequence in which these methods get called. The<br />
output gives us an idea of what might be happening and what the true sequence of<br />
events is. Let&#8217;s decorate the code a little to show what is happening. The comments<br />
show what scope we are running in.</P><br />
<P><PRE><CODE><br />
	// Script scope<br />
	method1(param: &#8220;one&#8221;) { // Closure1 scope<br />
		method2 { // Closure2 scope<br />
			method3 &#8220;hello&#8221;<br />
		} // End Closure2<br />
		method1( 123 ) { // Closure3 scope<br />
			method1 ( &#8220;nested&#8221; ) { // Closure4 scope<br />
				method3 10<br />
			} // End Closure4<br />
		} // End Closure3<br />
	} // End Closure1<br />
</CODE></PRE></P><br />
<P>The main block of code runs within the scope of the script. Each inline closure is in<br />
fact an anonymous instance of a C losure object. For the purpose of this exercise we<br />
will name these instances Closure1 to Closure4. The first call to m ethod1() occurs<br />
in the outer scope of the script so we would expect this method to be passed to the<br />
script instance. The subsequent method calls all happen within the scope of one or<br />
other of the anonymous closure instances, so we expect these methods to be invoked<br />
on the individual closure instances. The following sequence diagram illustrates this:</P><br />
<P><CENTER><IMG SRC="images/2010/10/Building-a-Builder/2.jpg"/></CENTER></P><br />
<H2>Resolve Strategy: OWNER_FIRST</H2><br />
<P>The one problem with the previous diagram is that we know that the closure<br />
instances don&#8217;t implement the method1() t o method3() methods. So this sequence<br />
diagram shows what methods are initially called, but it does not show what methods<br />
actually get called. When <b>Groovy</b> makes a call to a method on a closure, it does not<br />
always expect it to be present.</P><br />
<P>If a method is not present in the closure itself, <b>Groovy</b> will try to find it by looking<br />
in the owner of the closure, or its delegate, or both. The order in which this occurs<br />
is called the <B>resolve strategy</B> of the closure. The default resolve strategy is OWNER_<br />
FIRST, which means that the owner of the closure will be queried first for the<br />
method, followed by the delegate. If the owner of the closure happens to be another<br />
closure, then the resolve strategy will continue its search for a match in the owner of<br />
the owner and so on, until a match is found or the outer scope is reached.</P><br />
<P><PRE><CODE><br />
	The resolve strategy can be changed for a closure by calling<br />
	Closure.setResolveStrategy. We can change the resolve strategy to<br />
	any of the following self-explanatory strategies: OWNER_FIRST, OWNER_<br />
	ONLY, DELEGATE_FIRST, DELEGATE_ONLY, and NONE.<br />
</CODE></PRE></P><br />
<P>Although the preceding sequence diagram refl ects the first port of call for e ach<br />
method invocation, what in fact happens is that the resolve strategy kicks in and<br />
the method calls will percolate out through the closure instances. A match will<br />
eventually be found in the script instance, which is the only place where the actual<br />
methods exist. Therefore, the actual calling sequence is better represented as follows:</P><br />
<P><CENTER><IMG SRC="images/2010/10/Building-a-Builder/3.jpg"/></CENTER></P><br />
<P>The insight that <b>Groovy</b> designers had when designing the builder pattern was that<br />
this natural nesting of closures could be used to map to any construction process that<br />
involved a parent-child type of relationship. Even without using a builder class, we<br />
can nest closures&#8217; method calls to create a pseudo builder. In the next example, we<br />
declare three methods that we can use to construct a rudimentary tree structure out<br />
of map objects.</P><br />
<P>The root() method creates the initial tree map and inserts a root element into it. We<br />
can nest as many levels deep as we like with the nod e() method, as it will remember<br />
its parent node and add sub nodes to it. The leaf() method is the only one to take a<br />
value and it does not expect to be passed a closure, as it will create the leaf elements<br />
in the tree structure.</P><br />
<P><PRE><CODE><br />
	def current<br />
	def root (Closure closure) {<br />
		def tree = [:]<br />
		def root = [:]<br />
		tree["root"] = root<br />
		def parent = current<br />
		current = root<br />
		closure.call()<br />
		current = parent<br />
		return tree<br />
	}<br />
	def node (key, Closure closure) {<br />
		def node = [:]<br />
		current[key] = node<br />
		def parent = current<br />
		current = node<br />
		closure.call()<br />
		current = parent<br />
	}<br />
	def leaf (key, value ) {<br />
		current[key] = value<br />
	}<br />
	// pseudo builder code<br />
	def tree = root {<br />
		node (&#8220;sub-tree-1&#8243;) {<br />
			leaf &#8220;leaf-1&#8243;, &#8220;leaf object 1&#8243;<br />
		}<br />
		node (&#8220;sub-tree-2&#8243;){<br />
			node (&#8220;node-1&#8243;){<br />
				leaf &#8220;leaf-2&#8243;, &#8220;leaf object 2&#8243;<br />
			}<br />
		}<br />
	}<br />
	assert tree == [<br />
		root: [<br />
			"sub-tree-1": [<br />
				"leaf-1": "leaf object 1"<br />
			],<br />
			&#8220;sub-tree-2&#8243;: [<br />
				"node-1": [<br />
					"leaf-2": "leaf object 2"<br />
				]<br />
			]<br />
		]<br />
	]<br />
</CODE></PRE></P><br />
<H2>Pretended methods</H2><br />
<P>Many <b>Groovy</b> builders rely on the ability to describe arbitrarily-named elements.<br />
When we make use of markup builders to generate XML, we need to be able to<br />
insert whatever tag names are required to conform to the schema that we are using.<br />
Given that elements are created in method calls, we also need to be able to make<br />
arbitrarily- named method calls during the markup process.</P><br />
<P>With <b>Groovy</b>, we can respond to methods that don&#8217;t exist as concrete methods of<br />
a class. The term we use for this type of methods is <B>pretended methods</B>. <b>Groovy</b><br />
provides two means for implementing a pretended method.</P><br />
<H2>invokeMethod</H2><br />
<P>The PoorMansTagBuilder class that we covered in Chapter 5 uses invokeMethod as<br />
a means of pretending methods. The Poo rMansTagBuilder class works by handling<br />
all method calls to the builder, and invoking the closure argument manually. With<br />
invokeMethod, we can respond appropriately to any arbitrary method call. In this<br />
case, we output the appropriate XML tags.</P><br />
<P><PRE><CODE><br />
	class PoorMansTagBuilder {<br />
		int indent = 0<br />
		Object invokeMethod(String name, Object args) {<br />
			indent.times {print &#8221; &#8220;}<br />
			println &#8220;&lt;${name}&gt;&#8221;<br />
			indent++<br />
			args[0].delegate = this // Change delegate to the builder<br />
			args[0].call()<br />
			indent&#8211;<br />
			indent.times {print &#8221; &#8220;}<br />
			println &#8220;&lt;/${name}&gt;&#8221;<br />
		}<br />
	}<br />
</CODE></PRE></P><br />
<P>This is a simple case that we are using just to illustrate the mechanism. Although the<br />
technique works for simple cases, extending it to implement a more complete<br />
tag builder would rapidly result in complex and hard-to-maintain code.</P><br />
<H2>methodMissing</H2><br />
<P>Since <b>Groovy</b> 1.5, an alternative to invokeMethod was provided. The<br />
methodMissing mechanism differs slightly from invokeMethod, as it is only called<br />
when a method call fails to be dispatched to any concrete method. To update the<br />
PoorMansTagBuilder for using methodMissing instead of invokeMethod, all we<br />
need to do is replace the method name that we declare.</P><br />
<P><PRE><CODE><br />
	class PoorMansTagBuilder {<br />
		int indent = 0<br />
		def methodMissing(String name, args) {<br />
			indent.times {print &#8221; &#8220;}<br />
			println &#8220;&lt;${name}&gt;&#8221;<br />
			indent++<br />
			args[0].delegate = this // Change delegate to the builder<br />
			args[0].call()<br />
			indent&#8211;<br />
			indent.times {print &#8221; &#8220;}<br />
			println &#8220;&lt;/${name}&gt;&#8221;<br />
		}<br />
	}<br />
	def builder = new PoorMansTagBuilder ()<br />
	builder.root {<br />
		level1{<br />
			level2 {<br />
			}<br />
		}<br />
	}<br />
</CODE></PRE></P><br />
<H2>Closure delegate</H2><br />
<P>Earlier, we looked at how to code a pseudo builder using, methods declared within<br />
a script. The resolve strategy in that example passed method calls in the nested<br />
closure up to the owner of the closure. The builder block in the previous example is<br />
also in the scope of a script. Let&#8217;s decorate it as we did before, to identify the various<br />
anonymous closure instances.</P><br />
<P><PRE><CODE><br />
	// method root() called on PoorMansTagBuilder<br />
	builder.root { // Closure1<br />
		// method level1 called on Closure1 instance<br />
		level1{ // Closure2<br />
			// method level2 called on Closure2 instance<br />
			level2 { // Closure3<br />
			}<br />
		}<br />
	}<br />
</CODE></PRE></P><br />
<P>The first method call to root() is made against the builder instance, so it will be<br />
handled directly by Poo rMansTagBuilder.methodMissing(). Nested method<br />
calls will first be dispatched to the enclosing closure. The lev el1() and lev el2()<br />
methods won&#8217;t be found in the closure instances, so we would normally expect the<br />
resolve strategy to dispatch these methods up the chain of owners until a method<br />
is found. This normal dispatch chain would end up at the script instance, so these<br />
methods would cause a MethodMissingException to be thrown.</P><br />
<P>The secret of how this works is in the handling of the delegate for closure instances.<br />
The builder block starts with a direct method call onto the builder instance, builder.<br />
root(). Anonymous closure, Closure1, is passed as a par ameter. The call to root()<br />
will fail and fall through to methodMissing. In this simple example, arg[0] is<br />
always the closure because we are not processing parameters on our tags. A more<br />
sophisticated version would need to scan the parameters for the closure instance.</P><br />
<P>At this point we have access to the closure, so we can set its delegate to the builder<br />
instance. Now when the level1() and level2() calls are encountered, the resolve<br />
strategy will try the owner first and then try the delegate as follows:</P><br />
<UL><br />
<LI>The level1() call will not be resolved in Closure1. It won&#8217;t be found<br />
in the owner of Closure1, which is the script, but it will be resolved in<br />
the delegate,which is the builder instance. PoorMansTagBuilder.<br />
methodMissing will field the method and also set the delegate for the<br />
anonymous closure, Closure2.</LI><br />
<LI>The level2() call ha ppens in the scope of Closure2 but will not be resolved<br />
there. First its owner, Closure1, will be tried, and then its delegate, which<br />
once again is the builder instance.</LI><br />
</UL></p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<h2>Groovy Articles</h2>
<ul>
<li>Buy <a href="http://astore.amazon.com/javabeat-20?_encoding=UTF8&#038;node=33" target="_blank">Groovy Books</a> in <a href="http://astore.amazon.com/javabeat-20" target="_blank">Java Books</a> Store</li>
<li><a href="http://www.javabeat.net/articles/16-introduction-to-groovy-scripting-language-1.html">Introduction to Groovy &#8211; Scripting Language</a></li>
<li><a href="http://www.javabeat.net/articles/groovy/1/">Groovy Articles</a></li>
<li><a href="http://www.javabeat.net/articles/62-closures-in-groovy-1.html">Closures in Groovy</a></li>
<li><a href="http://www.javabeat.net/articles/58-web-development-in-groovy-using-groovlets-1.html">Web Development in Groovy using Groovlets</a></li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2010/10/groovy-for-domain-specific-languages/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Groovy Interview Questions and FAQs</title>
		<link>http://www.javabeat.net/2010/08/groovy-interview-questions-and-faqs/</link>
		<comments>http://www.javabeat.net/2010/08/groovy-interview-questions-and-faqs/#comments</comments>
		<pubDate>Thu, 05 Aug 2010 00:43:15 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Interview Questions]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=460</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Groovy Interview Questions and FAQs &#8211; 1 What is Groovy? Groovy is a powerful high level language for the Java platform which compiles down to Java bytecode. Think of it as a Ruby or Python like language that is tightly integrated with the Java platform &#8211; allowing you the same powerful and concise coding syntax [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>Groovy Interview Questions and FAQs &#8211; 1</h2>
<h2>What is Groovy?</h2>
<p>Groovy is a powerful high level language for the Java platform which compiles down to Java bytecode.<br />
Think of it as a Ruby or Python like language that is tightly integrated with the Java platform &#8211; allowing you the same powerful and concise coding syntax as Ruby or Pyton but allowing you to stay on the JVM and protect your investment in J2SE, J2EE and all the plethora of great useful Java code out there.</p>
<h2>Why Groovy? Why don&#8217;t you just use Jython, JRuby, bsh, rhino, pnuts, &#8230;</h2>
<p>Firstly ports of existing languages like Python, Ruby, Smalltalk and JavaScript to the JVM are a good thing and we welcome them. If you already use and/or are fond of these languages please be our guests to use the Java-port of them.One of the main design goals of Groovy is to be a scripting language for Java developers to use. So we wanted to reuse both Java&#8217;s semantics and the whole set of J2SE APIs rather than introduce a port of a different language with different semantics and APIs to learn and implement/maintain.</p>
<p>e.g. in Groovy, java.lang.Object is the root of the object hierarchy, Object.equals(), Object.hashCode() and Comparable are used for comparions and lookups of objects, that java.util.List and java.util.Map are used for collections, Java Beans are fully supported and that Java and Groovy classes are interchangable inside the<br />
VM. Groovy is built on top of the J2SE APIs, rather than having 2 parallel platforms etc.<br />
In other words we wanted the Groovy language to be very easy to pick up if you&#8217;re already a Java developer and for there to be a very small number of new APIs to learn. By this statement we&#8217;re not implying that Python / Ruby / JavaScript are hard to learn per se &#8211; its just there&#8217;s more to know, things are more different and there&#8217;s more APIs to learn</p>
<p>Think of Groovy as a Ruby or Python like language that is tightly integrated with the Java platform (as opposed to the Unix/Posix command shell and C-libraries) &#8211; allowing you the same powerful and concise coding syntax as Ruby or Pyton but allowing you to stay on the JVM and protect your investment in J2SE, J2EE and all the plethora of great useful Java code out there without any adapter layers or parallel API sets etc. There is a more detailed set of comparisio ther languages here</p>
<h2>What are the dependencies for Groovy?</h2>
<p>As well as Java 1.4 and the Groovy jar we also depend at runtime on the ASM library.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<h2>What is the licence for Groovy?</h2>
<p>Groovy is open source using a BSD / Apache style licence</p>
<h2>I get errors when trying to run groovy, groovysh or groovyConsole. Whats wrong?</h2>
<p>Groovy depends on JDK 1.4 or later. Common errors people have when trying to run Groovy is that there&#8217;s an old groovy jar on the CLASSPATH somewhere (have you checked in java/lib/ext?) or that JAVA_HOME points to an old JDK before JDK 1. For more help please see this description of running Groovy code.</p>
<h2>How can I add stuff to the classpath when running things in groovysh or groovy?</h2>
<p>You can add things to your $CLASSPATH environment variable. Another popular option is to create a .groovy/lib directory in your home directory and add whatever jars you want to be available by default. e.g. if you wish to connect to your favourite JDBC database and do some scripting with it then add your JDBC driver to ~/.groovy/lib.</p>
<h2>Things work if I use Suns conventions and put { on the same line, but if I add a new line things break?</h2>
<p>When using closures with method calls we have some syntax sugar in Groovy which is sensitive to whitespace (newlines to be preceise). Please see this description in common gotchas for a full description.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2010/08/groovy-interview-questions-and-faqs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Templates in Groovy</title>
		<link>http://www.javabeat.net/2008/04/templates-in-groovy/</link>
		<comments>http://www.javabeat.net/2008/04/templates-in-groovy/#comments</comments>
		<pubDate>Sun, 06 Apr 2008 12:15:30 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Templates in Groovy]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=167</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>1) Introduction In this article, we will expose the various APIs for processing Templates in Groovy. A template can be thought of some static content along with some well-defined place-holders. These templates can be re-used any number of times by simply copying it and substituting the place-holders with some appropriate values. The first section of [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>1) Introduction</h2>
<p align="justify">In this article, we will expose the various APIs for processing <em><strong>Templates in Groovy</strong></em>. A <em><strong>template</strong></em> can be thought of some static content along with some well-defined place-holders. These templates can be re-used any number of times by simply copying it and substituting the place-holders with some appropriate values. The first section of the article concentrates on the various types of Template Engines available in Groovy. And the later section of the article guides you in using the Template API. This is not an introductory article about Groovy, so novice readers can read the introductory article <a href="http://www.javabeat.net/2007/06/introduction-to-groovy-scripting-language/">Introductory Article on Groovy</a> before continuing with this article.</p>
<h3 id="Groovy Template API">2) Groovy Template API</h3>
<h4>2.1) Templates</h4>
<p align="justify">As mentioned earlier, generally a template is a static content with <em><strong>well-defined placeholders</strong></em>. For example, consider the following,</p>
<p align="justify">&#8216;[0] and [1] went up the hill&#8217;</p>
<p align="justify">The above content is an example of templated content which is having two place-holders pointed by [0] and [1]. Now this templated content can be re-used any number of times as following by substituting appropriate values,</p>
<p align="justify">&#8216;Jack and Jill went up the hill&#8217;</p>
<p>&#8216;Mary and Rosy went up the hill&#8217;</p>
<p>.<br />
.<br />
.</p>
<p>&#8216;Somebody and Nobody went up the hill&#8217;</p>
<h2>2.2) API Support</h2>
<p align="justify">The necessary support for programming Groovy templates is available in the groovy.text package. This package can be logically broken into three pieces as follows,</p>
<ol>
<li>Representation of a template</li>
<li>Template Engines</li>
</ol>
<p align="justify">We will discuss in detail in the forth coming sections.</p>
<h5>2.2.1) Representation of a template</h5>
<p align="justify">Template in Groovy is represented by the interface <code>groovy.text.Template</code>. A template usually represents some text content and they are often associated with a <em><strong>set of bindings</strong></em>. The set of bindings contains the values for the template text containing place-holders.</p>
<p align="justify">Values can be passed to the template text by calling the Template.make(Map bindings) method.</p>
<h5>2.2.2) Template Engines</h5>
<p align="justify"><em><strong>Template Engines</strong></em> are <em><strong>Factory classes</strong></em> which are used to create Template objects from a variety of sources. The source can be as simple as an ordinary text, from a file or a reader or from an URL. For example, the following code snippet creates a Template object whose content will come from a file,</p>
<pre class="brush: java; title: ; notranslate">File fileContainingTemplate = new File(&quot;template.txt&quot;);
TemplateEngine templateEngine = new SimpleTemplateEngine();
Template templateObject = templateEngine.createTemplate(fileContainingTemplate);</pre>
<h2 id="Code Samples">3) Code Samples</h2>
<h3>3.1) Simple Substitution</h3>
<p align="justify">We will see how to make use of <em><strong>Groovy Template API</strong></em> for text manipulation. To start with, we will consider a simple example in the following code,</p>
<p><strong>ValueInsertion.groovy</strong></p>
<pre class="brush: java; title: ; notranslate">import groovy.text.*

def day = ['day' : 'Holiday']
def message = &quot;Today is ${day} &quot;;

def templateEngine = new SimpleTemplateEngine()
def template = templateEngine.createTemplate(message)

Writable object = template.make(day)
println object</pre>
<p align="justify">The above code declares a map object called <code>day</code> which has one entry (key and value). The key is <code>'day'</code> and the value for the key <code>'day'</code> is Holiday. Next the program creates a template like string object called <code>'message'</code> whose value is <code>'Today is ${day}'</code>. Note that this templated message has a single place-holder which is denoted by <code>${day}</code>. We want this place-holder to replace with the value <code>'Holiday'</code> whose value is taken from the map <code>'day'</code>.</p>
<p align="justify">The next section of the code creates the <em><strong>Simple Template Engine</strong></em> for creating templates. Next, the template object is created for the message by calling the method, <code>TemplateEngine.createTemplate(message)</code>. Note that till now a string object is made to look like a template object with place-holders. For passing values to the templated text, we have to call the method <code>Template.make()</code> by passing in a map of values as shown below,</p>
<pre class="brush: java; title: ; notranslate">Writable object = template.make(day)</pre>
<p align="justify">The return type of this method is a Writable object which will contain the substituted text. In our example, the binding expression in the template text as represented by <code>${day}</code> and the key that we pass for making the template <code>['day' : 'Holiday']</code> should be one and the same.</p>
<p align="justify">The output for the above code is,</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">Today is [&quot;day&quot;:&quot;Holiday&quot;]</pre>
<h3>3.2) JSP Syntax based Substitution</h3>
<p align="justify">Another most common way of using place-holders is to use the <em><strong>JSP-based syntax</strong></em> for coding scriplets. For example, consider the following code,</p>
<p><strong>SimpleTemplateText1.groovy</strong></p>
<pre class="brush: java; title: ; notranslate">import groovy.text.*

def templateMessage =
&quot;Web site:&quot; + &quot;&quot;;

def values = ['webSite' : 'www.javabeat.net',
]

SimpleTemplateEngine templateEngine = new SimpleTemplateEngine ()
def template = templateEngine.createTemplate(templateMessage)

Writable writable = template.make(values)
println writable.toString()</pre>
<p align="justify">In the above example, <code>&lt;%= expression %&gt;</code> has been used instead of <code>${object}</code>. The rest of the code remains the same. However there are minor differences between these two expressions. In the former, the expression is evaluated and the value is inserted whereas in the latter case, the value of the object is directly inserted.</p>
<p align="justify">The output for the above code will be as follows,</p>
<pre class="brush: java; title: ; notranslate">Web site:www.javabeat.net</pre>
<h3>3.3) Evaluating Groovy Code</h3>
<p align="justify">In the above examples, we have seen that the Groovy Expression will be evaluated and the result will be inserted directly into the embedding text. Now, let us see how to evaluate Groovy expressions alone. Consider the example,</p>
<p><strong>SimpleTemplateText2.groovy</strong></p>
<pre class="brush: java; title: ; notranslate">import groovy.text.Template
import groovy.text.SimpleTemplateEngine

def text = 'Weather is  here at '
def binding = [
                &quot;temperature&quot; : &quot;very cold&quot;,
                &quot;location&quot;    : &quot;Bangalore&quot;
                ]

def engine = new SimpleTemplateEngine()
template = engine.createTemplate(text).make(binding)

println template</pre>
<p align="justify">In the above case, the object text has scripts in the following format <code>'&lt;% ... %&gt;'</code>. In such cases, the expression alone will be evaluated and the result wont be appended into the surrounding text. Here is the output of the above program,</p>
<pre class="brush: java; title: ; notranslate">Weather is very cold here at Bangalore</pre>
<h3>3.4) Reading text from file</h3>
<p><strong>ReadTemplateTextFromFile.groovy</strong></p>
<pre class="brush: java; title: ; notranslate">import groovy.text.*
import java.io.*

def templateFile = new File(&quot;.\\src\\mydata.template&quot;)
def data = [
                'name' : 'Raja',
                'designation' : 'Software Engineer',
                'location' : 'Bangalore',
                ]

def engine = new SimpleTemplateEngine()
def template = engine.createTemplate(templateFile)
def writable = template.make(data)

println writable</pre>
<p align="justify">Till now, we have seen that the Groovy template text is hard-coded directly into the source files. Now, let us see how to externalize the template text by keeping it in a file called <code>'mydata.template'</code>. The content of the file is as follows,</p>
<p><strong>mydata.template</strong></p>
<pre class="brush: java; title: ; notranslate">mydata.tempalte

    ${name}
    ${designation}
    ${location}</pre>
<p align="justify">The above XML file has three place-holders for <code>name</code>, <code>designation</code> and <code>location</code>. Back to the source code, we have defined a map of values for these three identifiers like,</p>
<pre class="brush: java; title: ; notranslate">def data = [
    'name' : 'Raja',
    'designation' : 'Software Engineer',
    'location' : 'Bangalore',
]</pre>
<p align="justify">The file object is represented by the object <code>'templateFile'</code> which is shown below,</p>
<pre class="brush: java; title: ; notranslate">def templateFile = new File(&quot;.\\src\\mydata.template&quot;)</pre>
<p align="justify">And this file object is passed to the template engine for reading the text content as follows,</p>
<pre class="brush: java; title: ; notranslate">def template = engine.createTemplate(templateFile)</pre>
<h3>3.5) GString Template Engine</h3>
<p><strong>GStringTemplateText1.groovy</strong></p>
<pre class="brush: java; title: ; notranslate">import groovy.text.*

def templateText =
    &quot;Call me after \n&quot; +
    &quot;We will meet on &quot;;

def valuesForTemplate = [
    'time' : '6.00 OM',
    'day'  : 'Sunday evening'
]

GStringTemplateEngine templateEngine = new GStringTemplateEngine()
def template = templateEngine.createTemplate(templateText)

Writable writable = template.make(valuesForTemplate)
println writable.toString()</pre>
<p align="justify">Various Template Engines are available in Groovy for template processing namely <code>SimpleTemplateEngine</code>, <code>XmlTemplateEngine</code> and <code>GStringTemplateEngine</code>. Till now, we have been using <code>SimpleTemplateEngine</code> for simple cases and if we want to go for template processing with performance in mind, then <code>GStringTemplateEngine</code> will be a better choice. <code>XmlTemplateEngine</code> takes care of reading the template text and writing the substituted text from and back to the XML file for fine tuning purposes and it takes care of formatting also.</p>
<h2>4) Conclusion</h2>
<p align="justify">In this article, we have covered the Groovy Template API. The Template API is very short and simple and it can be used widely for text processing and substitution. In the beginning of this article, we happened to see about Templates along with examples. Following that, we have explored the Template API, along with classes and interfaces with Groovy. To get a feel over the API, this various samples have been provided in the later end of the article.</p>
<p align="justify">The following are some of the popular articles published in Javabeat. Also you can refer the list of <a href="http://www.javabeat.net/category/web-frameworks/groovy/">groovy articles</a> and <a href="http://www.javabeat.net/groovy-and-grails-books/">groovy books</a> from our website. Please read the articles and post your feedback about the quality of the content.</p>
<ul>
<li><a title="Permanent Link to Creating JSON using Groovy" href="http://www.javabeat.net/2012/06/creating-json-using-groovy/" rel="bookmark">Creating JSON using Groovy</a></li>
<li><a title="Permanent Link to Introduction to Groovy Server Pages (GSP)" href="http://www.javabeat.net/2011/02/introduction-to-groovy-server-pages-gsp/" rel="bookmark">Introduction to Groovy Server Pages (GSP)</a></li>
<li><a href="http://www.javabeat.net/2007/06/introduction-to-groovy-scripting-language/">Introduction to groovy</a></li>
</ul>
<p>If you are looking to buy a book, please consider buying <a href="http://www.flipkart.com/beginning-groovy-grails-8184899211/p/itmdyuv8nx8mty7p?pid=9788184899214&amp;affid=suthukrish"> <strong>Beginning Groovy and Grails: From Novice to Professional</strong>.<br />
</a></p>
<p align="justify"><strong>If you are interested in receiving the future java articles from us, please subscribe <a href="http://www.javabeat.net/subscribe/">here</a>.</strong></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2008/04/templates-in-groovy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Closures in Groovy</title>
		<link>http://www.javabeat.net/2008/04/closures-in-groovy/</link>
		<comments>http://www.javabeat.net/2008/04/closures-in-groovy/#comments</comments>
		<pubDate>Sat, 05 Apr 2008 12:14:25 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Closures]]></category>
		<category><![CDATA[Closures in Groovy]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=166</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>1) Introduction In this article, let us look into one of the important features supported in Groovy, the Closures. Groovy is an object-oriented scripting language in which the syntax resembles Java. Not all languages support the concept of Closures directly, although they may provide indirect support, that too with so many limitations and restrictions. This [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>1) Introduction</h2>
<p align="justify">In this article, let us look into one of the important features supported in <em><strong>Groovy</strong></em>, the <em><strong>Closures</strong></em>. <em><strong>Groovy</strong></em> is an object-oriented scripting language in which the syntax resembles Java. Not all languages support the concept of Closures directly, although they may provide indirect support, that too with so many limitations and restrictions. This article will make you familiar with the concepts of Closures and will provide considerable amount of code snippets to make the understanding clearer. This article assumes that the reader is having sufficient knowledge in Groovy Programming and first-time readers may look into the <a href="http://www.javabeat.net/2007/06/introduction-to-groovy-scripting-language/">Introductory Article on Groovy</a> before proceeding with this article.</p>
<h2 id="Closures">2) Closures</h2>
<p align="justify">To say in simple words, a Closure definition is a <em><strong>block of code</strong></em> that can be re-used any number of times. The definition may look more or less like the definition of a function or a method. A Closure resembles a function or a method in many aspects, however there are subtle differences between them. For example, a Closure may take any number of arguments like a function. A Closure has a return value like a method. A closure can be re-used and referenced any number of times and anywhere similar to a method.</p>
<p align="justify">It is clear that a Closure is very similar to a function in many aspects, but the difference is that a Closure can be passed as an argument to a function. A programming language like Java supports similar kind of Closures through anonymous Inner classes. For example, consider the following piece of code,</p>
<pre class="brush: java; title: ; notranslate">Button button = new Button();
button.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent actionEvent)
    {
        // Do something here.
    }
});</pre>
<p align="justify">In the above code, the method <code>Button.addActionListener()</code> will take an argument of type <code>ActionListener</code>. We have defined something which is of type <code>ActionListener</code> and has included a method <code>actionPerformed()</code> within it. This type cannot be used elsewhere in the code since we don&#8217;t have any reference to it. One possible way to re-use the reference is to have something like the following,</p>
<pre class="brush: java; title: ; notranslate">ActionListener actionListener = new ActionListener(){
    public void actionPerformed(ActionEvent actionEvent)
    {
        // Do something here.
    }
};

Button button = new Button();
button.addActionListener(actionListener);</pre>
<p align="justify">To understand the need to have <em><strong>Closures</strong></em>, let us analyze the situation in this way. You have some simple piece of logic (such as printing the state of an object) and you want this logic to be re-used by some common group of objects. The more traditional way to arrive at the solution for this problem is to define a method with suitable argument list and then to call this method. However, in an object-oriented programming language like Java, methods doesn&#8217;t exist on their own. They have to be embedded within a class. It doesn&#8217;t look nice to create a new type (in the form of a class) and to embed a simple behavior in the form of a method. This is where Closures come in. They are simply a named type for some set of statements containing some useful logic. The named type can then be re-used any number of times.</p>
<p align="justify">The same problem exists with <em><strong>callbacks</strong></em>. Classes with the design of call-backs in mind, usually have a well-defined interface along with methods. And the client application (or the caller) has to define an implementation class conforming to the interface which often results in defining new types. This will result in the many smaller classes in the Application. One form of solution to these kind of problems is manifested in the form of Closures.</p>
<h2 id="Groovy Closures">3) Groovy Closures</h2>
<h3>3.1) Simple Closures</h3>
<p align="justify">Let us look into the syntax for defining and making use of Closures. The syntax of a closure definition looks like this,</p>
<pre class="brush: java; title: ; notranslate">ClosureName =
{
    Parameter List -&amp;gt;

    Set of statements.
}</pre>
<p align="justify">The syntax is simple (although it may not look like that at the very first glance). Let us get into the example. If we want to define a closure called <code>'helloClosure'</code>, then we can define something like this,</p>
<pre class="brush: java; title: ; notranslate">helloClosure =
{
    println &quot;Hello&quot;;
}</pre>
<p align="justify">Note that in the above definition, the closure name is <code>'helloClosure'</code> and since we don&#8217;t want this closure to accept any parameters, we have left the list of parameters that should follow after the brace <code>'{'</code> as blank. Next follows the block section which may contain any number of statements.</p>
<p align="justify">Let us look into the following sample,</p>
<p><strong>SimpleClosure.java</strong></p>
<pre class="brush: java; title: ; notranslate">public class SimpleClosure
{
    def testClosure =
    {
        println &quot;Test Closure&quot;;
    }

    public static void main(String[] args)
    {
        ClosureTest object = new ClosureTest();
        object.testClosure();
    }
}</pre>
<p align="justify">We have defined a closure called <code>'testClosure'</code> with the <code>'def'</code> (meaning for definition) keyword. This closure doesn&#8217;t accept any arguments. Simply defining the closure doesn&#8217;t provide any purpose unless someone calls that explicitly. In the main method, we have created an object for the class <code>'SimpleClosure'</code> and have invoked the closure <code>'testClosure'</code> in function-like syntax.</p>
<h3>3.2) Closures with Arguments</h3>
<p align="justify">In this section, let us see how to define Closures that takes arguments. As we have already seen, Closures, like functions may take any number of arguments. For example, consider the following code snippet,</p>
<p><strong>ClosureWithArguments.java</strong></p>
<pre class="brush: java; title: ; notranslate">public class ClosureWithArguments
{
    def addClosure =
    {
        int one, int two -&amp;gt;

        println &quot;Number one is &quot; + one;
        println &quot;Number two is &quot; + two;
        return one + two;
    }

    public static void main(String[] args)
    {
        ClosureWithArguments object = new ClosureWithArguments();
        def result = object.addClosure(10, 20);
        println &quot;Result from closure is &quot; + result;

        result = object.addClosure(130, 230);
        println &quot;Result from closure is &quot; + result;
    }
}</pre>
<p align="justify">In the above code, we have defined a closure called <code>'addClosure'</code>. Note the parameter list (int one, int two) that is following after the brace <code>'{'</code>. Following that is the symbol &#8216;-&gt;&#8217; which is used as a separator between the parameter list and the set of statements to follow. The code prints the arguments passed to this function before returning the result.</p>
<p align="justify">The caller (main method) calls this Closure using the same function-like syntax passing two arguments.</p>
<h3>3.3) Different ways of calling a Closure</h3>
<p align="justify">We have seen how to invoke or call a Closure in the above sections. For example, if the Closure Name is <code>'myClosure'</code>, then this closure can be invoked through the expressioin <code>'myClosure()'</code>.</p>
<p><strong>CallingClosures.java</strong></p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">public class CallingClosures
{
    def testClosure =
    {
        println &quot;Test Closure&quot;;
    }

    public static void main(String[] args)
    {
        CallingClosures object = new CallingClosures();
        object.testClosure();
        object.testClosure.call();
        object.testClosure.doCall();
    }
}</pre>
<p align="justify">However, there are other alternative ways of calling a Closure as mentioned above. Every closure has default methods (implicit methods, so no need to declare them) namely <code>call()</code> and <code>doCall()</code> so we can also call the closures in this manner.</p>
<h3>3.4) The Closure class</h3>
<p align="justify">It should be noted that all Closure definitions will be resolved to some Java class at run-time. So all Closures are just like any other objects. And it is not surprising that the class name of such closure objects seems to be <code>'Closure'</code>. It means that the following code will work fine.</p>
<p><strong>ClosureClassTest.java</strong></p>
<pre class="brush: java; title: ; notranslate">public class ClosureClassTest
{
    def testClosure =
    {
        println &quot;Test Closure&quot;;
    }

    public static void main(String[] args)
    {
        ClosureClassTest object = new ClosureClassTest ();

        Closure closureObjectForTest = object.testClosure;
        closureObjectForTest();
        closureObjectForTest.call();
        closureObjectForTest.doCall();
    }
}</pre>
<p align="justify">The above code tries to assign the closure <code>'testClosure'</code> to the object <code>'closureObjectForTest'</code> which is of type <code>'Closure'</code>. This is perfectly legal, since all Closure objects are of type <code>'Closure'</code>.</p>
<h3>3.5) Closure Currying</h3>
<p align="justify">At times, we may need to create multiple number of Closure objects whose argument lists to some extent will be similar. For example, consider the following Closure <code>'getNoOfRuns'</code> which takes two arguments, one is the name of the country and the other one being the name of the player. And we wish to make Closure calls four times with the following values,</p>
<ul>
<li>Country-&gt; India, PlayerName-&gt; Sachin</li>
<li>Country-&gt; India, PlayerName-&gt; Ganguly</li>
<li>Country-&gt; Pakistan, PlayerName-&gt; Afridi</li>
<li>Country-&gt; Pakistan, PlayerName-&gt; Salman</li>
</ul>
<p align="justify">Examine the first two set of invocations. Both are taking the value <code>'India'</code> as the first argument. And in the 3rd and the 4th invocation, the argument value <code>'Pakistan'</code> is common. Now, analyze the following code where we will see a better way of making invocations to the Closure.</p>
<p><strong>ClosureCurrying.java</strong></p>
<pre class="brush: java; title: ; notranslate">class ClosureCurrying
{

    def getNoOfRuns =
    {
        String country, String playerName -&amp;gt;

        if (country.equals(&quot;India&quot;))
        {
            if (playerName.equals(&quot;Sachin&quot;))
            {
                return 15806;
            }
            else if (playerName.equals(&quot;Ganguly&quot;))
            {
                return 11319;
            }
        }
        else if (country.equals(&quot;Pakistan&quot;))
        {
            if (playerName.equals(&quot;Afridi&quot;))
            {
                return 5226;
            }
            else if (playerName.equals(&quot;Salman&quot;))
            {
                return 1159;
            }
        }
        return -1;
    }

    public static void main(String[] args)
    {
        ClosureCurrying object = new ClosureCurrying();

        def indianTeam = object.getNoOfRuns.curry(&quot;India&quot;);

        def result = indianTeam(&quot;Sachin&quot;);
        println &quot;No. of runs scored by Sachin &quot; + result;

        result = indianTeam(&quot;Ganguly&quot;);
        println &quot;No. of runs scored by Ganguly &quot; + result;

        def pakistanTeam = object.getNoOfRuns.curry(&quot;Pakistan&quot;);

        result = pakistanTeam(&quot;Afridi&quot;);
        println &quot;No. of runs scored by Afridi &quot; + result;

        result = pakistanTeam(&quot;Salman&quot;);
        println &quot;No. of runs scored by Salman &quot; + result;
    }
}</pre>
<p align="justify">We have referenced the Closure <code>'getNoOfRuns'</code> and has called the method <code>'curry()'</code> on that with the value <code>'India'</code> as its argument. Let us imagine that the method <code>'curry()'</code> will create a new object with the countryName being set to <code>'India'</code>. Now if want to get the number of runs for the player <code>'Sachin'</code>, then simply invoke the <em><strong>Curried Closure</strong></em> (the Closure that was obtained after calling the <code>'curry()'</code> method) with the value <code>'Sachin'</code>. The same applies for <code>'Ganguly'</code> and for the rest of the players.</p>
<h3>3.6) Closures as Arguments to another Functions</h3>
<p align="justify">Till now, we have seen how to define and call Closures. In this section, we will see how to pass a Closure as an argument to some other function. Consider the following code snippet,</p>
<p><strong>PassingClosuresTest.java</strong></p>
<pre class="brush: java; title: ; notranslate">class PassingClosuresTest
{

    def testClosure =
    {
        println &quot;Test Closure&quot;;
    }

    void acceptClosure(Closure closure)
    {
        closure.call();
    }

    public static void main(String[] args)
    {
        PassingClosuresTest object =
            new PassingClosuresTest();
        Closure closureObject = object.testClosure;
        object.acceptClosure(closureObject);
    }
}</pre>
<p align="justify">In the above sample, we have defined a Closure called <code>'testClosure'</code> and have defined another method which is taking an argument of type <code>'Closure'</code>. In the main method, we have assigned the <code>'testClosure'</code> to the object <code>'closureObject'</code> which is of type <code>'Closure'</code> and the same is passed to the method <code>'acceptClosure()'</code> method.</p>
<h3>3.7) Making use of Closures</h3>
<p align="justify">In this section, let us make use of Closures being passed as arguments. For example, consider the following Class which wraps the string array objects. The <code>decorate()</code> method accepts an argument of type <code>'Closure'</code>. The logic within the method iterates over the strings and the Closure being passed as argument to this method is invoked by passing the iterated resultant string object itself as argument.</p>
<p><strong>DecoratedStringArrayClosureTest.java</strong></p>
<pre class="brush: java; title: ; notranslate">class DecoratedStringArrayClosureTest
{
    def strs = null;
    public DecoratedStringArrayClosureTest(def strs)
    {
        this.strs = strs;
    }

    public void decorate(Closure closure)
    {
        for (String temp in strs)
        {
            closure.call(temp);
        }
    }

    def DecoratedClosure =
    {
        String element -&amp;gt;
        println &quot;##&quot; + element + &quot;##&quot;;
    }

    public static void main(String[] args)
    {
        def numbers = [&quot;one&quot;, &quot;two&quot;, &quot;three&quot;];
        DecoratedStringArrayClosureTest object =
            new DecoratedStringArrayClosureTest(numbers);

        Closure decoratedClosureObject = object.DecoratedClosure;
        object.decorate(decoratedClosureObject);
    }
}</pre>
<p align="justify">The Decorated Closure decorates the string passed to it by surrounding the string with &#8216;#&#8217; symbols.</p>
<h2>4) Conclusion</h2>
<p align="justify">In this article, we understand the need for <em><strong>Closures</strong></em> and saw how Closures stand as a better replacement for defining a new type even for simpler cases. We also dealt in detail about the various usage cases of Closures in Groovy Scripting Language along with plenty of code samples.</p>
<p align="justify">The following are some of the popular articles published in Javabeat. Also you can refer the list of <a href="http://www.javabeat.net/category/web-frameworks/groovy/">groovy articles</a> and <a href="http://www.javabeat.net/groovy-and-grails-books/">groovy books</a> from our website. Please read the articles and post your feedback about the quality of the content.</p>
<ul>
<li><a title="Permanent Link to Creating JSON using Groovy" href="http://www.javabeat.net/2012/06/creating-json-using-groovy/" rel="bookmark">Creating JSON using Groovy</a></li>
<li><a title="Permanent Link to Introduction to Groovy Server Pages (GSP)" href="http://www.javabeat.net/2011/02/introduction-to-groovy-server-pages-gsp/" rel="bookmark">Introduction to Groovy Server Pages (GSP)</a></li>
<li><a href="http://www.javabeat.net/2007/06/introduction-to-groovy-scripting-language/">Introduction to groovy</a></li>
</ul>
<p>If you are looking to buy a book, please consider buying <a href="http://www.flipkart.com/beginning-groovy-grails-8184899211/p/itmdyuv8nx8mty7p?pid=9788184899214&amp;affid=suthukrish"> <strong>Beginning Groovy and Grails: From Novice to Professional</strong>.<br />
</a></p>
<p align="justify"><strong>If you are interested in receiving the future java articles from us, please subscribe <a href="http://www.javabeat.net/subscribe/">here</a>.</strong></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2008/04/closures-in-groovy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Web Development in Groovy using Groovlets</title>
		<link>http://www.javabeat.net/2007/12/web-development-in-groovy-using-groovlets/</link>
		<comments>http://www.javabeat.net/2007/12/web-development-in-groovy-using-groovlets/#comments</comments>
		<pubDate>Sun, 09 Dec 2007 12:04:02 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Groovlets]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=154</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>1) Introduction In this article, we will learn about how to achieve Web Development using Groovy. Groovy is a scripting language and it has components called Groovlets which sit on top of a Web Server for handling HTTP Requests and Responses similar to Java Servlets. This article will provide an overview about Groovlets in the [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>1) Introduction</h2>
<p align="justify">In this article, we will learn about how to achieve <em><strong>Web Development</strong></em> using Groovy. Groovy is a scripting language and it has components called <em><strong>Groovlets</strong></em> which sit on top of a Web Server for handling <strong><em>HTTP Requests and Responses</em></strong> similar to <em><strong>Java Servlets</strong></em>. This article will provide an overview about Groovlets in the first section and will present several code snippets that will help in simplifying the usage of Groovlets in the subsequent sections. Remember, this is not an introductory article on Groovy and first-time readers are strongly advised to have a look over the <a href="http://www.javabeat.net/2007/06/introduction-to-groovy-scripting-language/">Introductory article on Groovy </a>.</p>
<h2 id="Groovlets">2) Groovlets</h2>
<p align="justify">Before getting into <em><strong>Groovlets</strong></em>, let us look into the basics of a typical Java Web Application. Usually a Web Server will host one or more Web Applications and the Client&#8217;s Requests are handled by Components called Java Servlets which usually sit on top of the Web Server. A Servlet continue to live within the Web Server&#8217;s address space and its life-time will be controlled only by the Web Server. One of the major responsibilities of a Web Server is to match a client request to a particular Servlet in an Application. Typically, this is done in the Application&#8217;s configuration file, usually <code>web.xml</code> file.</p>
<p align="justify">So a Java Servlet can be considered as an extension point which provides some useful services to a Client. The Web Server wraps the Client request and passes a Http Request object to the Servlet. The Servlet retrieves various inputs from the Client and executes some actions accordingly. A Servlet is written in pure Java code and one can see a mix of Java Business logic as well as Html UI Generation in a Servlet.</p>
<p align="justify">Now, let us see the Java Servlet&#8217;s counterpart, Groovlets. <em><strong>Groovlets</strong></em>, or <em><strong>Groovy Pages</strong></em> that end with <em><strong>.groovy</strong></em> extension are processed by Groovy Engine which sits on top of a Web Server. Typically, a <em><strong>Groovy Engine</strong></em> is nothing but a <em><strong>Groovy Servlet</strong></em>. When a client requests for a Groovy page for the very first time, the Groovy Servlet will be invoked (we will configure this in the Application&#8217;s descriptor file) and parses the page to convert into a Java class or a Java Servlet. The Java Servlet is then compiled and an instance of the class will be created by the Web Server. Groovlets are much suitable only for simpler or small Web Applications. Compared to Java Servlets, coding in Groovy will be much simpler.</p>
<p align="justify">In the next few sections, we will see how to develop Groovlets or Groovy pages.</p>
<h2 id="Code Samples">3) Developing a Simple Groovlet</h2>
<p align="justify">In this section, we will see how to write a simple static Groovlet. By the word static, we mean that this Groovlet doesn&#8217;t provide any dynamic content upon request. Instead it will provide a simple Html page back to the Client Browser.</p>
<p align="justify">Let us look into the sample code,</p>
<p><strong>test.groovy</strong></p>
<pre class="brush: java; title: ; notranslate">
html.html
{
    head
    {
        title 'Groovy Test'
    }
    body
    {
        h1 'Groovy page called'
    }
}
</pre>
<p align="justify">Save the above file as <code>test.groovy</code> and deploy the file in a Web Application. For testing purpose, Tomcat Web Container can be used which is running the Groovlet. Make sure that you follow the J2EE standard directory structure for packaging the Web Application.</p>
<p><strong>web.xml</strong></p>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;

&lt;web-app&gt;

    &lt;servlet&gt;
        &lt;servlet-name&gt;GroovyServlet&lt;/servlet-name&gt;
        &lt;servlet-class&gt;groovy.servlet.GroovyServlet&lt;/servlet-class&gt;
    &lt;/servlet&gt;

    &lt;servlet-mapping&gt;
        &lt;servlet-name&gt;GroovyServlet&lt;/servlet-name&gt;
        &lt;url-pattern&gt;*.groovy&lt;/url-pattern&gt;
    &lt;/servlet-mapping&gt;

&lt;/web-app&gt;
</pre>
<p align="justify">The above listing is the deployment descriptor file for the Application. This Deployment Descriptor has two sections. One is the declaration of the Servlet and the other provides the mapping information to call the Groovy Servlet.</p>
<pre class="brush: java; title: ; notranslate">&lt;/p&gt;

&lt;servlet&gt;
    &lt;servlet-name&gt;GroovyServlet&lt;/servlet-name&gt;
    &lt;servlet-class&gt;groovy.servlet.GroovyServlet&lt;/servlet-class&gt;
&lt;/servlet&gt;
</pre>
<p align="justify">The above code snippet declares the Groovy Servlet with the name <code>'GroovyServlet'</code>. Note that the <code>'servlet-class'</code> tag should point to the fully qualified name of the Servlet, in this case it happens to <code>'groovy.servlet.GroovyServlet'</code>. Don&#8217;t forget to add the library classes (<code>groovy-all-1.0.jar</code>, which comes as part of the Groovy Distribution).</p>
<p align="justify">Now, consider the following code snippet,</p>
<pre class="brush: java; title: ; notranslate">&lt;/p&gt;

&lt;servlet-mapping&gt;
    &lt;servlet-name&gt;GroovyServlet&lt;/servlet-name&gt;
    &lt;url-pattern&gt;*.groovy&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
</pre>
<p align="justify">This declaration basically defines a mapping. A mapping generally specifies &#8216;the type of Request to be handled by the corresponding components&#8217;. In the above code snippet, we define the url pattern of the request in the tag <code>'url-pattern'</code> as <code>'*.groovy'</code>. It means that the request that matches this URL pattern will be handled by the Groovy Servlet.</p>
<p align="justify">Before jumping into the next section, let us analyse the code in <code>test.groovy</code>. The <code>test.groovy</code> file looked like this,</p>
<p><strong>test.groovy</strong></p>
<pre class="brush: java; title: ; notranslate">
html.html
{
    head
    {
        title 'Groovy Test'
    }
    body
    {
        h1 'Groovy page called'
    }
}
</pre>
<p align="justify">In Groovy, there are Components called <em><strong>Builders</strong></em>, which stands as the base for building the target. For example, a variant of Builder called <em><strong>Xml Builder</strong></em> can be used to populate XML contents in a file. Similarly, <em><strong>Html Builder</strong></em> can generate Html files. Other notable Builders in Groovy are <em><strong>Ant Builders</strong></em> and <em><strong>Swing Builders</strong></em> which are used to construct Build files and Swing Components respectively.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p align="justify">In our above code, we have used Html builder for populating Html contents which is to be served shortly to the clients. For the above <code>test.groovy</code>, the equivalent generated Html code would be,</p>
<pre class="brush: java; title: ; notranslate">&lt;/p&gt;

&lt;html&gt;

    &lt;head&gt;
        &lt;title&gt;Groovy Test&lt;/title&gt;
    &lt;/head&gt;

    &lt;body&gt;
        &lt;H1&gt;Groovy page called&lt;/H1&gt;
    &lt;/body&gt;

&lt;/html&gt;
</pre>
<h2>4) Groovlet displaying Request Information</h2>
<p align="justify">In this section, we will develop a Groovlet which will display the various request information supplied by the clients. Parallely, we will use the various implicit objects that are available. These implicit objects will be bound to some classes in the Java Servlet API. The following objects are the various commonly used implicit objects that are readily available and can be used in a Groovy Page.</p>
<ul>
<li>application, context &#8211;&gt; Maps to javax.servlet.ServletContext</li>
<li>session &#8211;&gt; Maps to javax.servlet.HttpSession</li>
<li>request &#8211;&gt; Maps to javax.servlet.HttpServlet</li>
<li>response &#8211;&gt; Maps to javax.servlet.HttpResponse</li>
<li>out &#8211;&gt; Maps to response.getWriter()</li>
</ul>
<p><strong>RequestInfo.groovy</strong></p>
<pre class="brush: java; title: ; notranslate">
html.html()
{
    head()
    {
        title 'Request Information'
    }
    body()
    {
        table(border : &quot;2&quot;)
        {
            tr()
            {
                td(&quot;Authentication Type&quot;);
                td(&quot;${request.getAuthType()}&quot;);
            }

            tr()
            {
                td(&quot;Context Path&quot;);
                td(&quot;${request.getContextPath()}&quot;);
            }

            tr()
            {
                td(&quot;HTTP Method&quot;);
                td(&quot;${request.getMethod()}&quot;);
            }

            tr()
            {
                td(&quot;Path Info &quot;);
                td(&quot;${request.getPathInfo()}&quot;);
            }
        }
    }
}
</pre>
<p align="justify">In the above file <code>RequestInfo.groovy</code>, we have again made use of Groovy Builder classes for generating the Html output. Note that for building an Html element that involves attributes, we have use the following syntax,</p>
<pre class="brush: java; title: ; notranslate">&lt;/p&gt;

(attrName : attrValue).
</pre>
<p align="justify">For example, in the above code, if we wish to set the <code>'border'</code> attribute for the table tag as <code>2</code>, then the same has to be mentioned as,</p>
<pre class="brush: java; title: ; notranslate">&lt;/p&gt;

table(border : &quot;2&quot;)
</pre>
<p align="justify">We have decorated the output by embedding the content in a simple Html table. Watch carefully for how we have taken the request information. We have used a simple scripting for the same. For example, consider the following script,</p>
<pre class="brush: java; title: ; notranslate">&lt;/p&gt;

${request.getPathInfo()
</pre>
<p align="justify">Here, the symbol <code>'request'</code> maps to the <code>HttpServletRequest</code> object and <code>getPathInfo()</code> can be treated as a method in the class <code>HttpServletRequest</code>. <code>${Symbol}</code> is the value for the expression. The equivalent Html code is given below,</p>
<pre class="brush: java; title: ; notranslate">&lt;/p&gt;

&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;Request Information&lt;/title&gt;
    &lt;/head&gt;

    &lt;body&gt;
        &lt;table border='2'&gt;
            &lt;tr&gt;
                &lt;td&gt;Authentication Type&lt;/td&gt;
                &lt;td&gt;null&lt;/td&gt;
            &lt;/tr&gt;

            &lt;tr&gt;
                &lt;td&gt;Context Path&lt;/td&gt;
                &lt;td&gt;/Groovy-Groovlets&lt;/td&gt;
            &lt;/tr&gt;

            &lt;tr&gt;
                &lt;td&gt;HTTP Method&lt;/td&gt;
                &lt;td&gt;GET&lt;/td&gt;
            &lt;/tr&gt;

            &lt;tr&gt;
                &lt;td&gt;Path Info &lt;/td&gt;
                &lt;td&gt;null&lt;/td&gt;
            &lt;/tr&gt;

        &lt;/table&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre>
<h2>5) Handling Form Requests</h2>
<p align="justify">In the final section, we will see how to use Groovlets for form submission. As a simple example, let us develop a simple Login form that contains the username/password text-fields along with a submit button. The following code is an example for the same,</p>
<p><strong>Login.groovy</strong></p>
<pre class="brush: java; title: ; notranslate">
html.html()
{
    head()
    {
        title 'Login Form'
    }
    body()
    {
        form(method : 'GET' , action : 'LoginAction.groovy')
        {
            tr()
            {
                td(&quot;Firstname:&quot;)
                input(type : 'text' , name : 'username')
            }

            tr()
            {
                td(&quot;Password:&quot;)
                input(type : 'password' ,  name : 'password')
            }

            tr()
            {
                input(type : 'submit')
            }
        }
    }
}
</pre>
<p align="justify">Note that when the user clicks the form to submit the values, we want some other Groovlet to be called with some appropriate request type. We have achieved the same in the form tag as follows,</p>
<pre class="brush: java; title: ; notranslate">&lt;/p&gt;

form(method : 'GET' , action : 'LoginAction.groovy')
</pre>
<p align="justify">The above form tag details that when this form is submitted, the Groovlet <code>'LoginAction.groovy'</code> will be called as pointed by the <code>'action'</code> attribute with <code>GET</code> as the request type. Following is the complete code listing for <code>'LoginAction.groovy'</code>.</p>
<p><strong>LoginAction.groovy</strong></p>
<pre class="brush: java; title: ; notranslate">
html.html()
{
    head()
    {
        title 'Welcome Page'
    }
    body()
    {
        String username = request.getParameter('username');
        String password = request.getParameter('password');

        if ((username.equals('guest')) &amp;&amp; (password.equals('guest')) )
        {
            h1 &quot;Welcome guest&quot;
        }
        else
        {
            h1 &quot;Unknown user&quot;
        }
    }
}
</pre>
<p align="justify">In the above Groovlet, the request values containing the username and password are taken and appropriate message is displayed depending on their values. It is always possible to compile Groovy code with that of Java code similar to the one we have seen in the above example.</p>
<h2>6) Conclusion</h2>
<p align="justify">This article provided a basic introduction on how to carry out Web Development programming in Groovy. It discussed about the Servlet counterpart that is available in Groovy, which are termed as <em><strong>Groovlets</strong></em>. The later sections on the article concentrated on writing various Groovlets, that display a simple html file to the user, displaying the request information along with form submission.</p>
<p align="justify">The following are some of the popular articles published in Javabeat. Also you can refer the list of <a href="http://www.javabeat.net/category/web-frameworks/groovy/">groovy articles</a> and <a href="http://www.javabeat.net/groovy-and-grails-books/">groovy books</a> from our website. Please read the articles and post your feedback about the quality of the content.</p>
<ul>
<li><a title="Permanent Link to Creating JSON using Groovy" href="http://www.javabeat.net/2012/06/creating-json-using-groovy/" rel="bookmark">Creating JSON using Groovy</a></li>
<li><a title="Permanent Link to Introduction to Groovy Server Pages (GSP)" href="http://www.javabeat.net/2011/02/introduction-to-groovy-server-pages-gsp/" rel="bookmark">Introduction to Groovy Server Pages (GSP)</a></li>
<li><a href="http://www.javabeat.net/2007/06/introduction-to-groovy-scripting-language/">Introduction to groovy</a></li>
</ul>
<p>If you are looking to buy a book, please consider buying <a href="http://www.flipkart.com/beginning-groovy-grails-8184899211/p/itmdyuv8nx8mty7p?pid=9788184899214&amp;affid=suthukrish"> <strong>Beginning Groovy and Grails: From Novice to Professional</strong>.<br />
</a></p>
<p align="justify"><strong>If you are interested in receiving the future java articles from us, please subscribe <a href="http://www.javabeat.net/subscribe/">here</a>.</strong></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2007/12/web-development-in-groovy-using-groovlets/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
