Grails « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ Grails ’

Reading Google Drive Spreadsheet in Grails Application

Posted by on May 13th, 2013

OAuth is a secure mechanism to access google drive. In order to access google drive in your application you need to register your application at the google API console at Google API Console. Read the blog  Integrating Google plus in grails application by Vishal Sahu to see how to get client ID, client secret and redirect URL but in order to read google drive spreadsheets select Drive API in the services pane while registering your project.

Now to access your Google drive in your grails application you may save the client ID, client secret and redirect URL in Config.groovy like this:

 googleDrive{
  redirectURL = "Redirect Url"
  clientId  = "Client Id"
  clientSecret= "Client Secret"
}

Add following  dependencies in BuildConfig.groovy to import jars for accessing google documents and OAuth authorization:


compile "com.google.gdata:core:1.47.1"
compile "com.google.apis:google-api-services-drive:v2-rev72-1.14.2-beta"
compile "com.google.http-client:google-http-client-jackson:1.14.1-beta"

To access authorized user’s google drive, you need to get an authorization URL. User of the application must access this URL to authorize the application with Google and generate the authorization code. Following sample action generates the required authorization URL:


def index = {
   String clientId = grailsApplication.config.googleDrive.clientId
   String redirectURL = grailsApplication.config.googleDrive.redirectURL
   //List of scopes for which to request access
   List scopes =["https://spreadsheets.google.com/feeds", "https://docs.google.com/feeds"];
   String authorizationUrl =
   new GoogleAuthorizationCodeRequestUrl(clientId , redirectURL, scopes).build();
   redirect(url: authorizationUrl)
 }

The browser will redirect to the URL you specified in the redirectUrl parameter with the authorization code. Here is a sample redirect action which sets the authorization code in session.


def callback(String code) {
  HttpSession session = request.getSession();
  session.code = code;
  setCredential()
}

The setCredential() method generates the access token and sets its value in the session.

def setCredential() {
  HttpTransport transport = new NetHttpTransport()
  JacksonFactory jsonFactory = new JacksonFactory()
  String clientId = grailsApplication.config.googleDrive.clientId
  String clientSecret = grailsApplication.config.googleDrive.clientSecret
  String redirectUrl = grailsApplication.config.googleDrive.redirectURL
  GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest
  (transport, jsonFactory, clientId, clientSecret,session.code, redirectUrl).execute();
  GoogleCredential accessToken = new GoogleCredential.Builder()
  .setClientSecrets(clientId, clientSecret)
  .setJsonFactory(jsonFactory).setTransport(transport).build()
  .setAccessToken(response.getAccessToken()).setRefreshToken(response.getRefreshToken());
  session.accessToken = accessToken
}

Once you have the access token you may access google drive. Following code snippet returns a list of all spreadsheets. Now you can view, edit, delete and manipulate your spreadsheets using Google Spreadsheet API.


SpreadsheetService service = new SpreadsheetService("MySpreadsheetService");
service.setOAuth2Credentials(session.accessToken)
URL sheetFeedUrl = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full")
SpreadsheetFeed feed = service.getFeed(sheetFeedUrl,SpreadsheetFeed.class);
List spreadsheets = feed.getEntries()

Following is the code for reading data from first spreadsheet from the list retrieved above:


List worksheets = spreadsheets.get(0).getWorksheets();
worksheets.each{worksheet->
URL listFeedUrl = worksheet.getListFeedUrl();
ListFeed listFeed = service.getFeed(listFeedUrl, ListFeed.class);
listFeed.entries.each{row->
row.customElements.tags.each{tag->
   println "Column: ${tag} -- Value: ${row.getCustomElements().getValue(tag)}"
  }
 }
}

Helpful links:

https://code.google.com/apis/console/

https://developers.google.com/google-apps/spreadsheets/

Hope it helps!!
Paridhi Goel
paridhi@intelligrape.com

Posted in Google Web Tools

Using Ftp with Grails

Posted by on April 4th, 2013

In one of my Grails project I need to drop files over ftp server. Using JSch one can easily transfer files over sftp. Just follow the below steps.
1. Add the below dependency to Grails project “grails-app/conf/BuildConfig.groovy” file

dependencies {
        compile 'com.jcraft:jsch:0.1.49'
    }

2. Create a class for adding ftp credentials information. e.g. “FtpCredentail”

class FtpCredential {

    String server
    String username
    String password
    String remoteBaseDir
    Integer port
}

3. Create a service named “FtpService” and add the following code into it

import com.jcraft.jsch.Channel
import com.jcraft.jsch.ChannelSftp
import com.jcraft.jsch.JSch
import com.jcraft.jsch.Session

class FtpService {
    def grailsApplication

    static transactional = true

    def save(InputStream inputStream, String fileName, FtpCredential ftpCredential) {
        connect(ftpCredential) { ChannelSftp sftp ->
            sftp.put inputStream, fileName
        }
    }

    def load(String fileName, FtpCredential ftpCredential) {
        connect(ftpCredential, { ChannelSftp sftp ->
            File outputFile = File.createTempFile(fileName,'')
            outputFile?.newOutputStream() << sftp.get(fileName)
            outputFile
        }, false)
    }

    def delete(String fileName, FtpCredential ftpCredential) throws Throwable {
        connect(ftpCredential) { ChannelSftp sftp ->
            sftp.rm fileName
        }
    }

    def makeDir(String directoryName, FtpCredential ftpCredential) {
        connect(ftpCredential) { ChannelSftp sftp ->
            sftp.mkdir directoryName
        }
    }

    private def connect(FtpCredential ftpCredential, Closure c, boolean disconnectOnFinish = true) {
        Session session = null
        ChannelSftp sftp = null
        try {
            JSch jSch = new JSch()
            session = jSch.getSession username, ftpCredential?.server, ftpCredential?.port
            session.setConfig "StrictHostKeyChecking", "no"
            File keyFile = new File("${grailsApplication.config.pathToKeyFile}")
            if (ftpCredential?.password) {
                session.password = ftpCredential?.password
            } else {
                jSch.addIdentity(keyFile?.absolutePath)
            }
            session.connect()
            Channel sFtpChannel = session.openChannel "sftp"
            sFtpChannel.connect()
            sftp = sFtpChannel as ChannelSftp
            sftp.cd ftpCredential?.remoteBaseDir
            c.call sftp
        } catch (Exception ex) {
            ex.printStackTrace()
        } finally {
            if (disconnectOnFinish) {
                sftp?.exit()
                session?.disconnect()
            }
        }
    }
}

Note: In the above code at line number 44.

File keyFile = new File("${grailsApplication.config.pathToKeyFile}")

The code looks for private key provided by ftp server for password-less log in. One should define the property named “pathToKeyFile” in “grails-app/conf/Config.groovy” with value equals to the path of key file.

Now you are ready to use the newly created FtpService service methods. Such as:

  1. save(inputStream, fileName, ftpCredential) for saving file over ftp.
  2. load(fileName, ftpCredential) for getting file from ftp.
  3. delete(fileName, ftpCredential) for deleting file over ftp.
  4. makeDir(directoryName, ftpCredential) for creating directory over ftp.

Example

For saving file over ftp one can use FtpService save method as shown below

 File file = File.createTempFile("temp","txt")
 FtpCredential ftpCredential = new FtpCredential(server: <server>, username: <username>, password: <password>, port: <server_port>, remoteBaseDir: <remote_base_directory>)
 InputStream inputStream = new BufferedInputStream(new FileInputStream(file))
 ftpService.save(inputStream, "fileNameToBeSavedOverFTPServer", ftpCredential)

Please share your feedback and suggestions.


Click here to read more JSch examples »



Puneet Behl
puneet.behl@intelligrape.com
https://twitter.com/puneetbhl
http://in.linkedin.com/in/puneetbhl

Posted in Grails

Grails GSP tag: grep

Posted by on October 31st, 2012

The other day I was reading the Grails docs and I came across a useful GSP tag: grep. I have been using Grails for over 3 years now but just recently got to see this new tag which has eased my life a bit in situations where the list of objects have to be filtered and iterated at the same time to perform some operations on them. The GSP ‘grep’ tag (equivalent to the ‘grep’ method in Groovy) filters the list on a given condition and iterates over the filtered list allowing you to do some operations on the objects (or whatever you want to do with the filtered objects).

I will give you a small example: Suppose we have a list of Person objects. You want to display the names starting with A, B, C and so on in different color schemes. How would you do it?

One implementation is to send different lists from the controllers (this would mean sending 26 lists i.e. one list for each character in the English alphabet) and render them in different color schemes. The other way would be to iterate over the Persons list in the GSP and have  different <g:if>…<:g:elseif> statements (for each character).

There is another smarter way: you could also use the ‘findAll‘ method of the List in the GSP <g:each> tag’s ‘in’ attribute i.e <g:each in=${personList.findAll {it.name.startsWith(‘A’)}} var=”person”> … </g:each>.

Similarly, we can use ‘grep’ tag here. We can filter out the list like this: <g:grep in=”${personList.name}” filter=”~/^A.*/”> … </g:grep>.

Notice the use of ‘name‘ field of the Person object in the ‘in‘ attribute of the grep tag. Also, the attribute ‘filter’ takes many forms of filter options; here we are using regex to filter the persons with the name starting with ‘A’.

I am not saying that this tag provides some new functionality which we could not have achieved by any other means but this tag makes it easier to filter out the lists on some specific parameters.

You can read more about this tag here. Also you can read about the Groovy GDK’s grep method usage here to see how and in what scenarios you can use this tag.

Hope this helps !!

- Abhishek Tejpaul
abhishek@intelligrape.com

Posted in Grails

Cool way to get/set processed HTML Markup in filters

Posted by on September 27th, 2012

Hi,

 

There was a case where i had to encrypt the HTML output of the GSP before displaying it to user. There are a lot of ways to do it, but i wanted to make is as simple as possible. Hence here is the pattern i used:

 

Note: This is just an example, you can use this concept to do thousands of cool things, like: pdf export etc..

 

ON THE GSP

<html>
<head>
<meta name="encrypt" value="true" />   
    ...
</head>
 .... misc code
</html>

Here what is did is, i created a GSP and just added a meta property to it saying “encrypt true”.

 

Now here is the Code for the Grails Filters (See inline comments)

def filters = {
        all(controller: '*', action: '*') {
            before = {                
            }
            after = { Map model ->
                try {
                    //Get the Site Mesh Page Instance
                    GSPSitemeshPage sitemeshPage = response?.getContent() as GSPSitemeshPage
                   
                    //Check if it is actual sitemest page, not just plain rendered content
                    if (sitemeshPage && sitemeshPage.getPage()) {
                        //Get the meta property value.
                        String metaPropValue = sitemeshPage.getProperty("meta.encrypt")
                        if (metaPropValue && metaPropValue == "true") {
                            //This is how you can get html contents of head/body after all tags resolved.
                            String head = new String(sitemeshPage.getHead())
                            String body = new String(sitemeshPage.getBody())

                            //Buffer for new body
                            StreamCharBuffer writer = new StreamCharBuffer()
                            //Write to buffer new content
                            writer.getWriter().write(encryptionService.encrypt(body))
                            sitemeshPage.setBodyBuffer(writer)
                        }
                    }
                } catch (Throwable ex) {
                    ex.printStackTrace()
                }
            }
            afterView = { Exception e ->

            }
        }
    }

 

And hence we have this processed content in response :)

 

 

Regards
Kushal Likhi

Posted in Grails

Groovy: Overriding “Plus” operator in a class with interesting example

Posted by on September 26th, 2012

Have you ever wondered how to overload “plus” operator in Groovy ? It is as easy as adding toppings to your favourite pizza. Let me explain. Let us taka a class for Pizza:

 

@ToString
class Pizza {
    String name
    List<Topping> toppings
    double price

}

And another for the Topping:

@ToString
class Topping {
    String name
    double price
}

Now to add toppings to the favourite pizza, let us overload the plus operator in Pizza class like this:

//Method with name "plus" will override the "+" operator. It will return a new pizza with the Toppings added.
    Pizza plus(Topping topping) {
        new Pizza(name: name, toppings: toppings + [topping], price: price + topping.price)
    }

Let us order a pizza:

Pizza pizza = new Pizza(name: "Veg Extravaganza Pizza", price: 323.32, toppings: [])

And our favourite toppings as well:

Topping cheeseBurst = new Topping(name: "cheese Burst", price: 80)
Topping extraCheese = new Topping(name: "Extra Cheese", price: 40.43)
Topping jalepenos = new Topping(name: "Jallepenos", price: 50.33)
Topping capsicum = new Topping(name: "capsicum", price: 20.32)

Can’t wait to add them all:

Pizza specialPizza = pizza + cheeseBurst + extraCheese + jalepenos + capsicum

Let us unbox our pizza:

println (specialPizza)
//OUTPUT
/*

Pizza(Veg Extravaganza Pizza, [Topping(cheese Burst, 80.0), Topping(Extra Cheese, 40.43), Topping(Jallepenos, 50.33), Topping(capsicum, 20.32)], 514.4)
*/

Isn’t it mouth watering.

Hope this helps.

 

Imran Mir
imran[at]intelligrape.com

Posted in Grails, Groovy

Instance based login in spring security core

Posted by on September 26th, 2012

Spring security loads the roles of user from user role table based on all roles assigned to user and that role is application specific.
But In my project i require to assign roles to user based on instance . So when the instance is changed roles should be changed .In grails we can overide the methods of plugin. So when instance change i reauthenticate the user and overrided the “loadAuthorities ” method of spring security. So instead of fetching roles from spring security loadAuthorities method , it loads from this overided loadAuthorities method…

class UserRole implements Serializable {

    User user
    Role role
    BootCamp bootCamp

     
class CustomUserDetailsService extends GormUserDetailsService {

@Override
protected Collection loadAuthorities(user, String username, boolean loadRoles) {
		if (!loadRoles) {
			return []
		}
def conf = SpringSecurityUtils.securityConfig
String authoritiesPropertyName = conf.userLookup.authoritiesPropertyName
String authorityPropertyName = conf.authority.nameField
Bootcamp bootCamp=BootCamp.get(RequestContextHolder.currentRequestAttributes().getSession()?.bootCampId))      
  User loggedInUser = User.findByEmail(username)
 //Write your query for loading roles here for ex.

Collection<?> userAuthorities =UserRole.findAllByUserAndBootCamp(loggedInUser, bootCamp)?.role

		
def authorities = userAuthorities.collect { new GrantedAuthorityImpl(it."$authorityPropertyName") }
authorities ?: NO_ROLES
	}
}

for example i am reloading the role by calling this method…

def getAuthoritiesBasedOnBootCamp() {
        session.bootCampId = params.bootCampId
        springSecurityService.reauthenticate(User.loggedInUser.email, "")
        redirect(action: 'dashBoard')
    }

Shaurav@intelligrape.com

Posted in Grails

Few Simple steps for integrating Rabbit MQ with Grails

Posted by on September 25th, 2012

Rabbit MQ as defined by rabbitmq.com is a robust messaging for applications. We used RabbitMQ to achieve asynchronous communication between two parts of the application.

I would like to share the same in a step by step fashion.

Here are few simple steps that I followed to make my grails application use rabbitmq:
(more…)

Posted in Grails

Redis: Heavyweight Tags – an awesome use-case for caching with Redis

Posted by on September 25th, 2012

Redis plugin provides a beautiful way to cache the html tags. Using this plugin we can make big savings on the time taken to render the gsp tags.

<redis:memoize  key="someKey" expire="3600" >
   //Some heavy weight tags rendering
  // Lots of db / network operations.
</redis:memoize>

I found this tag extremely helpful in rendering the public facing pages of our site. the pages which refreshed not very frequently and required few seconds to render(if done without caching).

The difference in the time taken to render the page is dependent on our choice of right candidate for Memoizing.

(more…)

Posted in Design Pattern, Grails

Redis: Tag Cloud using Redis

Posted by on September 25th, 2012

I would like to share a simple and efficient way of creating tagclouds that I discovered very recently. A Tag Cloud is a pictorial representation of some tags/text. The size of the tag/text is drirectly proportional to the weightage of that tag/text. A sample tag cloud could be seen on our blogs site.

How to do it?

A very simple way of making it possible is just by making a Map having the Tag as key and its occurrences as the value. 

The presence of redis makes me think that it is not at all taxing for my poor server.

Redis provides a data-structure called Sorted Set. In Sorted sets, every member of a Sorted Set is associated with score, that is used in order to take the sorted set ordered, from the smallest to the greatest score. While members are unique, scores may be repeated.

We can use the Sorted Set to contain the Tags as value and their corresponding weightage as score. This way we have a Sorted Set of all the Tags. We may choose to select top 50 Tags from the Sorted Set.

Prerequisite: You must have Redis installed and running on your machine. Here is a link to Redis site showing how to do it http://redis.io/download

Here is an example of showing top 50 tags from Blog domain class.

class Blog{
  String content
  String title
  static hasMany = [categories: String]
}

The code for generating the tagCloud is:

 Jedis redis = new Jedis("localhost");
    redis.connect();

 for (def blog: Blog.list()) {
                        blog.categories.each {catgry ->
                            redis.zincrby('tag-cloud-sorted-set', 1, "${catgry}")
                        }
                    }

 Map tagCloud = [:]
        Set<String> categories = redis.zrevrange('tag-cloud-sorted-set', 0, 50)
        int size = 30
        categories.eachWithIndex {catgry, idx ->
            if (idx % 15 == 0) {
                size = size - 3
            }
            tagCloud.put(catgry, size.toString())
        }
   return tagCloud

Once we get the Map of tagCloud we can render it as follows:

 		<g:each in="${tagCloud.keySet()}" var="key" status="idx">
                    <g:link action="search" controller="feed" params="[category: key]"
                            style="font-size: ${tagCloud.get(key)}px;">${key}</g:link>
                </g:each>

(more…)

Posted in Grails

A Nice pattern for Exception Handling in Grails Actions

Posted by on September 25th, 2012

I always wondered about finding a nice way to handle the Exceptions in my applications. I usually ended up creating tens of Exception classes and handling them.

Recently, I came across a nice way of achieving the same. I am thankful to my colleague Amit Jain for helping me realize this nice pattern.

def myService 

def myAction = {
  
try{
myService.doSomeTask()
}catch(BusinessException ex ){
   flash.message = ex.message
}catch(Exception ex){
   flash.message = "Internal Error"
   log.error("Unknown Exception:", ex);
}
}

Since, the day I started to follow this pattern, I rarely needed too many Exception classes.

(more…)

Posted in Grails