Groovy « Intelligrape Groovy & Grails Blogs

Archive for the ‘ Groovy ’ Category

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

Image comparison

Saturday, August 14th, 2010
Posted by anshul

In one of our projects, we need to compare images which comes from various sources and remove the duplicate one.

The below algo helps us to remove the duplicate images.

 boolean compareImage(String firstPhotoUrl, String secondPhotoUrl) {
        boolean result = true;
        BufferedImage bi1 = ImageIO.read(new URL(firstPhotoUrl))
        BufferedImage bi2 = ImageIO.read(new URL(secondPhotoUrl))
        int size1 = bi1.getData().getDataBuffer().size;
        int size2 = bi2.getData().getDataBuffer().size;
        if ((size1 == size2) && (bi1.width == bi2.width) && (bi1.height == bi2.height)) {
            Raster r1 = bi1.getData();
            Raster r2 = bi2.getData();
            DataBuffer db1 = r1.getDataBuffer();
            DataBuffer db2 = r2.getDataBuffer();
            int size = db1.getSize();
            for (int i = 0; i < size; i++) {
                int px1 = db1.getElem(i);
                int px2 = db2.getElem(i);
                if (px1 != px2) {
                    result = false;
                    break;
                }
            }
        } else {
            result = false;
        }
    }
    return result;
}

Hope this helped!

Cheers!
Anshul Sharma

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

Creating select tag with optgroup in Grails

Tuesday, August 10th, 2010
Posted by Vishal Sahu

Hi,
In one of my projects i needed to create a select-input tag with OPTGROUP options.
I searched a lot about it and found that g:select tag do not support OPTGROUP

So to solve this problem, i created a simple optgroup tag using Html and grails taglib.

I created a Map for the values to be used in the select tag and pass it to the test.gsp page from the controller.
Say Map dataMap=["Car":["Car A","Car B","Car C"],”Truck”:["Truck A","Truck B"]]

I put the tag in test.gsp where i want to display the select dropdown

 
         <test:optGroup name = "data" dataMap="${dataMap}" />

In my TestTaglib.groovy, i defined the tag as

 
class TestTagLib {
    static namespace = 'test'
 
    def optGroup = {attrs ->
        Map dataMap = attrs['dataMap']
        out << g.render(template: 'layouts/optSelect', model: [dataMap:dataMap])
    }
}

I created a template “_optSelect.gsp” under the layouts folder

 
<select name="mainList">
    <optgroup label="--"><option value="">(Select One)</option></optgroup>
    <g:each in="${dataMap}" var="data">
        <optgroup label="${data.key}">
            <g:each in="${data.value}" var="value">
                <option value="${value}">${value}</option>
            </g:each>
        </optgroup>
    </g:each>
</select>

This generated the required SELECT dropdown with OPTGROUP and solved the problem.

Hope it helps.

Regards:-

Vishal Sahu
vishal@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 Transactions using @Transactional annotations and Propagation.REQUIRES_NEW

Friday, July 30th, 2010
Posted by Abhishek Tejpaul

Hi All,

Here is how you can implement a new transaction in an already executing transaction in Grails which uses nothing but Spring framework’s Transaction mechanism as an underlying implementation. Spring provides @Transactional annotations to provide declarative transactions. We can use the same in our Grails project to achieve the transactional behavior.

Here is the scenario: You have two domain classes named SecuredAccount and AccountCreationAttempt. You try to transactionally save the SecuredAccount object which in turn creates a AccountCreationAttempt object which writes to the database stating: “There is an attempt to create a new SecuredAccount at this time: <current date and time>”. Point to note here is that even if the creation of the new SecuredAccount object fails, the record must still be written to the database so that the Administrator can validate whether the attempt at the specific time was by a legitimate user or an attacker.

Here is the code:

import org.springframework.transaction.annotation.*
Class MyService {
 
static transactional = false
def anotherService
 
@Transactional
def createSecuredAccount() {
def securedAccount = new SecuredAccount(userId:"John")
securedAccount.save(flush:true)
anotherService.createAccountCreationAttempt()
throw new RuntimeException("Error thrown in createSecuredAccount()")
}
}
import org.springframework.transaction.annotation.*
class AnotherService {
 
static transactional = false
 
@Transactional(propagation = Propagation.REQUIRES_NEW)
def createAccountCreationAttempt() {
def accountCreationAttempt = new AccountCreationAttempt(logRemarks: "There is an attempt to create a new SecuredAccount at this time: {new Date()}")
accountCreationAttempt.save(flush:true)
}
}

Now in this scenario, AccountCreationAttempt object always gets persisted whether or not the transaction for creating SecuredAccount object fails.

Here are few gotchas regarding the above transactions:

1.) First of all, for Propagation.REQUIRES_NEW to work as intended, it has to be inside a new object i.e. a new service in our example. If we had put the createAccountCreationAttempt() method in the MyService there would be no new transaction spawned and even no log entry would be made. This is Spring’s proxy object implementation of transactions and you can read more about it here:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/transaction.html#transaction-declarative-annotations.

Please pay special attention to the “NOTE” sub-section.This is what it states:

“In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional.”

2.) Secondly, all the @Transactional methods should have a public visibility i.e. createSecuredAccount() and createAccountCreationAttempt() methods should be public methods, and not private or protected. This again is Spring’s @Transactional annotations implementation and you can read about it at the same link as provided above. Note the right side-bar titled “Method visibility and @Transactional“.

Well, once you keep note of these gotchas I guess you are all set to make good use of @Transactional annotations and its full power.

Cheers !!!

- Abhishek Tejpaul
abhishek@intelligrape.com
[IntelliGrape Software Pvt. Ltd.]

  • Share/Bookmark
Posted in Database, Grails, Groovy

Tips for Agile Development with Unit Testing approach.

Wednesday, July 14th, 2010
Posted by salil

This is more towards the best practices and my experiences for developing an application at a faster rate.

In my current project, we are using many different APIs (for external services). And usually it takes time to explore, implement and then stabilize the application. Also, it’s not over once you stabilize your APIs based code. Because there are possibilities to have unexpected results such as server side errors, broken request, broken response, etc. Also you never know when Service provider makes some changes and your code breaks.

Well, here are some tips which really helped me to achieve faster implementation and more stable application (esp. when working with third party APIs).

TRY TO MAKE YOUR CODE UNIT TESTABLE as much as possible.

1. Create Service layer for API based implementation. Keep this service layer independent from other application. So that you should run it without any other dependency.

2. Try to make small chunks of code (in form of methods) with least dependency on external things.
Avoid Domain/Database/Environment specific code. In other words, don’t put any kind of framework specific dependency. In some cases you can’t avoid. But try to avoid as much as possible. Because it could lead to integration testing and which again takes more time. Unit test is the fastest way to check your code stability.

3. In case you have some dependencies (and that can not be avoided) – Try to mock it up. In many cases it’s possible. If you are using Grails/Groovy kind of framework/language – you have an edge to take an advantage of meta-programming.

4. There is no specific way to do this. But it comes with practice. You can follow above tips to implement your Service Layer Code. And then create unit tests – invoke your API based service methods. And run it. Wow.. that’s it.

Advantages:
If there’s any kind of changes (from service provider), that can break your application’s functionality, test driven development will work as a “Life Saver”. It can tell you where’s the problem and why it happened. And you can make appropriate changes to stabilize it again.

Same thing implements when you develop a new feature. Unit Test Case helps you see the results in few seconds. Instead of waiting for 10-15 minutes (until application starts).

Isn’t it cool?

I really appreciate this approach. Hope others will also use it.

Thanks
Salil Kalia

  • Share/Bookmark
Posted in Grails, Groovy, Test, Unit Test

Grails unit testing for beginners

Wednesday, July 14th, 2010
Posted by Imran Mir

Ques: How is unit testing different from integration testing ?

Ans: Integration tests need to bring up the whole grails environment.They talk to the database. All the dynamic GORM methods and properties are available here. Unit testing are small focused, fast loading tests that do not load supporting components.

Ques: How can I unit test a method in a service ?

Ans: You would need to follow these simple steps:

Suppose you want to write a unit test case for a someFunction() in MyService:

class MyService {
    public String myFunction() {
      return "testString"
    }
  }

-> Create Unit Test File : grails create-unit-test com.intelligrape.xxx.MyService. It will create the test file in the folder /test/unit
-> Write a testcase function
-> Create an object of MyService
-> Call the function and make assertions

public void testMyFunction() {
    def myService = new MyService()
    String string = myService.myFunction()
    assertEquals "testString", string
  }

Ques: I am saving an object from this function. How can I test that ?

 public void myFunction(int number, String name) {
    MyDomainClass object = new MyDomainClass(age: number, name: name)
    object.save()
  }

Ans: Its pretty simple. You would first need to mock the domain class whose object is being saved.

   def instances = []
   def myTestDomain = mockDomain('MyDomainClass',instances)

instances will serve as a cache of objects. Right now it contains no object. But when you call the save method from the function to be tested, it will automatically put that object in this cache. So, we can make assertions against this cache. Just to remind you, no database communication occurs during the unit testing.

 public void testMyFunction() {
    def instances = []
    def myTestDomain = mockDomain('MyDomainClass', instances)
    def myService = new MyService()
    String string = myService.myFunction(30, 'myName')
    assertEquals 1, instances.size()
  }

Ques: What does this mockDomain do ?

Ans: mockDomain is a method of GrailsUnitTestCase, that helps to mock a domain class. mockDomain also mocks most of the injected methods of the domain class like, save(), validate(),delete(),get() and many others. But there are many methods it does not mock,e.g., createCriteria,find,findAll,withTransaction and many others.

Ques: That was great. But now my function uses some other service to do some job. How can I test that ?

  public void myFunction(String empId) {
    String name = otherService.someOtherFunction(empId)
    MyDomainClass object = new MyDomainClass(name: name)
    object.save()
  }

Ans: In this case you would need to mock both, other service as well as the method which is called.

void testMyFunction() {
    def otherService = mockFor(OtherService)
    otherService.demand.someOtherFunction() {empId-&gt; return "testName"}
    def myService = new MyService()
    myService.otherService = otherService.createMock()
    String string = myService.myFunction(30, 'myName')
    assertEquals 1, instances.size()
}

Ques: What does this mockFor method do ?

Ans: It is a method that is used to mock a dependency. We can mock services and its methods with the help of this. The demand method of the object returned by the method can be used to mock different methods of the mockedInstance. We can also specify the number of times the function is actually called in the function.

 otherService.demand.someOtherFunction(1..2) {empId; return "testName"}

Here, it means someOtherFunction() will be called not more than 2 times in the function.

Hope this helps.
Imran Mir
imran@intelligrape.com

  • Share/Bookmark
Posted in Grails, Groovy, Test, Unit Test

Merge two PDF files

Monday, July 12th, 2010

In my current project the user has the option to add pdf file into the system. Recently we got the requirement to add a cover page to each pdf document that user downloads. We were already using the iText API for generating pdf so the task to do that was easy. After going through the documentation of iText I found a way to merge two pdf files.

try{
            PdfReader pdfReader1 = new PdfReader("firstFile.pdf");
            PdfReader pdfReader2 = new PdfReader("secondFile.pdf");
            PdfCopyFields finalCopy = new PdfCopyFields(new FileOutputStream("finalCopy.pdf"));
            finalCopy.open();
            [pdfReader1,pdfReader2].each {PdfReader pdfReader ->
                   finalCopy.addDocument(pdfReader);
            }
            finalCopy.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

I hope it helped you :)

## Uday Pratap Singh ##
uday@intelligrape.com

http://www.IntelliGrape.com/
http://in.linkedin.com/in/meudaypratap

  • Share/Bookmark
Posted in Groovy, Java tools

Suppress Tracking of various scripts on test and development environment

Sunday, July 11th, 2010
Posted by Tarun Pareek

In my recent project, every time the page loads, it loads with lots of scripts making calls to and getting content from googleapis, fb, clixpy, cdn etc. to provide the functionality, due to which the page loads very slowly and this led to the wastage of time to test a certain functionality.

To overcome this problem in test and development environment and at the same time to run those script in the production environment, I added the “suppressTracker” tag that enable or disable the script on the basis of environment on which it is executing or on the basis of session set for tracker.

Step 1 : Create the suppressTracker tag in your tagLib,

import grails.util.Environment;
 
def suppressTracking = {attrs, body ->
        if (Environment.currentEnvironment==Environment.PRODUCTION && !session.suppressTracking){
            out<< body()
        }
}

Step 2 : Add suppressTracker tag on the script which you want to suppress for test and development environment,

<util:suppressTracking>
  <script type="text/javascript">
       Your Script Code ..........
  </script>
</util:suppressTracking>

Hope this code will help :)

~Regards,
Tarun
Intelligrape Software

http://in.linkedin.com/in/tarunpareek

  • Share/Bookmark

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