Intelligrape Groovy & Grails Blogs

get totalCount of records when using limit in one Query

Posted by Shaurav on May 17th, 2012

For pagination we generally execute two query ,first for geting resultset by using limit in sql query and second to count the total no. of records . For total no. of records we again execute the same query with count(*).

You would need two queries like these:

SELECT COUNT(*) FROM author WHERE name LIKE 'a%';

SELECT name, email FROM author WHERE name LIKE 'a%' LIMIT 10;

But if you have a complex query that joins several tables and takes a while to execute – well, you probably wouldn’t want to execute it twice and waste server resources.

Since MYSQL 4.0 we can use SQL_CALC_FOUND_ROWS option in  query which will tell MySQL to count total number of rows disregarding LIMIT clause. In main query add SQL_CALC_FOUND_ROWS option just after SELECT and in second query  use FOUND_ROWS() function to get total number of rows without executing the query.

Queries would look like this:

SELECT SQL_CALC_FOUND_ROWS name, email FROM author WHERE name LIKE 'a%' LIMIT 10;

SELECT FOUND_ROWS();

Limitation: Must call second query immediately after the first one(or before next one) because SQL_CALC_FOUND_ROWS does not save number of rows anywhere.In the absence of the SQL_CALC_FOUND_ROWS option in the most recent successful SELECT statement, FOUND_ROWS() returns the number of rows in the result set returned by that statement.
Read the rest of this entry »

  • Share/Bookmark
Posted under Database

Overriding properties in a Spring Bean with BeanFactoryPostProcessor

Posted by Vivek Krishna on May 12th, 2012

I was going through the source code of one of the Grails Plugins where I found the use of Spring’s BeanDefinitionRegistryPostProcessor to override some configurations that are available in DataSource.groovy. That involved a complete over riding of a PropertyValue definition.

 

It set me thinking about whether there is a way to override bean properties like String, Integer etc in a simpler way after the bean has initialized. In comes BeanFactoryPostProcessor, which provides a wonderful hook to do just that.

 

I created a small grails project and added a class CustomBean which looked like this :


class CustomBean {
       String customVariable
}

I registered a customBean on resources.groovy using

beans = {
    customBean(CustomBean) {
        String value = "Test Data From resources.groovy"
        println "Setting value ${value}"
        customVariable = value
    }

    customBeanPostProcessor(CustomBeanPostprocessor)
}

This sets the initial value of customVariable as “Test Data From resources.groovy”.

If you are wondering what the customBeanPostprocessor is, that is just what I am going to explain next.
The bean implements the BeanFactoryPostProcessor interface and overrides the methods which provides us with hooks to modify the properties of the bean.

 

The class definition is:

import groovy.util.logging.Log4j
import org.springframework.beans.factory.config.BeanPostProcessor

@Log4j
class CustomBeanPostprocessor implements BeanPostProcessor{

    @Override
    Object postProcessBeforeInitialization(Object bean, String beanName) {
        return bean
    }

    @Override
    Object postProcessAfterInitialization(Object bean, String beanName) {
        if(beanName == 'customBean') {
            log.debug("Setting custom value inside post processor")
            bean.customVariable = "Set from Post Processor"
        }
        return bean
    }
}

What amazed me is the elegance with which the developers of the framework has provided entry points into its internals without forcing the users to shave the yak.

 

  • Share/Bookmark
Posted under Grails, Spring

Change user preferred locale using spring’s SessionLocaleResolver

Posted by Nitesh on May 11th, 2012

Here we are going to talk about a scenario where there are some records in database which are specific to locale and they need to be displayed as per user’s current locale at number of places.Also user can change its preferred locale.

For this I preferred to set the user’s locale in the session object. There are two ways to do this :-

1. Add attribute “lang” to the request and it will be available to session automatically.

For example: whenever user clicks on the link, the language will change to English and the user will remain on the same page.


<g:link controller="${params.controller}" action="${params.action}" params="${params+[lang:'en']}">English</g:link>
/*Add different languages here*/

2.Also set default locale in the session in case, it is not set.

For that add following to any Filters :-


if (!session.'org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE') {
LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
localeResolver.setLocale(request, response, new Locale('en'));

}

This sets the locale in spring’s SessionLocaleResolver class. Session always refer for the locale from here only.

Now one can check the locale wherever session is available. For example in GSPs:


<g:if test="${session.'org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE'.toString()=='en'}">

Note: This implementation is useful to set locale in session (for accessing many times). Otherwise locale is available directly from current request as given below:-

import org.springframework.web.servlet.support.RequestContextUtils as RCU
Locale locale=RCU.getLocale(request)

Hope this helped!
Nitesh Goel
[Intelligrape Software Pvt. Ltd.]

RequestContextUtils
  • Share/Bookmark
Posted under Grails

Fetching File From FTP in Background With Curl.

Posted by Hitesh Bhatia on May 9th, 2012

Last night I had to restore file with size greater than 220GB from our backup FTP server to our main server after OS re installation.

Now I could have simply done “get” after logging into ftp out server, but that would have required my machine to stay awake all night unattended. Seems simple but everything I tried didn’t seem to work .

In comes curl, literally saved my night. With simple command written below I was able to transfer file from ftp server to local machine.

 curl ftp://name:password@server/file.tar > file.tar

And then it was piece of cake running it in background with nohup

nohup curl ftp://name:password@server/file.tar > file.tar &

Thanks to curl, me and my system were able to get good nights sleep :)

_________________________________
Hitesh Bhatia
Mail LinkedIn,Facebook,Twitter
_________________________________
  • Share/Bookmark
Tags: , , ,
Posted under System

Restricting Access To Plugin’s Classes With Spring Security

Posted by Hitesh Bhatia on May 3rd, 2012

Many of Grails plugin like searchable  and console can prove to be really dangerous if access to their URLs is not blocked. After adding searchable plugin to my project, I realized that access to its controllers was not defined and was open for all. Now this was a major security concern. There are many ways of restricting access like doing it manually in filters. But since I am using spring security plugin, there was a better way out. It allows to create mapping (static rules) as configuration for different user roles.

There are different ways of securing url in spring security plugin. And since I am using annotations, I’ll be defining static rule for annotations only.


grails.plugins.springsecurity.controllerAnnotations.staticRules = [

'/console/**': ['ROLE_ADMIN'],

'/searchable/**': ['ROLE_ADMIN']

]

By doing this I blocked access for all but ones with the role “ROLE_ADMIN”  for console and searchable controllers.

_________________________________
Hitesh Bhatia
Mail,LinkedIn,Facebook,Twitter
_________________________________
  • Share/Bookmark
Posted under Grails

Multiple Bootable OS in Single USB

Posted by Hitesh Bhatia on April 19th, 2012

Recently I have been knee deep into Linux installations. Installing through  USB is great process, there is no hassle of CD and its faster too. But problem is first we need bootable USB. Up till now I used “Start Disk Creator”, which is bundled in Ubuntu and is great for creating bootable USB, major problem with it is that it creates single boot USB, that is If I have bootable USB for Ubuntu 11.04, it will be erased when I create a bootable stick for Ubuntu 11.10.

This was a problem for me, and I found a solution to this problem in Multisystem, which creates a single bootable USB for multiple OS.
Here are steps to install And Use Multisystem
1) Download From PenDriveLinux.com, Extract the package .. change the permission of extracted file “install-depot-multisystem.sh” to make it executable.

2) Execute this file and it’ll download some files, and complete its installation. After Its Done, lets move to actually creating Pen Drive with multiple bootable OS.

3) Run Multisystem and it’ll ask you to confirm any USB drive if inserted. Once confirmed it  should look as following images, but there would be no OS pre configured. (it shows some as I configured them, it also tells me that I have  4live CDs already configured.)
MultisystemMultisystem Home Screen
4) Click on icon at bottom in middle (Which has “Select .iso or .img “written on top of it). And Select  image file of OS for which bootable USB need to be created. It’ll again ask for password and within  less than a minute bootable will be ready.

5)Same process (step 4) can be repeated to add multiple OS to bootable USB stick.

6) It also lets you test how bootable stick will work.Just Click on “Q” button and see the magic. Below are the images of me testing ArchBang from my bootable USB.
Multisystem Boot
Archbang 1
Archbang 2

  • Share/Bookmark
Posted under Linux, System

Handling corrupted references through ignoreNotFound database mapping in Grails

Posted by Tarun Pareek on April 17th, 2012

Hi,
 
Recently i had a use-case where we have the legacy database and it contains the corrupted references of a non existent record in many-to-one relationship, and i have to populate a grid that contain info also from referenced record. As referenced record doesn’t exist, So when we refer to the certain record will result in Hibernate throwing exception :

org.hibernate.ObjectNotFoundException

and not a single record loaded on grid.
 
As it is legacy database i am not sure what should be the correct value for the particular record.
 
After few searches, i come accross a property in grails database mapping to handle such cases, let see how it work :

class Task{
   String name
   ParentTask parent

   static mapping = {
       parent ignoreNotFound: true
   }
}

class ParentTask{
   String name
}

Basically, ignoreNotFound simply mapping hibernate not-found property.
 
Note : A record loaded with ignoreNotFound: true will throw an exception during call of save() because of the missing reference.
 
Either you can first update the invalid property or corrupted reference to the correct reference and then update other property that will solve your problem. It depend how you handle such scenario on your usecase.
 
Thanks,
Tarun Pareek
tarun@intelligrape.com
http://in.linkedin.com/in/tarunpareek
More Blogs by Me
 

  • Share/Bookmark
Posted under Database, Grails

Integrating Grails with Weceem

Posted by manoj on April 16th, 2012

Today, I’ll be talking on how to go about integrating the Weceem CMS into a grails-app. It is extremely simple and with a couple of steps you would have a CMS that can render traditional as well as custom content merged into your grails application.

Ok … First things first … What is Weceem ?

Weceem (as in ‘We seem’ to like it :D ) is a Content Management System developed by Marc Palmer for JCatalog that is built on Grails. It is open source and easy to use.  Apart from being customizable, the other thing that I liked about it was the ability to create custom content, and that too using grails conventions!!.

While it supports traditional content like Blogs, Wiki articles etc, one had the flexibility and support of creating a custom content that might be more in line with the hosting grails app. Add to that the ease of a grails plugin that makes it’s integration with an existing grails app a breeze.

Getting back to Installation …..

To install weceem simply type

grails install-plugin weceem

While installing, it will pull a whole lotta stuff as it’s dependencies (searchable, blueprint , ckeditor etc).

Next to see the plugin’s CMS page, one needs to configure a couple of properties.

1)   In your Config.groovy change the follwing line to false ….

grails.mime.file.extensions = false //set to true by default

2)  Next if you need content to be served from the root URI (‘/’) of your application, simply remove the default grails URL mapping for ‘/’ URLMappings.groovy.i.e doing this will cause the app home page to change to the CMS home page.

Thats all you need to have Weceem up and running.

Simply hit ‘grails run-app’ and depending on your implementation of Step 2 above either hit ‘/’ or ‘wcmContent/show’ and VOILA!!!, you end up on the landing page of the CMS. Click on the ‘edit content repository’ link to go to the Content Repository that looks something like the image below…

Weceem CMS landing page

Weceem CMS landing page

You have a grails powered CMS integrated into your app in matter of minutes. Click on the new content link button, and you are presented with a range of content options … from HTML to Blogs to Wiki pages and so on.

Great … Lets create some content …

First select existing Blog folder in the CMS dashboard  and then click on  the ‘New Content’ -> Blog Entry ..

Add some content …

Thats it … All you gotta do now is hit save.

Now to view our content … Go to the blogs page of your app (URI for page is defined in ‘Alias uri’ section of Blogs folder-edit page.. Default is ‘blog’) or “http://<serverURL>/blog”

Tip : To serve all content through a specific URI prefix .. just add

weceem.content.prefix = 'content' // replace 'content' with anything you prefer ... 

to make your blogs page and all other repository content be served from  http://<serverURL>/content/<blog_or_anything_else>

In the next blog, I’ll talk how to go about creating your own custom content ..

Till then … peace out .. :)

Manoj Mohan
manoj(at)intelligrape(dot)com
  • Share/Bookmark
Posted under CMS, Grails, Groovy

Clear Time function for MySQL

Posted by Gaurav Sharma on April 12th, 2012

Hi all,

Here is a simple function that can allow you to clear time from the DATETIME field of your database table

DROP FUNCTION IF EXISTS cleartime;
delimiter //
CREATE FUNCTION cleartime(dt datetime) RETURNS DATETIME
  NO SQL
  DETERMINISTIC
BEGIN
  DECLARE t    varchar(15);               -- the time part of the dt
  DECLARE rdt  datetime default dt;    	  -- the datetime after time part is cleared

  SET t = TIME(dt);
  SET rdt = SUBTIME(dt,t);

  RETURN rdt;
END //
delimiter ;

To import this function to your database just copy and paste above code in MySQL command prompt with your database selected.

The implementation is shown in following example:

select cleartime(datetime_field) from table_name;     -- to view field with its time cleared
                     --OR
update table_name set datetime_field=cleartime(datetime_feild) from table_name;
  • Share/Bookmark
Posted under Database

Dealing with immutable collections in Java

Posted by Salil on April 11th, 2012

Perhaps, you know it before or just skipped it after going through Java API. But I really found it very helpful at this point.

 

Recently, I had a requirement in an open-source project, where users can iterate through the objects saved in collections (esp. List). But the problem was, we really didn’t want users to directly or indirectly update those collection objects. Or in other words, we wanted to provide them collections with Read-Only behavior.

 

So to fulfill this requirement, I had few solutions -
1) Writing a wrapper class for iterating the objects in collection, in a manner that it behaves like Immutable collection objects.
2) Implementing your own Collection classes to support read-only behavior.
3) Returning the output as Iterable.
4) And many more – as complicated as we want to make it.

 

Well, need not to worry guys!
Java provides an in-built class “java.util.Collections – to deal with such kind of problems.

Collections class comes up with a good list of static methods. Like, for converting a modifiable list to unmodifiable list (read-only list), we have following method:

List myUnmodifiableList = Collections.unmodifiableList(myModifiableList)

and now, if anyone will try to modify ‘myUnmodifiableList’, it will throw UnsupportedOperationException.
Similarly, there are other methods to handle different types of collections.

 

I hope this might help someone.

 

Please put your comment, if there’s any better way out there.

 

Cheers!
Salil Kalia
Salil [at] IntelliGrape [dot] com
Twitter LinkedIn

  • Share/Bookmark
Posted under Grails, Groovy