Intelligrape Groovy & Grails Blogs

Duplicate headers received from server issue on chrome

Posted by Tarun Pareek on April 11th, 2012

Hi,
 
Recently, in my project while downloading some files(not on all files) i am getting exception on chrome, that say :
 
Duplicate headers received from server

Error 349 (net::ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION): Multiple Content-Disposition headers received. This is disallowed to protect against HTTP response-splitting attacks.
 

But when i download the same files on IE, Firefox and other browsers that causing exception, no problem occur it work like charm. :)
 
But its weird that why is chrome giving exception only on some files while downloading, then i searched, i found that new release of chrome has this problem. It seem like Content-disposition header become very strict and sensitive, in the spec that chrome uses.
 
Solution that worked for me to solve the problem :
 
Wrong :

response.setHeader(“Content-disposition”, “attachment; filename=${fileName}”)

Correct :

response.setHeader(“Content-disposition”, “attachment; filename=\”"+fileName+”\”")
 
It worked for me. Hope it helps you also :)
 
Thanks,
Tarun Pareek
tarun@intelligrape.com
http://in.linkedin.com/in/tarunpareek
More Blogs by Me

  • Share/Bookmark
Posted under Grails, Groovy

Setting default layout in Grails application

Posted by Uday Pratap Singh on April 5th, 2012

Grails uses Sitemesh for adding layout to the views. Layouts are located in layouts folder and to add layouts to the view we generally add any of the following line in head

<g:applyLayout name="layoutName"/>
or
<meta name="layout" content="layoutName" />

But most of the time we have single layout, so why we repeat the same line for adding layout in our gsps. Grails has the solution for this as well.
Grails comes with a config property grails.sitemesh.default.layout which will set the layout of the page if there is no layout tag added to the gsp. We just need to write the following lind in Config.groovy and its all done

grails.sitemesh.default.layout = 'layoutName'

But the bad part is it doesn’t work with the scaffolded code even if I update the template of my view and remove the meta tag of layout. It would be nice if grails comes with this config property and I just need to update the layout property to change the layout.
Hope it helps


## Uday Pratap Singh ##
uday@intelligrape.com
http://www.IntelliGrape.com/
http://in.linkedin.com/in/meudaypratap

  • Share/Bookmark
Posted under Design Pattern, Grails

Importing Domain Constraints

Posted by Imran Mir on April 4th, 2012

Following DRY is at the heart of grails. While saving domain objects in our project, we used to copy the domain class constraints to the Command Objects (pretty ugly as it is), until we found that we can import constraints directly from the domain classses using importFrom() method in Grails 2.0

class VenueCO {
    String name
    String description
    Integer someExtraField

    String addressLine1
    String addressLine2
    String city
    String state
    String zip

    static constraints = {
        importFrom Venue
        importFrom GeographicAddress

        someExtraField(nullable: false)
    }
}

Not only does it import all the constraints from the User and GeographicAddress domain classes and apply them to our command object, but also ignores the constraints that don’t have corresponding properties in the command object.

Other variations of the importFrom() are:

importFrom User, include: ["lastName"]
importFrom User, include: [/.*Name/]   // imports all constraints that ended with 'Name'

Note: It works for grails 2 and above. For others there is a similar concept of shared constraints.

Cheers.
Imran Mir
imran[at]intelligrape[dot]com

  • Share/Bookmark
Posted under Grails

Forgot Root Password in Linux, How to Reset Root Password through GRUB?

Posted by Tarun Pareek on March 28th, 2012

Hi,
 
It is a major problem when we forgot our root password in linux. But don’t know how to recover it. First thought that came to mind reinstall machine. But I found a way that might help you without reinstall and save your hours. It is a interesting trick in linux to get back our root password in few minutes. I used it on ubuntu 11.10 it work fine for me. Some people might know about this method, but I thought i share with you all for those who don’t know.
 
Caution : But please don’t play with this for fun, only use it when in need.
 
Here are the steps to get back your password :
1. Reboot your system.
2. When Grub Loads, Either move arrow to stop clock/timer.
3. Select Ubuntu Kernel, and then Press ‘e’ key to open it in Edit Mode.
 

 
4. In edit mode, screen will look like this in Ubuntu…
 

 
If you see the 2nd line from bottom, that says info about kernel add ‘1′ in end of command as given below,
linux /boot/vmlinuz-2.6.31.9 root=UUID=904bf39-9234 ro quiet splash 1
 
5. Then Press Ctrl + b to boot kernel in single user mode.
6. By using passwd command reset your root password,
root# passwd
New UNIX Password:
Retype UNIX Password:
passwd updated successfully
 
7. Now reboot the machine, machine will reboot with your new password.
 
I hope it helps. ;)
 
Thanks,
Tarun Pareek
tarun@intelligrape.com
http://in.linkedin.com/in/tarunpareek
More Blogs by Me

  • Share/Bookmark
Posted under Linux, System

mysqldump of particular records without create – drop of tables

Posted by Tarun Pareek on March 27th, 2012

Hi,
 
Recently i was in a situation where i need to take the dump of particular records in mysql. We are pretty much familiar with the normal mysqldump statement given below :

mysqldump --user=usr --password=pwd database_name table_name > dumpFile.sql;

The above statement will provide us the dump of the respective database and table into the dumpFile.sql. But if you open the dump file you will see something like this :
 

    //dumpFile.sql
DROP TABLE IF EXISTS `table_name`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `table_name` (
  ...
) ENGINE=InnoDB AUTO_INCREMENT=204182 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `table_name`

LOCK TABLES `table_name` WRITE;
/*!40000 ALTER TABLE `table_name` DISABLE KEYS */;
INSERT INTO `table_name` VALUES ('1','data1');
/*!40000 ALTER TABLE `table_name` ENABLE KEYS */;
UNLOCK TABLES;

Because of the above dump, it will always first drop and recreate the table before sourcing your dump into the database.
So our first task to remove the creation and drop of table from the mysqldump, because when we take dump of particular records, What we want is just inserting the records in database without create and drop of tables and no loss of existing data.
 

    //Creating Dump without create and drop of table :
mysqldump --user=usr --password=pwd --no-create-info database_name table_name > dumpFile.sql;

If you compare the first and above statement there is only one change, –no-create-info option :
It don’t write CREATE TABLE statements that re-create each dumped table. So our dumpFile.sql now contains only this :

--
-- Dumping data for table `table_name`

LOCK TABLES `table_name` WRITE;
/*!40000 ALTER TABLE `table_name` DISABLE KEYS */;
INSERT INTO `table_name` VALUES ('1','data1');
/*!40000 ALTER TABLE `table_name` ENABLE KEYS */;
UNLOCK TABLES;

 

    //Creating Dump of particular records using conditional clause and without create and drop of table :
mysqldump --user=usr --password=pwd --no-create-info database_name table_name --where="id in (1,2,3)"> dumpFile.sql;

In above statement with –no-create-info, we removed the create-drop of table and by –where option we can specify our condition on basis of which we want to fetch the particular records. In above statement it will fetch the record in table that has value 1, 2 or 3 in field ‘id’. So our dumpFile.sql now contains only this :

--
-- Dumping data for table `table_name`
--
-- WHERE:  id in (1,2,3)

LOCK TABLES `table_name` WRITE;
/*!40000 ALTER TABLE `table_name` DISABLE KEYS */;
INSERT INTO `table_name` VALUES ('1','data1'),('2','data2'),('3','data3');
/*!40000 ALTER TABLE `table_name` ENABLE KEYS */;
UNLOCK TABLES;

 
I hope it helps. :)
 
Thanks,
Tarun Pareek
tarun@intelligrape.com
http://in.linkedin.com/in/tarunpareek
More Blogs by Me

  • Share/Bookmark
Posted under Database

Writing sentences with Groovy 2.0

Posted by Vivek Krishna on March 22nd, 2012

Groovy 2.0 comes with some amazing new features, which prompted a numbering scheme jump from 1.9.x to 2.0. One of the key features that I took note while going through  Guillaume Laforge’s presentation at 33rd Degree was the support for plain language sentences made possible by optional parentheses,  and dots.

We love the language and we love pizza! So, I put together a small script to demonstrate the power of natural language support available on Groovy 2.0 (Tested the feature on 2.0.0-beta2).

The PizzaDelivery takes orders and outputs the order.


class PizzaDelivery {

    Integer quantity
    String topping
    Date time

    PizzaDelivery need(Integer quantity){
        this.quantity = quantity
        return this
    }

    PizzaDelivery with(String topping){
        this.topping = topping
        return this
    }

    PizzaDelivery at(String time) {
        this.time = Date.parse('h:mm', time)
        return this
   }

   String toString(){
        return "${quantity} ${topping} at ${time.format('h:mm')} hours"
   }
}

PizzaDelivery pizzaDelivery = new PizzaDelivery()
pizzaDelivery.with{
    need 3 with 'pepperoni' at '6:00'           // need(3).with('pepperoni').at("6:00")
}

println pizzaDelivery

This will allow us to create very simple yet elegant DSLs which would feel like English or any other language that one feels comfortable with.

  • Share/Bookmark
Posted under Groovy

Sharing HTTP Session between subdomains

Posted by Imran Mir on March 21st, 2012

Recently, I had a usecase to share same http session between different subdomains. The idea was that if a user is logged in on “somedomain.com“, he need not to login again to go to subdomain.somedomain.com. The same http session should be usable. I started off on the wrong foot by looking into the SpringSecurity plugin, which I had been using. But, later on, I found that this is to be done by configuring the Tomcat. The solution is to configure tomcat to recongnize session cookies from the subdomains. So all it takes is to modify element tomcat/conf/Context.xml to:

 <Context sessionCookiePath="/" sessionCookieDomain=".yourdomain.com">

and you are good to go. The solution works for Tomcat version 6.0.27 and above.

Cheers,
Imran Mir
imran[at]intelligrape[dot]com

  • Share/Bookmark
Posted under Grails, System

Integrating LinkedIn with grails application

Posted by Vishal Sahu on March 19th, 2012

In my recent grails project, i needed to integrate LinkedIn with the application using LinkedIn API. I searched a lot about it and find the Java wrapper of linkedIn to use it with my grails application and thought it worth sharing.
LinkedIn uses OAuth2.0 protocol for authorization when our application tries to access the data.


LinkedIn provides 2 ways to access its data

  1. REST API
  2. JavaScript API

I used the REST API to make calls for accessing data.

The steps involved in using LinkedIn API in our grails application are as:-


#1. Register Application :

Register an application on LinkedIn here and get an API key.
This process will generate application and provide API Key & Secret Key for getting access token for API calls.


#2. Get Access Token :

With the help of API key and API secret generated in the above step, we need to get access token for calls. There are various wrapper libraries available to get the access token.


The Java wrapper which i used can be downloaded from here.


Steps involved in getting access token are same for any social media using Oauth 2.0 protocol.
#. A request token is sent to the server to get a URL for the user to give back a verification code.
#. The verification code and the request token are used in another request to get an access token.
Once we have that access token we can then use it to get data from the LinkedIn.


Code to get verification_code is as :


def registerOnLinkedIn = {

  String apiKey = API_KEY obtained from registered LinkedIn Application
 String apiSecret = API_SECRET obtained from registered LinkedIn Application
 String callbackurl = http://www.example.com/myapp/linkedInCallback
                              // callback URL to get the access token

  LinkedInOAuthService oauthService = LinkedInOAuthServiceFactory.getInstance()
                                         .createLinkedInOAuthService(apiKey, apiSecret)
  LinkedInRequestToken  linkedInRequestToken=  oauthService.getOAuthRequestToken(callbackurl);
  String  authUrl = linkedInRequestToken.getAuthorizationUrl()
  session['REQUEST_TOKEN'] = linkedInRequestToken
  // set linkedRequest token in session, as we will be requiring it to get access token
  redirect(url: authUrl)

 }       

This will redirect user to linkedIn server to grant permissions for this application and provides an verification code to obtain access token

As the user grants permission, the linkedin will redirect it back to the application with verification code, which is used to retrieve access_token.


Code to handle callback, where linkedIn sends verification code.



def linkedInCallBack = {
        LinkedInOAuthService oauthService = LinkedInOAuthServiceFactory.getInstance()
                                                 .createLinkedInOAuthService(apiKey, apiSecret)
        LinkedInRequestToken requestToken = (LinkedInRequestToken) session['REQUEST_TOKEN']
        List<String> ouathVerifier = params.list("oauth_verifier")
        LinkedInAccessToken linkedInAccessToken = oauthService.getOAuthAccessToken(requestToken, ouathVerifier[0])
        String accessToken = linkedInAccessToken.token
                                         // required access token for API calls.
   }

This will generate access token for API calls.


This worked for me.
Hope it helps.

Useful Links:
https://developer.linkedin.com/documents/quick-start-guide
http://code.google.com/p/linkedin-j/


Cheers!!!
Vishal Sahu
vishal@intelligrape.com
http://www.intelligrape.com

  • Share/Bookmark
Posted under Grails, Groovy

Grails 2.0 action arguments data binding

Posted by Uday Pratap Singh on February 20th, 2012

One feature that I really like in Grails 2.0 is action arguments databinding. While reading more about it I also found a nice grails.web.RequestParameter annotation. When you know something you always find its use case. In my recent project I need to take radius and height as params for creating a cylinder so my action looks like

def save(float radius, float cylinder){
....
}

but now I have changed my action as

def save(@RequestParameter('r')float radius, @RequestParameter('h')float height){
....
}

Now radius will initialize with params.r and height will initialize with params.h. It made my urls short and my code more readable.
I believe that the real benefit of this annotation would be in a scenario where an external API returns some result whose fields are not that intuitive.
However I have a wish here, that if we could use this annotation on command object fields as well then it will be more useful.

Hope it helps


## Uday Pratap Singh ##
uday@intelligrape.com
http://www.IntelliGrape.com/
http://in.linkedin.com/in/meudaypratap

  • Share/Bookmark
Posted under Design Pattern, Grails

Using aliases in aggregate functions of criteria queries

Posted by puneet on February 13th, 2012

When using criteria queries, many times we encounter a use case where we need to order our result not on any field of domain class but on our result set, in these cases aliases can be used.


In my project, use case was to find most liked products from the domain:

ProductStat{
Date dateCreated
Product product
}

To find the result, the query I used was :

ProductStat.createCriteria().list() {
            projections {
                groupProperty("product")
                count("product", "totalProducts")  // alias totalProducts
            }
            order("totalProducts", "desc")
}

In this way using alias “totalProducts” I was able to order the result according to the count of products.


  • Share/Bookmark
Posted under Grails