Grails « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ Grails ’

Handling Password Protected Pdf with PdfReader

Thursday, August 19th, 2010
Posted by Hitesh Bhatia

In one of our grails project , we had to attach cover to Pdf file . But since some of pdf’s uploaded were password protected.

To handle this scenario we added bouncyCastle.jar , so our version of iText was able to handle password protected pdf .
And Then to check whether pdf is password protected or not , we used “Boolean isOpenedWithFullPermission()” method.

PdfReader pdf = PdfReader("filePath")
Boolean editable = pdf.isOpenedWithFullPermissions()
 
if(editable){
//attach Cover
}else {
//skip  cover
}

As “isOpenedWithFullPermissions()” returns a Boolean variable ,
it was easy for us to recognize whether we would be able to edit (i.e attach cover in our case) depending on its output. (i,e true or false)
 

_________________________________
Hitesh Bhatia
Mail
LinkedIn,Facebook,Twitter
_________________________________

  • Share/Bookmark
Posted in Grails, Groovy

QR Code on PDF Documents for Identification and Detection on Server Side

Thursday, August 12th, 2010
Posted by Vivek Krishna

In one of our projects, we needed to include QR Code on the PDF documents, which were to be sent out to the user and the printed version was to be received back from them. Once the documents were received, we were going to scan each sheet into an image file and then, these files were going to be read by the grails application, identify the digital copy of the document and set a “received” status on the domain class representing the document.

Grails QR Code plugin proved to be an excellent choice to generate QR Codes to be included in the document, however, we were using iText Renderer, which meant that we had to provide the absolute URL to the image stream. This was accomplished by providing a URL, which was similar to

${createLink(controller: 'qrcode', action: 'text', absolute: true, params: [text: 'Text to be Encoded'])}

instead of using the the tags provided by the plugin. Ability to set the property ‘absolute’ while creating links is one of the features I would love to see in the QRCode tag library.

Once the hard copies of the documents were received, we were going to scan them and upload them to our grails application. There are many desktop utilities available for detecting QR Code on images, but no ready made solution for a web application.

A library which we found useful, however,  was zxing hosted on Google Code. This had a command line tool and the wiki also suggested possible ways to use the library within a java application.

What we did was to read the image using the javax.imageio.ImageIO.read() method (this takes in only a file, so we ended up writing the uploaded file temporarily on the disk and then read it) and then decode the qrcode as:

        com.google.zxing.Reader reader = new QRCodeReader()
        java.awt.image.BufferedImage image = ImageIO.read(imageFile)
        com.google.zxing.LuminanceSource source = new com.google.zxing.client.j2se.BufferedImageLuminanceSource(image);
        com.google.zxing.BinaryBitmap bitmap = new com.google.zxing.BinaryBitmap(new com.google.zxing.common.HybridBinarizer(source))
        Result result = reader.decode(bitmap)
        return result.text

This returns the text, which was embedded in the QR Code.

Hope this helps

Vivek

http://in.linkedin.com/in/svivekkrishna

  • Share/Bookmark
Posted in Grails, Java tools

Sharing Session Information between Wordpress and Grails using Cookies and base64 encoding

Tuesday, August 3rd, 2010
Posted by Vivek Krishna

A scenario arose in one of our projects that we had to share some information between the grails application (which was taking care of dynamic content) and wordpress (which was used to maintain the static pages about the application). The information was the logged in user’s name so that we could display that on the header. After giving it some thought, we decided that setting a cookie with the logged in user’s name from the grails application and then reading it from the wordpress application using javascript was one way of doing so.

This was achieved by setting the cookie with code on grails side as

Cookie cookie = new Cookie('userNameCookie', fullname);
cookie.setVersion(-1)  // unknown version bypasses quoting logic
cookie.path = "/"
cookie.maxAge = 30 * 60 * 60; //30 minutes life
response.addCookie(cookie)

There is an excellent jQuery cookie plugin to read cookies using javascript. All that needs to be done is include the javascript file and call the method given below to get the value from it

jQuery.cookie('userNameCookie')

However, there was an issue with this approach. The usernames could have unicode characters like ä, ö etc. The cookie was not getting set from the grails application and threw an Exception because the unicode characters weren’t escaped. The exception also suggested that we could use decodeBase64(). But since it was due to encode, we decided to convert the fullname to bytes, encode it to base64, call the toString() method and then set the value. What we did was to change the cookie value to from grails

Cookie cookie = new Cookie('usercookie', fullname.bytes.encodeBase64().toString());

In order to decode this base64 encoded string on the client side, we used the jQuery Base 64 Functions plugin. This can be used to decode a base64 encoded string as

jQuery.base64Decode(jQuery.cookie('userNameCookie'));

This worked like a charm.

Hope this helps

Vivek

http://in.linkedin.com/in/svivekkrishna

vivek[at]intelligrape.com

  • Share/Bookmark

Unique closure on more than one field.

Monday, August 2nd, 2010
Posted by Hitesh Bhatia

In one of my recent grails project, I had requirement to get unique objects from list based on more than one field. Now this can be done by passing list to closure unique .

I had list of dates of couple of years ,and what I needed was unique combination of month and year.

List<Date>  dates 
date.unique{[it.month,it.year]}

_________________________________
Hitesh Bhatia
Mail
LinkedIn,Facebook,Twitter
_________________________________

  • Share/Bookmark
Posted in Grails, Groovy

Grails : load proxy domain objects

Monday, July 26th, 2010
Posted by Amit Jain

Hi Friends,

I was going through grails docs, encountered a method called load(), found it really useful thought would share with you. What load() does is, it creates a proxy object and doesn’t retrieve the record from the database until property other than id is accessed.
Let us consider a scenario, where we have id of a Object “subject” and students of that subject needs to be listed. So we would generally do something like as given below:

Subject subject = Subject.get(subjectId)
Student.findBySubject(subject)

In the above code, we had to load subject unnecessarily where its ‘id’ should have been sufficient. Now, with load no extra queries are required.

Subject subject = Subject.load(subjectId)  //creates a proxy object, not retrieved from database 
Student.findBySubject(subject)

And same when used with criteria queries

Student.list{
  eq('subject', Subject.load(subjectId))
  ...
}

Thanks to the grails development team for all their efforts!

Cheers!!

~~Amit Jain~~
amit@intelligrape.com

http://www.IntelliGrape.com

  • Share/Bookmark
Tags: , ,
Posted in Grails

Tomcat 6 Session Persistence through JDBCStore

Wednesday, July 21st, 2010
Posted by Abhishek Tejpaul

In one of our recent projects, we needed to save the HTTP session in the database.
This blog refers the Apache documentation as found here: http://tomcat.apache.org/tomcat-6.0-doc/config/manager.html

These are the following steps that need to be followed:

Step 1: Create a database named tomcat (as shown in our example in Step 3 below) or any other name as specified in the ‘connectionURL’ attribute of the <Store> element.

Step 2: Create the following table in the newly created database:

create table sessions (
session_id     varchar(100) not null primary key,
valid_session  char(1) not null,
max_inactive   int not null,
last_access    bigint not null,
app_name       varchar(255),
session_data   mediumblob,
KEY kapp_name(app_name)
);

Step 3: Copy the context.xml file available at the global level at this location: <TOMCAT_HOME>/conf to your application’s META-INF folder and replace the <Manager> element with the following:

<Manager className='org.apache.catalina.session.PersistentManager'
                saveOnRestart='false'
                minIdelSwap='0'
                maxIdleSwap='0'
                maxIdleBackup='1'>
<Store className="org.apache.catalina.session.JDBCStore"
driverName="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost/tomcat?user=username&amp;password=password"
sessionTable="sessions"
sessionIdCol="session_id"
sessionDataCol="session_data"
sessionValidCol="valid_session"
sessionMaxInactiveCol="max_inactive"
sessionLastAccessedCol="last_access"
sessionAppCol='app_name' />
</Manager>

If these settings are placed in the ‘<TOMCAT_HOME>/conf/context.xml‘, it will have a global effect on all the applications running on the server. For an application specific setting, you can place a newly created “context.xml” file in the <APP_HOME>/META-INF sub-folder inside the webapps folder.
Please note that attributes used in the <Store> element make use of the table columns as created in the database in Step 2.

Step 4: Set the following system properties named – ‘org.apache.catalina.session.StandardSession.ACTIVITY_CHECK‘ to ‘true‘.
For further information on this, read the ‘Persistent Manager Implementation’ section at this link : http://tomcat.apache.org/tomcat-6.0-doc/config/manager.html

Step 5: Make sure you have placed the MySql jar in the <TOMCAT_HOME>/lib folder.

Now you can try to hit the application’s URL and check the database table to see the newly persisted session. Please note that it takes around 60 seconds to see the stored session in the database so you might have to wait a bit. You can have multiple instances of tomcat running your application pointing to the same database and can share this persisted session in case any of the tomcat instance crashes.

NOTE: Please make sure if you make any changes to the “context.xml” file, you have to delete the following xml file located in the <TOMCAT_HOME>/conf/Catalina/localhost/{yourAppName}.xml. If you don’t delete this file, then your changes will be ignored and the settings defined in this file will take effect.

Cheers!!!

Abhishek & Imran

abhishek@intelligrape.com | imran@intelligrape.com

[Intelligrape Software Pvt. Ltd.]

  • Share/Bookmark
Posted in Database, Grails

Searchable plugin – Lucene search on numeric values

Wednesday, July 14th, 2010
Posted by Aman Aggarwal

While using searchable plugin for the first time, I wasn’t aware that lucene implements only lexicographic comparisons for searching on indexed values (even on numeric fields). Before I learned this, I kept on wondering why a Person of age 6 always appeared in search results when I look for People more than 20 years of age. The solution was to define a transient field ageIndexValue in domain class Person and implement its getter as:

String getAgeIndexValue() {
    return org.apache.lucene.document.NumberTools.NumberTools.longToString(this.age)
}

Also, you will need to change the search query from

q=age:[20 TO *] to q=ageIndexValue:[0000000000000u TO *]
where, 0000000000000u == org.apache.lucene.document.NumberTools.NumberTools.longToString(20L)

~Aman Aggarwal
aman@intelligrape.com

http://www.IntelliGrape.com/

  • Share/Bookmark
Posted in Grails

Grails: Change number of records displayed with Remote-Pagination

Tuesday, June 29th, 2010
Posted by Amit Jain

Hi Friends,

I have released version 0.2.3 of remote-pagination plugin, which includes an option to enable user to change page sizes out of the given options. As given in the documentation, lets have a look at the example below :

//Example Domain:
class Book {
String title
String author
}
 
//Example controller:
class BookController {
def list = {
[books: Book.list(params)]
}
 
def updateList ={
render(template:"listTemplate" ,model:[ bookInstanceList: Book.list(params )]) }
}
 
//GSP Code :

Demo Image :

Demo image

Now when the user changes the page size, it updates the number of records in a table asynchronously. We can also pass additional parameters if needed, using the params attribute.

Hope this helped!

~~Amit Jain~~
amit@intelligrape.com

http://www.IntelliGrape.com

  • Share/Bookmark
Posted in Grails

Clearing Hibernate Query Cache in Grails

Wednesday, June 23rd, 2010
Posted by Vivek Krishna

In one of the projects, we had used Query Caching to improve the performance. However, it also meant that the updates/inserts into a table did not get reflected immediately, i.e. something like:

DomainClass.findByPropertyName("propertyName", [cache: true])

returned the same list as it was, before the insertion/updation took place. We found that this could be resolved by clearing the query cache every time an update took place. This was done in Grails by making a call:

sessionFactory.queryCache.clear()

Make sure that the artefact(controller, service, taglib, job etc.) has sessionFactory injected into it using the line:

def sessionFactory

Hope this helps.

– Vivek

vivek[at]IntelliGrape[dot]com

http://in.linkedin.com/in/svivekkrishna

  • Share/Bookmark
Posted in Database, Grails, Java tools

Open Pdf in Google Docs using Time Based Cache in Grails

Wednesday, June 23rd, 2010
Posted by Hitesh Bhatia

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: http://snippets.dzone.com/posts/show/2360

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&amp;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

http://in.linkedin.com/in/bhatiahitesh

_______________________________

  • Share/Bookmark
Posted in Grails, Groovy, Java tools