Open Pdf in Google Docs using Time Based Cache in Grails

23 / Jun / 2010 by Hitesh Bhatia 1 comments

Recently, we had a requirement where secure URLs were to be made accessible to Google.

Our implementation was to send a url with token valid for 10 seconds. The token expired automatically after 10 seconds. We used time based cache for this as described here:

T set max time to 10 seconds , I set default MaxAge to 10 millis in above file only which could have also been done easily using its constructor.

Here’s how we did it ,

class AbcController {
    static TimedMap timedMap = new TimedMap()

   //  while calling "addDocumentUrl" path of document was passed as params attachmentPath
    def addDocumentUrl = {
 	        String attachmentPath = params.attachmentPath
 	        String token = UUID.randomUUID().toString()
 	        timedMap.put(uniqueIdentification,attachmentPath)
 	        redirect(url: getGoogleUrl(token))          // this will  make google hit specified url
 	    }

     String getGoogleUrl(String token) {
 	        String absoluteUrl = ConfigurationHolder.config.builder.absoluteURL
                String GOOGLE_URL="http://docs.google.com/viewer?embedded=true&url="
 	        String googlePath = GOOGLE_URL + absoluteUrl + "/abc/someAction/" + token
 	        return googlePath
 	    }
}

Action someAction was made public so that Google was able to access it. And when Google hits this action it gives token as id.

   def someAction = {
        String key = params.id.toString()
        try {
            String attachmentPath = timedMap.get(key)
            File file = new File(attachmentPath)
            response.setHeader("Content-disposition", "attachment; filename=pdf")
            response.setContentType("application/pdf")
            response.setContentLength(file.size().toInteger());
            OutputStream out = response.getOutputStream();
            out.write(file.readBytes());
            out.flush()
            out.close();
        } catch (Exception e) {
            e.printStackTrace()
        }
    }

_______________________________
Hitesh Bhatia
hitesh@intelligrape.com

_______________________________

FOUND THIS USEFUL? SHARE IT

comments (1 “Open Pdf in Google Docs using Time Based Cache in Grails”)

Leave a comment -