<?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; Java tools</title>
	<atom:link href="http://www.intelligrape.com/blog/category/java-tools/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>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>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>
		<item>
		<title>Setting System property from command line in grails</title>
		<link>http://www.intelligrape.com/blog/2011/08/24/setting-system-property-from-command-line-in-grails/</link>
		<comments>http://www.intelligrape.com/blog/2011/08/24/setting-system-property-from-command-line-in-grails/#comments</comments>
		<pubDate>Wed, 24 Aug 2011 10:26:14 +0000</pubDate>
		<dc:creator>Vishal Sahu</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Java tools]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[System]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=4093</guid>
		<description><![CDATA[Hi,
In one of my recent grails project, i needed to set System property from command line while running the grails application.
I looked for it and found a simple solution to do so and found it worth sharing.

Suppose we want to set any property, say app.property=&#8221;propertyValue&#8221;, then the command to set the property in grails application [...]]]></description>
			<content:encoded><![CDATA[<p>Hi,</p>
<p>In one of my recent grails project, i needed to set System property from command line while running the grails application.<br />
I looked for it and found a simple solution to do so and found it worth sharing.<br />
</br><br />
Suppose we want to set any property, say app.property=&#8221;propertyValue&#8221;, then the command to set the property in grails application would be:</p>
<pre class="brush: java;">
  grails  -Dapp.property=&quot;propertyValue&quot; run-app
</pre>
<p>Similarly to retrieve the value of System property, we use</p>
<pre class="brush: java;">
String myPropertyValue= System.getProperty(&quot;app.property&quot;)
</pre>
<p>It helped me a lot..<br />
Hope it helps<br />
</br><br />
Vishal Sahu<br />
vishal@intelligrape.com<br />
<a href="http://www.intelligrape.com">www.intelligrape.com</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/08/24/setting-system-property-from-command-line-in-grails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Inject custom validation errors in object</title>
		<link>http://www.intelligrape.com/blog/2011/08/18/inject-custom-validation-errors-in-object/</link>
		<comments>http://www.intelligrape.com/blog/2011/08/18/inject-custom-validation-errors-in-object/#comments</comments>
		<pubDate>Thu, 18 Aug 2011 17:37:20 +0000</pubDate>
		<dc:creator>Uday Pratap Singh</dc:creator>
				<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[GORM]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[Java tools]]></category>
		<category><![CDATA[add custom errors]]></category>
		<category><![CDATA[grails command object]]></category>
		<category><![CDATA[grails object validation]]></category>
		<category><![CDATA[grails validation]]></category>
		<category><![CDATA[inject errors in grails]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=4055</guid>
		<description><![CDATA[Reading the grails docs is like my habit, they always enhances your learning. Today I was going through the grails docs again and I found a very good way of showing some custom error messages. As I saw it I found the use case in one of my project that could be refactored by this [...]]]></description>
			<content:encoded><![CDATA[<p>Reading the grails docs is like my habit, they always enhances your learning. Today I was going through the grails docs again and I found a very good way of showing some custom error messages. As I saw it I found the use case in one of my project that could be refactored by this approach</p>
<p>There are use cases where we need to show some errors which are beyond your domain / command object  constraints validators for these cases you can inject your custom error messages to the object take an example of updating the password. Any of the field is not domain related so we have to create a command object like </p>
<pre class="brush: java;">
class UpdatePasswordCO {

    String password
    String newPassword
    String confirmNewPassword

    static constraints = {
        password(nullable: false, blank: false)
        newPassword(nullable: false, blank: false)
        confirmNewPassword(nullable: false, blank: false, validator: {val,   obj -&gt;
            if (obj.newPassword != val) {
                &quot;confirmPassword.mismatch.newPassword&quot;
            }
        })
    }
}
</pre>
<p>Now you have to check whether the logged in user entered the correct password or not. So rather than putting the message in flash scope you can directly put this error to the command object it self</p>
<pre class="brush: java;">
def updatePassword = {UpdatePasswordCO updatePasswordCO -&gt;
        if (updatePasswordCO.validate()) {
            if (User.loggedInUser.validatePassword(updatePasswordCO.password)) {
                flash.message = &quot;Password updated successfully&quot;
            } else {
                updatePasswordCO.errors.rejectValue(&quot;password&quot;, &quot;password.mismatch.current.password&quot;)
            }
        }
        if (updatePasswordCO.hasErrors()) {
            render(view: 'profile', model: [updatePasswordCO: updatePasswordCO])
        } else {
            redirect(action: 'profile')
        }
}
</pre>
<p>So in above approach you have injected a new error on password field with a code. By doing this your hasErrors tag on gsp page will show your custom error as well. For more details you can refer <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/validation/Errors.html">Spring</a></p>
<p><br/><br />
Hope it helps<br />
<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/08/18/inject-custom-validation-errors-in-object/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generating EAN-8 standard barcode using Barcode4J</title>
		<link>http://www.intelligrape.com/blog/2011/04/14/generating-ean-8-standard-barcode-using-barcode4j/</link>
		<comments>http://www.intelligrape.com/blog/2011/04/14/generating-ean-8-standard-barcode-using-barcode4j/#comments</comments>
		<pubDate>Thu, 14 Apr 2011 15:25:56 +0000</pubDate>
		<dc:creator>Vishal Sahu</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Java tools]]></category>
		<category><![CDATA[System]]></category>
		<category><![CDATA[barcode]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=3606</guid>
		<description><![CDATA[Hi,
In one of my project i needed to generate EAN-8 standard bar-code for identifying the various products. I searched for various libraries available for generating bar-code and found a library to do so. The library i used for generating the bar-code is Barcode4J.
You can download it from here

Barcode4J is a flexible generator for barcodes written [...]]]></description>
			<content:encoded><![CDATA[<p>Hi,</p>
<p>In one of my project i needed to generate EAN-8 standard bar-code for identifying the various products. I searched for various libraries available for generating bar-code and found a library to do so. The library i used for generating the bar-code is Barcode4J.<br />
You can download it from <a href="http://barcode4j.sourceforge.net/">here</a></p>
<p>
Barcode4J is a flexible generator for barcodes written in Java. It&#8217;s free, available under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, version 2.0</a>.<br />
The bar-code generated with the help of of this library uses eight digit number hence EAN-8.</p>
<p>To generate bar-code image from this library is quite simple. Just put the <strong>barcode4j.jar</strong> in the lib folder of the application.</p>
<pre>
</pre>
<p>Code to generate image is:-</p>
<pre class="brush: java;">
public File generateBarcode(Long codeDigits){
try {
      //'codeDigits' is the code for which we want to generate bar-code image
     EAN8Bean bean = new EAN8Bean();
     final int dpi = 150;
     bean.setModuleWidth(UnitConv.in2mm(1.0f / dpi));
     bean.setFontSize(2.0)
     bean.doQuietZone(true)
     File outputFile = new File(filepath) // existing file in the file system
     OutputStream out = new FileOutputStream(outputFile)

     // class to convert provided image into barcode image
     BitmapCanvasProvider canvas = new BitmapCanvasProvider(out, &quot;image/jpeg&quot;, dpi,   BufferedImage.TYPE_BYTE_BINARY, false, 0)
     bean.generateBarcode(canvas, codeDigits)
     canvas.finish()
     return outputFile
}
</pre>
<p>So, here it takes a file from the file system and convert it into the required barcode image. Now, the user can simply display this image on the items.<br />
<br />
In my case, i needed to generate a bar-code image for each product, so i create new file for every item, and stored it on the file system with unique name.</p>
<p>
This works in my case.<br />
Hope it helps</p>
<pre>
</pre>
<p>Cheers..!!!<br />
Vishal Sahu<br />
vishal@intelligrape.com</p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/04/14/generating-ean-8-standard-barcode-using-barcode4j/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Paypal Integration : Auto redirecting to application after processing payment</title>
		<link>http://www.intelligrape.com/blog/2011/03/15/paypal-integration-auto-redirecting-to-application-after-processing-payment/</link>
		<comments>http://www.intelligrape.com/blog/2011/03/15/paypal-integration-auto-redirecting-to-application-after-processing-payment/#comments</comments>
		<pubDate>Mon, 14 Mar 2011 18:41:18 +0000</pubDate>
		<dc:creator>Vishal Sahu</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Java tools]]></category>
		<category><![CDATA[Auto redirect]]></category>
		<category><![CDATA[online payment]]></category>
		<category><![CDATA[payment]]></category>
		<category><![CDATA[paypal]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=3348</guid>
		<description><![CDATA[Hi,
In my recent grails project, i needed to return back to the application after processing payment at the paypal website. I searched a lot about it. Then i found the solution to do so and thought it worth sharing.

Here are the steps i followed:-
1. The Paypal button:- 
This is the code for putting the paypal [...]]]></description>
			<content:encoded><![CDATA[<p>Hi,</p>
<p>In my recent grails project, i needed to return back to the application after processing payment at the paypal website. I searched a lot about it. Then i found the solution to do so and thought it worth sharing.</p>
<p>
Here are the steps i followed:-</p>
<p><strong>1. The Paypal button:- </strong><br />
This is the code for putting the paypal button in any web-page</p>
<pre>
<form method="post" action="https://www.paypal.com/cgi-bin/webscr">

    <img border="0" alt="" width="1" height="1" src="https://www.paypal.com/en_US/i/scr/pixel.gif">
</form>
</pre>
<p>Here:<br />
 The email of merchant&#8217;s account or the seller account, the account to which payment is to be made and the email by which the account is registered is given in the hidden field &#8220;business&#8221;.</p>
<pre>
</pre>
<p>The URL to which we want application to return after processing payment is provided in the hidden field with the name &#8220;return&#8221; i.e. </p>
<pre></pre>
<p>This completes the application side implementation for paypal.<br />
<br />
<strong>2. Paypal Account Configuration</strong><br />
Now we have to configure the Merchant&#8217;s account to Auto-redirect to the provided URL after processing the payment.</p>
<p>   Steps to configure account are:-<br />
   <br />
   1. Log in to Paypal Account<br />
   2. Click the Profile Link in sub-menu of  My Account.<br />
   <img src="http://www.intelligrape.com/blog/wp-content/uploads/2011/03/Profile-Summary-PayPal_1300126550721.png" alt="" width="665" height="85" class="alignnone size-full wp-image-3353" /><br />
<br />
  3. Under &#8220;Selling Preferences&#8221; click &#8216;Website Payment Preferences&#8217; link.<br />
<a href="http://www.intelligrape.com/blog/wp-content/uploads/2011/03/Profile-Summary-PayPal_1300126570607.png"><img src="http://www.intelligrape.com/blog/wp-content/uploads/2011/03/Profile-Summary-PayPal_1300126570607.png" alt="" width="500" height="230" class="alignnone size-full wp-image-3355" /></a></p>
<p>
   4. Select the Auto-Return radio button to enable the auto return feature. </p>
<p><a href="http://www.intelligrape.com/blog/wp-content/uploads/2011/03/Website-Payment-Preferences-PayPal_1300126988327.png"><img src="http://www.intelligrape.com/blog/wp-content/uploads/2011/03/Website-Payment-Preferences-PayPal_1300126988327.png" alt="" width="500" height="280" class="alignnone size-full wp-image-3356" /></a></p>
<p>
This enables the auto-redirect feature in the paypal account.<br />
<br />
This worked for me.<br />
Hope it helps.<br />
<br />
Vishal Sahu<br />
vishal@intelligrape.com</p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/03/15/paypal-integration-auto-redirecting-to-application-after-processing-payment/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Converting date from one timezone to another in groovy</title>
		<link>http://www.intelligrape.com/blog/2011/02/09/converting-date-from-one-timezone-to-another-in-groovy/</link>
		<comments>http://www.intelligrape.com/blog/2011/02/09/converting-date-from-one-timezone-to-another-in-groovy/#comments</comments>
		<pubDate>Wed, 09 Feb 2011 18:20:30 +0000</pubDate>
		<dc:creator>Vishal Sahu</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Java tools]]></category>
		<category><![CDATA[System]]></category>
		<category><![CDATA[convert date]]></category>
		<category><![CDATA[date]]></category>
		<category><![CDATA[date conversion]]></category>
		<category><![CDATA[date time]]></category>
		<category><![CDATA[date timezone]]></category>
		<category><![CDATA[timezone]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=2728</guid>
		<description><![CDATA[Hi,
In my recent grails project, i came across the situation where i needed to convert the date in given timezone to the date in another timezone. I searched a lot about it and got many solutions for this problem and then i came out with a simple way to do so.

Lets i have a date [...]]]></description>
			<content:encoded><![CDATA[<p>Hi,<br />
In my recent grails project, i came across the situation where i needed to convert the date in given timezone to the date in another timezone. I searched a lot about it and got many solutions for this problem and then i came out with a simple way to do so.<br />
<br />
Lets i have a date in TimeZone say oldTimeZone and i want to convert it to another timeZone say newTimeZone, so to convert it to another timezone, i wrote the method given below. </p>
<p></p>
<pre>

public Date convertToNewTimeZone(Date date, TimeZone oldTimeZone, TimeZone newTimeZone){

      long oldDateinMilliSeconds=date.time - oldtimeZone.rawOffset
      // oldtimeZone.rawOffset returns the difference(in milliSeconds) of time in that timezone with the time in GMT
      // date.time returns the milliseconds of the date

      Date dateInGMT=new Date(oldDateinMilliSeconds)

      long convertedDateInMilliSeconds = dateInGMT.time + newTimeZone.rawOffset
      Date convertedDate = new Date(convertedDateInMilliSeconds)

    return convertedDate
}
</pre>
<p></p>
<p>This Works for me.<br />
Hope it helps.</p>
<p>
Cheers..!!!<br />
Vishal Sahu<br />
vishal@intelligrape.com<br />
<a href="http:// www.intelligrape.com">www.intelligrape.com</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/02/09/converting-date-from-one-timezone-to-another-in-groovy/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Groovy: Sort list of objects on the basis of more than one field</title>
		<link>http://www.intelligrape.com/blog/2011/01/25/groovy-sort-list-of-objects-on-the-basis-of-more-than-one-field/</link>
		<comments>http://www.intelligrape.com/blog/2011/01/25/groovy-sort-list-of-objects-on-the-basis-of-more-than-one-field/#comments</comments>
		<pubDate>Mon, 24 Jan 2011 19:29:03 +0000</pubDate>
		<dc:creator>Salil</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Java tools]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[comparator]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[sorting]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=2699</guid>
		<description><![CDATA[Usually, when we deal with databases, we don&#8217;t face such kind of situation because we query database to get result-set in required order.
But let&#8217;s say you have a List of objects that you want to sort on the basis of two fields. Let&#8217;s discuss it with an example.

I have a list of Tasks (with date [...]]]></description>
			<content:encoded><![CDATA[<p>Usually, when we deal with databases, we don&#8217;t face such kind of situation because we query database to get result-set in required order.</p>
<p>But let&#8217;s say you have a List of objects that you want to sort on the basis of two fields. Let&#8217;s discuss it with an example.<br />
<br/><br />
I have a list of Tasks (with date and priority fields). I want to sort these tasks ordered by Date and priority-wise (as second level sorting).</p>
<p>Here, I gonna use Expando class, so I can directly run this in my groovyConsole. But definitely you can use some &#8216;Task&#8217; class.</p>
<pre class="brush: groovy;">
Expando a = new Expando(date: Date.parse('yyyy-MM-dd','2011-01-01'), priority:1)
Expando b = new Expando(date: Date.parse('yyyy-MM-dd','2011-01-01'), priority:2)
Expando c = new Expando(date: Date.parse('yyyy-MM-dd','2011-01-02'), priority:1)
Expando d = new Expando(date: Date.parse('yyyy-MM-dd','2011-01-01'), priority:3)

def list = [a,d,c,b]
</pre>
<p>If sorting was required on the basis of date only, it was very simple.</p>
<pre class="brush: groovy;">
list.sort(it.date)
</pre>
<p>But as per our requirements &#8211; order by date (first level sorting) and priority (second level sorting). We can do something like following.</p>
<pre class="brush: groovy;">
list.sort{x,y-&gt;
  if(x.date == y.date){
    x.priority &lt;=&gt; y.priority
  }else{
    x.date &lt;=&gt; y.date
  }
}
</pre>
<p>Well, there could be some better way. If you know please put your comments. But it worked well in my case.</p>
<p><br/><br />
Cheers!<br />
Salil Kalia<br />
Salil [at] IntelliGrape [dot] com<br />
<a href="http://twitter.com/salil_kalia" target='_blank'>Twitter</a> <a href="http://in.linkedin.com/in/salilkalia" target='_blank'>LinkedIn</a> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2011/01/25/groovy-sort-list-of-objects-on-the-basis-of-more-than-one-field/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>MalformedByteSequenceException with grails jasper plugin 1.1.6</title>
		<link>http://www.intelligrape.com/blog/2010/12/03/malformedbytesequenceexception-with-grails-jasper-plugin-1-1-6/</link>
		<comments>http://www.intelligrape.com/blog/2010/12/03/malformedbytesequenceexception-with-grails-jasper-plugin-1-1-6/#comments</comments>
		<pubDate>Fri, 03 Dec 2010 11:16:41 +0000</pubDate>
		<dc:creator>Sachin</dc:creator>
				<category><![CDATA[Java tools]]></category>
		<category><![CDATA[Jasper]]></category>
		<category><![CDATA[jasper plugin]]></category>
		<category><![CDATA[MalformedByteSequenceException]]></category>
		<category><![CDATA[reports]]></category>

		<guid isPermaLink="false">http://www.intelligrape.com/blog/?p=2186</guid>
		<description><![CDATA[MalformedByteSequenceException solved in grails jasper plugin 1.1.6]]></description>
			<content:encoded><![CDATA[<p>Hi All,</p>
<p>I was facing a lot of problems with creating pdf reports using jasper plugin 1.1.6 in grails, Though I had earlier worked with 0.9.5 and 0.9.7 versions of the plugin with a lot of ease but some how 1.1.6 version of plugin was not generating reports  it always ended up throwing <strong>MalformedByteSequenceException</strong>: Invalid byte 1 of 1-byte UTF-8 sequence.</p>
<pre class="brush: java;">com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Invalid byte 1 of 1-byte UTF-8 sequence.
 at com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.invalidByte(UTF8Reader.java:684)
 at com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.read(UTF8Reader.java:554)
 at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.load(XMLEntityScanner.java:1742)
 at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.arrangeCapacity(XMLEntityScanner.java:1619)
 at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.skipString(XMLEntityScanner.java:1657)
 at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(XMLVersionDetector.java:193)
 at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:772)
 at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
 at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
 at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
 at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
 at org.apache.commons.digester.Digester.parse(Digester.java:1647)
 at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:241)
 at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:228)
 at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:216)
 at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:199)
 at net.sf.jasperreports.engine.JasperCompileManager$compileReport.call(Unknown Source)
 at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:149)
 at java.lang.Thread.run(Thread.java:662)</pre>
<p>I tried various things like changing the header of the jrxml file, adding new attributes in jasperReport tag and changing encoding type but to no Avail. Then I tried generating report without the .jasper files and deleted all jasper files except for sub-reports (sub-reports need to be in a pre-compiled state for the plugin to work)  and thing started working. For some strange reason the plugin was throwing exception when jasper report was available but if the report was compiled on the fly the plugin had no trouble with it. I am not sure what may be the reason may be I-report or something, but I got a move on. Hope You will too.</p>
<p>With Regards</p>
<p>Sachin Anand</p>
<p>sachin[at]intelligrape[dot].com</p>
]]></content:encoded>
			<wfw:commentRss>http://www.intelligrape.com/blog/2010/12/03/malformedbytesequenceexception-with-grails-jasper-plugin-1-1-6/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

