<?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>Intelligrape  Groovy &#38; Grails Blogs &#187; Groovy</title>
	<atom:link href="http://www.intelligrape.com/blog/category/groovy/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.intelligrape.com/blog</link>
	<description></description>
	<lastBuildDate>Thu, 02 Feb 2012 07:48:06 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<image>
			<title>Intelligrape  Groovy &amp; Grails Blogs</title>
			<url>http://www.intelligrape.com/blog/wp-content/uploads/2011/05/favicon2.ico</url>
			<link>http://www.intelligrape.com/blog</link>
			<width></width>
			<height></height>
			<description></description>
		</image>		<item>
		<title>Groovy annotations for ToString and EqualsAndHashCode</title>
		<link>http://www.intelligrape.com/blog/2012/01/29/groovy-annotations-for-tostring-and-equalsandhashcode/</link>
		<comments>http://www.intelligrape.com/blog/2012/01/29/groovy-annotations-for-tostring-and-equalsandhashcode/#comments</comments>
		<pubDate>Sun, 29 Jan 2012 12:10:29 +0000</pubDate>
		<dc:creator>Uday Pratap Singh</dc:creator>
				<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[equals grails domain class]]></category>
		<category><![CDATA[grails domain class template]]></category>
		<category><![CDATA[groovy annotations]]></category>
		<category><![CDATA[groovy equals]]></category>
		<category><![CDATA[groovy hasCode]]></category>
		<category><![CDATA[groovy toString]]></category>
		<category><![CDATA[hashcode grails domain class]]></category>
		<category><![CDATA[tostring grails domain class]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=5037</guid>
		<description><![CDATA[As I am a lazy programmer most of the time I dont implement toString and equals methods on my grails domain classes. I would like to say thanks to Groovy for helping me out and giving me a ready made recipe for this. Now I just need to annotate my class with ToString and EqualAndHashCode [...]]]></description>
			<content:encoded><![CDATA[<p>As I am a lazy programmer most of the time I dont implement toString and equals methods on my grails domain classes. I would like to say thanks to Groovy for helping me out and giving me a ready made recipe for this. Now I just need to annotate my class with <a href="http://groovy.codehaus.org/gapi/groovy/transform/ToString.html">ToString</a> and <a href="http://groovy.codehaus.org/gapi/groovy/transform/EqualsAndHashCode.html">EqualAndHashCode</a> annotation it adds appropriate implementation of these methods for me. Now My domain class looks something like this.</p>
<pre class="brush: java;">
@ToString(includeNames = true, includeFields = true, excludes = 'dateCreated,lastUpdated,metaClass')
@EqualsAndHashCode
class Item {
    String name
    Float price
    boolean active = true
    Date dateCreated
    Date lastUpdated
}
</pre>
<p>Before adding this annotation my domain class toString looks like this</p>
<pre class="brush: java;">
Item item = new Item(name: &quot;Chips&quot;, active: false, price: 15)
println &quot;To String output -: &quot; + item //To String output -: com.intelligrape.myapp.Item : null
</pre>
<p>Now I get the following output for Item object toString</p>
<pre class="brush: java;">
Item item = new Item(name: &quot;Chips&quot;, active: false, price: 15)
println &quot;To String output -: &quot; + item //To String output -: com.intelligrape.myapp.Item(name:Chips, price:15.0, active:false)
</pre>
<p>To get this annotation on all my domain classed I updated the template of grails domain classes so that whenever I do create-domain-class it give me the annotated domain classes</p>
<pre class="brush: java;">
@artifact.package@
import groovy.transform.EqualsAndHashCode
import groovy.transform.ToString

@ToString(includeNames = true, includeFields = true, excludes = 'dateCreated,lastUpdated,metaClass')
@EqualsAndHashCode
class @artifact.name@ {

    Date dateCreated
    Date lastUpdated
}
</pre>
<p>Hope it helps</p>
<p><br/><br />
## Uday Pratap Singh ##<br />
uday@intelligrape.com<br />
<a href="http://www.IntelliGrape.com/">http://www.IntelliGrape.com/</a><br />
<a href="http://in.linkedin.com/in/meudaypratap">http://in.linkedin.com/in/meudaypratap</a>  </p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2012/01/29/groovy-annotations-for-tostring-and-equalsandhashcode/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Closure Caching For Increased Performance (.memoize())</title>
		<link>http://www.intelligrape.com/blog/2011/12/29/closure-caching-for-increased-performance-memoize/</link>
		<comments>http://www.intelligrape.com/blog/2011/12/29/closure-caching-for-increased-performance-memoize/#comments</comments>
		<pubDate>Thu, 29 Dec 2011 11:10:38 +0000</pubDate>
		<dc:creator>Kushal Likhi</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[groovy grails performance caching]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=4868</guid>
		<description><![CDATA[Well This is something awesome and can increase the performance of the project when used wisely. using the groovy .memoize() we can ask closures to perform kind of caching. This can boost up the performance of the system.

&#160;
_
Note: This feature is available in groovy 1.8+
Well Let me Explain this Using Examples
Now suppose i have a [...]]]></description>
			<content:encoded><![CDATA[<p>Well This is something <b>awesome</b> and can increase the performance of the project when used wisely. using the groovy .memoize() we can ask closures to perform kind of caching. This can boost up the performance of the system.<br />
</p>
<h1>&nbsp;</h1>
<h1>_</h1>
<p><strong>Note:</strong> This feature is available in groovy 1.8+</p>
<h1>Well Let me Explain this Using Examples</h1>
<p>Now suppose i have a function &#8220;distance&#8221; which calculates distance between two points.<br />
Hence for it instead of writing a function(Method) lets write a closure for it.</p>
<pre class="brush: java;">
        def distance = {x1, y1, x2, y2 -&gt;
            sleep(200)  //just to add a delay for demo purposes
            Math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
        }

       //To Call It 5 Times
       5.times {
            def t1 = System.currentTimeMillis()
            println distance(100, 20, 400, 10)
            println &quot;took: ${System.currentTimeMillis() - t1} milliseconds to execute&quot;
        }
</pre>
<p>Now if we will Run this the Output will be as follows:</p>
<pre class="brush: plain;">
300.1666203960727
took: 201 milliseconds to execute
300.1666203960727
took: 200 milliseconds to execute
300.1666203960727
took: 201 milliseconds to execute
300.1666203960727
took: 201 milliseconds to execute
300.1666203960727
took: 201 milliseconds to execute
</pre>
<p>Each time this closure is called all statements are executed again and hence re-computation. But if set of inputs are same then technically output should be same. hence a type of caching will help.<br />
Also if several users are acessing the app then for each user if something is done again and again though the inputs are same then that is again a overhead, this issue can also be solved by <strong>memoizeing</strong>. <img src='http://www.intelligrape.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h1>Now lets Do it with .memoize()</h1>
<pre class="brush: java;">
        def distance = {x1, y1, x2, y2 -&gt;
            sleep(200)  //just to add a delay for demo purposes
            Math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
        }.memoize() //Note now closure is memoized 

       //To Call It 5 Times
       5.times {
            def t1 = System.currentTimeMillis()
            println distance(100, 20, 400, 10)
            println &quot;took: ${System.currentTimeMillis() - t1}&quot;
        }
</pre>
<p>Now the result is:</p>
<pre class="brush: plain;">
300.1666203960727
took: 202 milliseconds to execute
300.1666203960727
took: 1 milliseconds to execute
300.1666203960727
took: 1 milliseconds to execute
300.1666203960727
took: 0 milliseconds to execute
300.1666203960727
took: 0 milliseconds to execute
</pre>
<p><b>We can definitely see the difference between time taken to execute.</b><br />
AND HURRAY, ALL REPETITIVE CALLS WITH SAME INPUT DATA ARE NOW CACHED AND HENCE INCREASED PERFORMANCE.</p>
<h1>&nbsp;</h1>
<p>Hope it helped<br />
Regards<br />
Kushal Likhi</p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/12/29/closure-caching-for-increased-performance-memoize/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Install Apps on Facebook Fan page using API</title>
		<link>http://www.intelligrape.com/blog/2011/12/18/install-apps-on-facebook-fan-page-using-api/</link>
		<comments>http://www.intelligrape.com/blog/2011/12/18/install-apps-on-facebook-fan-page-using-api/#comments</comments>
		<pubDate>Sun, 18 Dec 2011 12:47:13 +0000</pubDate>
		<dc:creator>Vishal Sahu</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Facebook]]></category>
		<category><![CDATA[Facebook Fan Page]]></category>
		<category><![CDATA[Facebook Integration]]></category>
		<category><![CDATA[Graph API]]></category>
		<category><![CDATA[Social]]></category>
		<category><![CDATA[Social Media]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=4752</guid>
		<description><![CDATA[Hi,
In my current grails project, we are using Facebooks Apps for our application so that any user who wish to use that app, can attach it with his/her Facebook Fan Page manually by visiting the App Profile Page and then adding it to the Fan Page. Then the attached facebook app can fetch data from [...]]]></description>
			<content:encoded><![CDATA[<p>Hi,<br />
In my current grails project, we are using Facebooks Apps for our application so that any user who wish to use that app, can attach it with his/her Facebook Fan Page manually by visiting the App Profile Page and then adding it to the Fan Page. Then the attached facebook app can fetch data from our project. </p>
<pre>
</pre>
<p>But few days ago, Facebook announced that it is <a href="http://developers.facebook.com/blog/post/611/"><strong>Removing App Profile Pages</strong></a>.<br />
Now for adding facebook apps to  fan page, we can either  <strong>Create an Profile page for  app</strong> or  <strong>Add the app to Fan page using API</strong>.</p>
<pre>
</pre>
<p>I implemented the feature to attach any Facebook App to Facebook Fan page using API and thought it worth sharing.</p>
<pre>
</pre>
<p>I am assuming that you already have the Facebook Page Access Token with you, if not you can see how to Integrate facebook with web application and get access token <a href="http://www.intelligrape.com/blog/2010/11/14/integrate-java-application-with-facebook-using-graph-api/">here</a>.</p>
<pre>
</pre>
<p>Get App Id from Facebook App page:-<br />
<img src="http://www.intelligrape.com/blog/wp-content/uploads/2011/12/rsz_1screenshot_at_2011-12-18_1725081.png" alt="" width="600"></p>
<pre>
</pre>
<p>To attach any Facebook Fan page, we need to issue an HTTP POST request to the facebook URL.<br />
URL for POST request </p>
<pre class="brush: java;">
URL :  https://graph.facebook.com/${FACEBOOK_PAGE_ID}/tabs
</pre>
<p>Values we will be requiring :</p>
<pre class="brush: java;">

String FAN_PAGE_ACCESS_TOKEN = fan page access token.
String APP_ID = app id from the registered app.
String FACEBOOK_PAGE_ID = id of the facebook page to which app is to be attached.
</pre>
<p>Code to issue post request at the given URL:</p>
<pre class="brush: java;">

        StringBuilder sb = new StringBuilder(&quot;access_token=&quot;);
        sb.append(URLEncoder.encode(FAN_PAGE_ACCESS_TOKEN, &quot;UTF-8&quot;));
        sb.append(&quot;&amp;app_id=&quot;);
        sb.append(URLEncoder.encode(APP_ID, &quot;UTF-8&quot;));

        URL url = new URL(&quot;https://graph.facebook.com/${FACEBOOK_PAGE_ID}/tabs&quot;);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        String publishedPostId
        try {
            connection.setDoOutput(true);
            connection.setRequestMethod(&quot;POST&quot;);
            connection.setRequestProperty(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;);
            connection.setRequestProperty(&quot;Content-Length&quot;, &quot;&quot; + sb.toString().length());
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream());
            outputStreamWriter.write(sb.toString());
            outputStreamWriter.flush();
            log.debug(&quot;Response code ${connection.responseCode} , Message : ${connection.responseMessage}&quot;)
            if (connection.responseCode != 200) {
                log.debug(&quot;Unable to attach app to facebook fan page&quot;)
            }
        } finally {
            connection?.disconnect()
        }
</pre>
<pre>
</pre>
<p>So, we can attach any Facebook App to the Facebook Fan Page using the above code.</p>
<pre>
</pre>
<p>This worked for me.<br />
Hope it helps.</p>
<pre>
</pre>
<p>Cheers !!!<br />
Vishal Sahu<br />
vishal@intelligrape.com<br />
<a href="http://www.linkedin.com/in/vishalsahu">http://www.linkedin.com/in/vishalsahu</a><br />
<a href="http://www.intelligrape.com">http://www.intelligrape.com</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/12/18/install-apps-on-facebook-fan-page-using-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Integrating Google plus in grails application</title>
		<link>http://www.intelligrape.com/blog/2011/12/06/integrating-google-plus-in-grails-application/</link>
		<comments>http://www.intelligrape.com/blog/2011/12/06/integrating-google-plus-in-grails-application/#comments</comments>
		<pubDate>Tue, 06 Dec 2011 07:12:04 +0000</pubDate>
		<dc:creator>Vishal Sahu</dc:creator>
				<category><![CDATA[Google Web Tools]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Java tools]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[Google Plus]]></category>
		<category><![CDATA[OAuth 2.0]]></category>
		<category><![CDATA[Social Media]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=4687</guid>
		<description><![CDATA[In my current project, i needed to integrate Google+ in the application using server-side API. Google uses OAuth2.0 protocol for authorization when our application tries to access the data. All we require is an access token to fetch data from Google using REST calls which serves data in JSON format.

I implemented it using Web Server [...]]]></description>
			<content:encoded><![CDATA[<p>In my current project, i needed to integrate Google+ in the application using server-side API. Google uses OAuth2.0 protocol for authorization when our application tries to access the data. All we require is an access token to fetch data from Google using REST calls which serves data in JSON format.<br />
<br />
I implemented it using Web Server Applications API and thought it worth sharing.</p>
<pre>
</pre>
<p>There are basically 3 steps to fetch data from Google.</p>
<pre>
</pre>
<p><strong>1. Register an application.</strong></p>
<p>We need to register an application at <a href="https://code.google.com/apis/console">Google API Console</a>.  Go to the Google console page using the link provided and create an aplication.</p>
<pre>
</pre>
<p>Steps involve in registering an application are:-</p>
<pre>
</pre>
<p>a.) Create project by providing name to the project.</p>
<pre>
</pre>
<p><img class="size-full wp-image-4690" src="http://www.intelligrape.com/blog/wp-content/uploads/2011/12/rsz_1.png" alt="" width="474" height="315" /></p>
<pre>
</pre>
<p>b.) Turn ON the service required, in our case it is Google Plus API.</p>
<pre>
</pre>
<p><img class="size-full wp-image-4691" src="http://www.intelligrape.com/blog/wp-content/uploads/2011/12/2-1.png" alt="" width="370" height="212" /></p>
<pre>
</pre>
<p>c.) Create a Oauth 2.0 Client ID.</p>
<pre>
</pre>
<p><a href="http://www.intelligrape.com/blog/wp-content/uploads/2011/12/3-1.png"><img class="size-full wp-image-4692" src="http://www.intelligrape.com/blog/wp-content/uploads/2011/12/3-1.png" alt="" width="432" height="286" /></a></p>
<pre>
</pre>
<p>d.) Create the OAuth 2.0 ClientId and provide the callback URL where google will send the authorization token.</p>
<pre>
</pre>
<p><a href="http://www.intelligrape.com/blog/wp-content/uploads/2011/12/4-1.png"><img class="size-full wp-image-4693" src="http://www.intelligrape.com/blog/wp-content/uploads/2011/12/4-1.png" alt="" width="386" height="295" /></a></p>
<pre>
</pre>
<p>e.) Note down Client ID and Client Secret as generated in the above step.</p>
<pre>
</pre>
<p><a href="http://www.intelligrape.com/blog/wp-content/uploads/2011/12/5-1.png"><img class="size-full wp-image-4694" src="http://www.intelligrape.com/blog/wp-content/uploads/2011/12/5-1.png" alt="" width="547" height="221" /></a></p>
<pre>
</pre>
<p><strong>2. Obtain an Access Token from the Google Authorization Server.</strong></p>
<pre>
</pre>
<p>Obtaining an access token involves 2 steps.</p>
<pre>
</pre>
<p>a.) Request for Authorization Code.</p>
<pre>
</pre>
<p>In this step, we will request the Google server for authorization code by providing registered application client ID in the URL to Google server.</p>
<p>I created an action to redirect to Goolge, when someone want to connect to google plus.</p>
<pre class="brush: java;">
String CLIENT_ID =client_id_obtained from registered app
String CALLBACK_URL = callback_url_as_mentioned in the registered app.
String GOOGLE_PLUS_SCOPE='https://www.googleapis.com/auth/plus.me'    // scope is the permissions we are requesting.
</pre>
<pre>
</pre>
<p>Action code is as:</p>
<pre class="brush: java;">
def registerOnGooglePlus = {
String authorizeUrl = &quot;https://accounts.google.com/o/oauth2/auth?scope=${GOOGLE_PLUS_SCOPE}&amp;
redirect_uri=${CALLBACK_URL}&amp;response_type=code&amp;client_id=${CLIENT_ID}&amp;access_type=offline&quot;
URL urlForGooglePlus = new URL(authorizeUrl)
redirect(url: urlForGooglePlus)
}
</pre>
<p>The Redirect will take user to permissions page, if the user is already logged-in or will take to login page and then permissions page.</p>
<p>After approving the required permissions, user will redirect back to the application&#8217;s registered Callback URL with the authorization code.</p>
<pre>
</pre>
<p><a href="http://www.intelligrape.com/blog/wp-content/uploads/2011/12/6-1.png"><img class="size-full wp-image-4695" src="http://www.intelligrape.com/blog/wp-content/uploads/2011/12/6-1.png" alt="" width="570" height="250" /></a></p>
<pre>
</pre>
<p>b.) Request for Access Token with the authorization code obtained from the above action.</p>
<pre>
</pre>
<p>Access Token can be received by a POST request using the Client Secret and authorization code received.</p>
<p>The POST call requires 5 properties to be send in the body of the request in the encoded form.</p>
<pre class="brush: xml;">

	code : The authorization code returned from the initial request
	client_id : The client_id obtained during application registration
	client_secret : The client secret obtained during application registration
	redirect_uri : The URI registered with the application
	grant_type : authorization_code
</pre>
<pre class="brush: java;">

// Sample action to receive authorization code

def callBack={
StringBuilder sb = new StringBuilder(&quot;code=&quot;);
sb.append(URLEncoder.encode(code, &quot;UTF-8&quot;));
sb.append(&quot;&amp;client_id=&quot;);
sb.append(URLEncoder.encode(clientId, &quot;UTF-8&quot;));
sb.append(&quot;&amp;client_secret=&quot;);
sb.append(URLEncoder.encode(clientSecret, &quot;UTF-8&quot;));
sb.append(&quot;&amp;redirect_uri=&quot;);
sb.append(URLEncoder.encode(callbackUrl, &quot;UTF-8&quot;));
sb.append(&quot;&amp;grant_type=&quot;);
sb.append(URLEncoder.encode('authorization_code', &quot;UTF-8&quot;));

String URL_TO_REQUEST_TOKEN= 'https://accounts.google.com/o/oauth2/token'

URL url = new URL(URL_TO_REQUEST_TOKEN);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
connection.setRequestMethod(&quot;POST&quot;);
connection.setRequestProperty(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;);
connection.setRequestProperty(&quot;Content-Length&quot;, &quot;&quot; + sb.toString().length());
connection.setRequestProperty(&quot;Host&quot;, &quot;accounts.google.com&quot;);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream());
outputStreamWriter.write(sb.toString());
outputStreamWriter.flush();
log.debug(&quot;Response code ${connection.responseCode} , Message : ${connection.responseMessage}&quot;)
String resultData = connection.content.text
def responseJson = JSON.parse(resultData)
String ACCESS_TOKEN = responseJson?.access_token
}
catch (Exception e) {
e.printStackTrace()
}
}
</pre>
<pre>
</pre>
<p><strong>3. Calling Google API.</strong></p>
<p>Now, with the help of access token, we can call google API to fetch Data by appending the access token in the GET request.</p>
<p>Example:</p>
<pre>
</pre>
<p>To fetch person&#8217;s profile data</p>
<pre class="brush: java;">
GET :  https://www.googleapis.com/oauth2/v1/userinfo?access_token=ACCESS_TOKEN
</pre>
<pre>
</pre>
<p>To get list of profile acitivties</p>
<pre class="brush: java;">
 GET :  https://www.googleapis.com/plus/v1/people//activities/public?access_token=ACCESS_TOKEN
</pre>
<pre>
</pre>
<p><strong>References:-</strong><br />
<a href="http://code.google.com/apis/accounts/docs/OAuth2WebServer.html">http://code.google.com/apis/accounts/docs/OAuth2WebServer.html</a></p>
<p><a href="http://code.google.com/apis/accounts/docs/OAuth2.html">http://code.google.com/apis/accounts/docs/OAuth2.html</a></p>
<pre>
</pre>
<p>Hope this helps..!!!</p>
<pre>
</pre>
<p>Vishal Sahu<br />
vishal[at]intelligrape[dot]com<br />
<a href="http://www.intelligrape.com">www.intelligrape.com</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/12/06/integrating-google-plus-in-grails-application/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Validating emails, urls and date using Java API</title>
		<link>http://www.intelligrape.com/blog/2011/11/14/validating-emails-urls-and-date-using-java-api/</link>
		<comments>http://www.intelligrape.com/blog/2011/11/14/validating-emails-urls-and-date-using-java-api/#comments</comments>
		<pubDate>Mon, 14 Nov 2011 12:47:19 +0000</pubDate>
		<dc:creator>Bhagwat Kumar</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[commons-validator]]></category>
		<category><![CDATA[Credit card validator]]></category>
		<category><![CDATA[DateValidator]]></category>
		<category><![CDATA[EmailValidator]]></category>
		<category><![CDATA[GenericValidator]]></category>
		<category><![CDATA[Url validator]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=4494</guid>
		<description><![CDATA[Using commons-validator jar for validation emails, date, url, credit card etc. This jar file is bundled with the grails jar files. So writing regular expressions or creating command objects/domains for the single field validation is overkilling. The jar file has a special class GenericValidator for validating well-known data types.]]></description>
			<content:encoded><![CDATA[<p>Recently I was looking for a programmatic way for validating data against well known validation e.g. email and date. I have to use them inside custom validator and sometimes in controller/action. Creating Command objects for validating was not suitable in my case(overkilling solution). Writing/looking for regular expression was another solution. I found a special class  <code>GenericValidator</code> in <code>org.apache.commons.validator</code> package (<code>commons-validator</code> jar file, bundled with grails jars) . The class has many useful <code>static</code> methods for validating data. e.g. for validating <em>email, url, credit card, date</em> etc. Here is the sample code for validation using <code>GenericValidator</code> class: </p>
<pre class="brush: groovy;">
import org.apache.commons.validator.GenericValidator

assert GenericValidator.isEmail(&quot;bhagwat@intelligrape.com&quot;)  //valid email
assert !GenericValidator.isEmail(&quot;bhagwatintelligrape.com&quot;)  // invalid email

assert GenericValidator.isUrl(&quot;http://www.intelligrape.com&quot;)  //valid URL
assert !GenericValidator.isUrl(&quot;www.intelligrape.com&quot;) //invalid URL

assert GenericValidator.isCreditCard(&quot;4111111111111111&quot;) // valid visa card number
assert !GenericValidator.isCreditCard(&quot;4111111111111112&quot;) // invalid visa card number

assert GenericValidator.isDate(&quot;2011-12-30&quot;, &quot;yyyy-MM-dd&quot;, true) // valid date(last argument for checking strict)
assert GenericValidator.isDate(&quot;2011-02-28&quot;, &quot;yyyy-MM-dd&quot;, true) // valid date - 28th Feb
assert !GenericValidator.isDate(&quot;2011-02-29&quot;, &quot;yyyy-MM-dd&quot;, false) // invalid date - 29th Feb 2011
</pre>
<p>For other useful methods and their details follow the link :<br />
<a href="http://commons.apache.org/validator/apidocs/org/apache/commons/validator/GenericValidator.html">http://commons.apache.org/validator/apidocs/org/apache/commons/validator/GenericValidator.html</a>.</p>
<p>In addition to <code>GennericValdator</code> class there are separate classes for validating date, email, credit card, ISBN validator in the <code>org.apache.commons.validator package</code> viz. <em>DateValidator, CreditCardValidator, EmailValidator, ISBNValidator, UrlValidator</em> and so on. Here is the sample code for using <code>DateValidator</code> class.</p>
<pre class="brush: groovy;">
import org.apache.commons.validator.DateValidator

DateValidator dateValidator=DateValidator.getInstance()
assert dateValidator.isValid(&quot;11-02-28&quot;, &quot;yy-MM-dd&quot;, true)
assert !dateValidator.isValid(&quot;11-02-29&quot;, &quot;yy-MM-dd&quot;, true)
</pre>
<p>Hope it helps you.</p>
<p>Bhagwat Kumar<br />
bhagwat(at)intelligrape(dot)com</p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/11/14/validating-emails-urls-and-date-using-java-api/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Groovy : Find Index of Element in Map</title>
		<link>http://www.intelligrape.com/blog/2011/11/10/groovy-find-index-of-element-in-map/</link>
		<comments>http://www.intelligrape.com/blog/2011/11/10/groovy-find-index-of-element-in-map/#comments</comments>
		<pubDate>Thu, 10 Nov 2011 18:16:26 +0000</pubDate>
		<dc:creator>Hitesh Bhatia</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[index]]></category>
		<category><![CDATA[map]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=4474</guid>
		<description><![CDATA[Groovier way of finding index of element from Map. It can be obtained with findIndexOf Method, which accepts closure as argument.


Map map=[&#34;groovy&#34;:1,&#34;grails&#34;:2,&#34;index&#34;:3,&#34;element&#34;:4]
assert 3 == map.findIndexOf{it.key==&#34;element&#34;}
assert 0 == map.findIndexOf{it.value==1}

]]></description>
			<content:encoded><![CDATA[<p>Groovier way of finding index of element from Map. It can be obtained with findIndexOf Method, which accepts closure as argument.</p>
<pre class="brush: groovy;">

Map map=[&quot;groovy&quot;:1,&quot;grails&quot;:2,&quot;index&quot;:3,&quot;element&quot;:4]
assert 3 == map.findIndexOf{it.key==&quot;element&quot;}
assert 0 == map.findIndexOf{it.value==1}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/11/10/groovy-find-index-of-element-in-map/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Log Sql in grails for a piece of code</title>
		<link>http://www.intelligrape.com/blog/2011/10/21/log-sql-in-grails-for-a-piece-of-code/</link>
		<comments>http://www.intelligrape.com/blog/2011/10/21/log-sql-in-grails-for-a-piece-of-code/#comments</comments>
		<pubDate>Fri, 21 Oct 2011 09:02:22 +0000</pubDate>
		<dc:creator>Uday Pratap Singh</dc:creator>
				<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[logging]]></category>
		<category><![CDATA[grails sql logging]]></category>
		<category><![CDATA[sql logging for code]]></category>
		<category><![CDATA[sql logging for method]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=4388</guid>
		<description><![CDATA[There are time when we need to see the sql logging statement just for a method of for a particular code. Although we already have logSql property in DataSource to do it for us but it sometimes makes difficult if we need to see the log for a small piece of code rather than for [...]]]></description>
			<content:encoded><![CDATA[<p>There are time when we need to see the sql logging statement just for a method of for a particular code. Although we already have logSql property in DataSource to do it for us but it sometimes makes difficult if we need to see the log for a small piece of code rather than for whole project.<br />
So I need something that will execute my code withing a block which automatically starts sql logging and switch it off when code is finished. Groovy closures are the solution for this problem. For doing it I created a class LogSql which have a static execute method that takes the closure as parameter.</p>
<pre class="brush: java;">
import org.apache.log4j.Level
import org.apache.log4j.Logger

public static def execute(Closure closure) {
        Logger sqlLogger = Logger.getLogger(&quot;org.hibernate.SQL&quot;);
        Level currentLevel = sqlLogger.level
        sqlLogger.setLevel(Level.TRACE)
        def result = closure.call()
        sqlLogger.setLevel(currentLevel)
        result
}
</pre>
<p>Now when I want to see the logs I do something like following.</p>
<pre class="brush: java;">
String name = &quot;Uday&quot;
Person person
LogSql.execute {
       person = Person.findByName(name)
}
</pre>
<p>This prints the sql statement for all the sql fired in the given piece of code block.     </p>
<p>Hope it helps</p>
<p><br/><br />
## Uday Pratap Singh ##<br />
uday@intelligrape.com<br />
<a href="http://www.IntelliGrape.com/">http://www.IntelliGrape.com/</a><br />
<a href="http://in.linkedin.com/in/meudaypratap">http://in.linkedin.com/in/meudaypratap</a>    </p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/10/21/log-sql-in-grails-for-a-piece-of-code/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Closure as an implementation to interface</title>
		<link>http://www.intelligrape.com/blog/2011/10/04/closure-as-an-implementation-to-interface/</link>
		<comments>http://www.intelligrape.com/blog/2011/10/04/closure-as-an-implementation-to-interface/#comments</comments>
		<pubDate>Tue, 04 Oct 2011 13:44:27 +0000</pubDate>
		<dc:creator>Mohd Farid</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=4297</guid>
		<description><![CDATA[Recently, I saw some code of grails Hibernate Plugin and noticed an interesting usage of ‘as’ operator. The ‘as’ operator of groovy is typically used to change the types of objects.

For example:
1	int a = "20" as int
2	assert a==20

The ‘as’ operator can be used to provide implementation to interface as well. Here is an example of the same:
1	interface Eatable{
2	   void eat()
3	}
4	 
5	def x =  {println "It's groovy style" } as Eatable
6	x.eat()

Had it been java, this could have been achieved through an annonymous class like this:
1	new Eatable(){
2	  void eat(){
3	    System.out.println "Its java style"
4	  }
5	}.eat()]]></description>
			<content:encoded><![CDATA[<p>Recently, I saw some code of grails Hibernate Plugin and noticed an interesting usage of &#8216;as&#8217; operator. The &#8216;as&#8217; operator of groovy is typically used to change the types of objects.</p>
<p>For example: </p>
<pre class="brush: groovy;">
int a = &quot;20&quot; as int
assert a==20
</pre>
<p>The &#8216;as&#8217; operator can be used to provide implementation to interface as well. Here is an example of the same:</p>
<pre class="brush: groovy;">
interface Eatable{
   void eat()
}

def x =  {println &quot;It's groovy style&quot; } as Eatable
x.eat()
</pre>
<p>Had it been java, this could have been achieved through an annonymous class like this:</p>
<pre class="brush: java;">
new Eatable(){
  void eat(){
    System.out.println &quot;Its java style&quot;
  }
}.eat()
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/10/04/closure-as-an-implementation-to-interface/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How to get Google Indexed Pages Count, and/or do Google searches through AJAX/programmatically</title>
		<link>http://www.intelligrape.com/blog/2011/09/27/how-to-get-google-indexed-pages-count-andor-do-google-searches-through-ajaxprogmatically/</link>
		<comments>http://www.intelligrape.com/blog/2011/09/27/how-to-get-google-indexed-pages-count-andor-do-google-searches-through-ajaxprogmatically/#comments</comments>
		<pubDate>Tue, 27 Sep 2011 13:35:32 +0000</pubDate>
		<dc:creator>Kushal Likhi</dc:creator>
				<category><![CDATA[Google Web Tools]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Java tools]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=4279</guid>
		<description><![CDATA[Hi,
Recently i had to get the count of the Pages Google has Indexed for a perticular web Site progmatically.
In the process i found that Google offers an AJAX Search API to perform Google Searches.
.
Hence i Implemented a Class which does the same for me easily(Ajax Search in Google).
And this Solution Does Google Searches programmatically and [...]]]></description>
			<content:encoded><![CDATA[<p>Hi,<br />
Recently i had to <strong>get the count of the Pages Google has Indexed</strong> for a perticular web Site progmatically.<br />
In the process i found that Google offers an AJAX Search API to perform Google Searches.<br />
.<br />
Hence i <strong>Implemented a Class</strong> which does the same for me easily(Ajax Search in Google).<br />
And this Solution <strong>Does Google Searches programmatically</strong> <strong>and Also</strong> <strong>Give us the Indexed Pages Count</strong>.<br />
<strong>Note:</strong> Its Groovy Implementation, Similar can be done in JavaScript using Ajax though intent will remain the same.<br />
<em>The class has been named GoogleAjaxSearch because it uses the Google AJAX Search API <img src='http://www.intelligrape.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </em><br />
<br />
Use Cases Are As Follows:</p>
<pre class="brush: java;">
//Case 1 Simple Search
String searchQuery = &quot;my search Query&quot;
GoogleAjaxSearch googleAjaxSearch = new GoogleAjaxSearch(searchQuery)
println googleAjaxSearch.results //Type List&lt;Expando&gt;, Just print it to see available properties
</pre>
<p></p>
<pre class="brush: java;">
//Case 2: Get Number Of Indexed Pages in Google
String searchQuery = &quot;site:intelligrape.com&quot;
GoogleAjaxSearch googleAjaxSearch = new GoogleAjaxSearch(searchQuery)
println googleAjaxSearch.estimatedResultCount
</pre>
<p></p>
<pre class="brush: java;">
//Case 3: Redo a search with same SearchQuery or a different Search Query
String searchQuery = &quot;search string&quot;
GoogleAjaxSearch googleAjaxSearch = new GoogleAjaxSearch(searchQuery)
googleAjaxSearch.redo() //Re-Search with same query
googleAjaxSearch.redo(&quot;New Query&quot;) // Re-Search With New Query
</pre>
<p></p>
<pre class="brush: java;">
//Case 4: All Details Available
String searchQuery = &quot;site:intelligrape.com&quot;
GoogleAjaxSearch googleAjaxSearch = new GoogleAjaxSearch(searchQuery)
println googleAjaxSearch.estimatedResultCount //Gives the result count, indexed pages count
println googleAjaxSearch.currentPageIndex    //Search result server side pagination - current page
println googleAjaxSearch.results  //List&lt;Expando&gt; containing results
println googleAjaxSearch.responseStatus //HTTP Status Code
println googleAjaxSearch.responseDetails //Details for response, if any
println googleAjaxSearch.searchQuery     //Search Query
println googleAjaxSearch.moreResultsUrl // Url to hit for next Page of results
println googleAjaxSearch.jsonResult // Complete raw JSON Result from google
println googleAjaxSearch.pages  // Pagination Pages Details
</pre>
<p>The Class Code Is As Follows:</p>
<hr />
<pre class="brush: java;">
package myPackage.googleSearch

import grails.converters.JSON

class GoogleAjaxSearch {

    public String searchQuery
    public String responseDetails
    public String moreResultsUrl
    public String jsonResult

    public Integer responseStatus
    public Integer currentPageIndex
    public Integer estimatedResultCount

    public def pages

    public List&lt;Expando&gt; results = []

    private static final String ajaxSearchTarget = &quot;http://ajax.googleapis.com/ajax/services/search/web?v=1.0&amp;q=###SEARCHQUERY###&amp;filter=0&quot;

    public GoogleAjaxSearch(String searchQuery) {
        this.searchQuery = searchQuery
        search()
    }

    public GoogleAjaxSearch() {
        this(null)
    }

    public void redo() {
        search()
    }

    public void redo(String newSearchQuery) {
        this.searchQuery = newSearchQuery
        search()
    }

    private void search() {
        if (searchQuery) {
            URL url = new URL(ajaxSearchTarget.replace('###SEARCHQUERY###', searchQuery))
            URLConnection connection = url.openConnection()
            connection.setDoInput(true)
            InputStream inStream = connection.getInputStream()
            BufferedReader searchResultContent = new BufferedReader(new InputStreamReader(inStream))
            jsonResult = searchResultContent.getText()
            parseJsonAndPopulateObject()
        }
    }

    private void parseJsonAndPopulateObject() {
        def jsonArray = JSON.parse(jsonResult)
        this.responseStatus = Integer.parseInt(jsonArray.responseStatus as String, 10)
        this.responseDetails = jsonArray.responseDetails
        this.moreResultsUrl = jsonArray.responseData.cursor.moreResultsUrl
        this.currentPageIndex = Integer.parseInt(jsonArray.responseData.cursor.currentPageIndex as String, 10)
        this.pages = jsonArray.responseData.cursor.pages
        this.estimatedResultCount = Integer.parseInt(jsonArray.responseData.cursor.estimatedResultCount as String, 10)
        results = jsonArray.responseData.results.collect {
            new Expando(
                    content: it.content,
                    GsearchResultClass: it.GsearchResultClass,
                    titleNoFormatting: it.titleNoFormatting,
                    title: it.title,
                    cacheUrl: it.cacheUrl,
                    unescapedUrl: it.unescapedUrl,
                    url: it.url,
                    visibleUrl: it.visibleUrl
            )
        }
    }
}
</pre>
<p>Hope That Helps <img src='http://www.intelligrape.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
Regards<br />
Kushal Likhi</p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/09/27/how-to-get-google-indexed-pages-count-andor-do-google-searches-through-ajaxprogmatically/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Annotation for checking required session fields</title>
		<link>http://www.intelligrape.com/blog/2011/09/21/annotation-for-checking-required-session-fields/</link>
		<comments>http://www.intelligrape.com/blog/2011/09/21/annotation-for-checking-required-session-fields/#comments</comments>
		<pubDate>Wed, 21 Sep 2011 13:42:24 +0000</pubDate>
		<dc:creator>Uday Pratap Singh</dc:creator>
				<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Java tools]]></category>
		<category><![CDATA[action of controller from string value]]></category>
		<category><![CDATA[Annotations]]></category>
		<category><![CDATA[controller class using string class name]]></category>
		<category><![CDATA[grails filters]]></category>
		<category><![CDATA[groovy annotation]]></category>
		<category><![CDATA[session check annotation]]></category>
		<category><![CDATA[session checking in grails]]></category>
		<category><![CDATA[setting default value in annotation]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=4268</guid>
		<description><![CDATA[Recently I worked on a project where I used spring security plugin. Its a very wonderful plugin for making your application secured from unauthorized users. It gives you a simple annotation @Secured to add security to your action and controller. Thats the first time I got to know the real use case of annotation. So [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I worked on a project where I used spring security plugin. Its a very wonderful plugin for making your application secured from unauthorized users. It gives you a simple annotation @Secured to add security to your action and controller. Thats the first time I got to know the real use case of annotation. So I started reading about annotation and few days later I found the use case to implement my own annotation.</p>
<p>All the projects I have worked on had login functionality where we put the userId and projectId into the session. Then in my code I use to get the user from session.userId. Something like</p>
<pre class="brush: java;">
def books = {
   User user = User.get(session.userId)
   Project project = Project.get(session.projectId)
   ......
   .....
}
</pre>
<p>The above code fails when user directly hits this action because there is no check to verify the user is not null. The simple answer for this problem is either use beforeInterceptor or filters. So we started checking the session.userId in filters. But again there are cases where you dont want to check this session value or you can say there are public urls as well. Now we have to put few if else statements in filter.</p>
<p>Here I got my use case to implement an annotation for controllers and actions which checks for the required fields in the session before getting into the action. So I created an annotation in src/groovy folder</p>
<pre class="brush: java;">
import java.lang.annotation.ElementType
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
import java.lang.annotation.Target

@Target([ElementType.FIELD, ElementType.TYPE]) // Annotation is for actions as well as controller so target is field and for class
@Retention(RetentionPolicy.RUNTIME) // We need it at run time to identify the annotated controller and action
@interface RequiredSession {
    String[] exclude() default [] // To exclude some of the actions of controller

    String[] fields() default [&quot;userId&quot;,&quot;projectId&quot;] // The default value is set to userId and projectId that can be overridden while using the   annotation on controller or action.

    String onFailController() default &quot;home&quot; // Default controller when the field not in session is set to index page

    String onFailAction() default &quot;index&quot; // Default action when the field not in session is set to index page
}
</pre>
<p>Now I created a ApplicationFilters and before redirected the request to any action I check for the condition of session fields if the requested action or controller is annotated. The code in the filter is something like </p>
<pre class="brush: java;">
class ApplicationFilters {
    def filters = {
        validateSession(controller: '*', action: '*') {
            before = {
                if (controllerName) {

//Get the instance of controller class from string value i.e; controllerName
                    def controllerClass = grailsApplication.controllerClasses.find {it.logicalPropertyName == controllerName}

//Read the RequiredSession annotation from controller class
                    def annotation = controllerClass.clazz.getAnnotation(RequiredSession)

//Get the current action from actionName otherwise read default action of controller
                    String currentAction = actionName ?: controllerClass.defaultActionName

//Look for the annotation on action if controller is not annotated or the action name is excluded
                    if (!annotation || currentAction in annotation.exclude()) {

//Get the action field from string value i.e; currentAction
                        def action = applicationContext.getBean(controllerClass.fullName).class.declaredFields.find { field -&gt; field.name == currentAction }
//If action is found get the annotation else set it to null
                        annotation = action ? action.getAnnotation(RequiredSession) : null
                    }

//Check for the field in session whether the are null or not if any of the field is null loginFailed is true
                    boolean loginFailed = annotation ? (annotation.fields().any {session[it] == null}) : false

                    if (loginFailed) {

// If login is failed user redirected to on fail action and controller
                        redirect(action: annotation.onFailAction() , controller: annotation.onFailController())
                        return false;
                    }
                }
            }

        }
    }
}
</pre>
<p><br/></p>
<p>And its all done. Now we just annotate our controller and actions accordingly.</p>
<pre class="brush: java;">
@RequiredSession(exclude = [&quot;registration&quot;, &quot;joinProject&quot;])
class UserController {
      def edit ={}
      def update = {}
      def list ={}
      def save ={}

      def registration ={}
      def joinProject = {}
}
</pre>
<p>In above example registration and joinProject action will bypass the session fields check.</p>
<pre class="brush: java;">
@RequiredSession
class ItemController {
        def index={}
        def buy ={}
        def save ={}
}
</pre>
<p>All the action of above examples can be accessed only when user is logged in.</p>
<pre class="brush: java;">
class HomeController {
      def index ={}
      def aboutUs={}
      @RequiredSession
      def dashboard = {}
}
</pre>
<p>Actions other than dashboard are public actions which can be accessed without login.</p>
<pre class="brush: java;">
class UserController {
  @RequiredSession(fields = [&quot;loggedInUserId&quot;])
   def updatePassword = {

   }
}
</pre>
<p>For updating password user dont need to have some project into session so we specified the fields to be checked in session.</p>
<p>Hope it helps</p>
<p><br/><br />
## Uday Pratap Singh ##<br />
uday@intelligrape.com<br />
<a href="http://www.IntelliGrape.com/">http://www.IntelliGrape.com/</a><br />
<a href="http://in.linkedin.com/in/meudaypratap">http://in.linkedin.com/in/meudaypratap</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/09/21/annotation-for-checking-required-session-fields/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

