Java tools « Intelligrape Groovy & Grails Blogs

Archive for the ‘ Java tools ’ Category

GORM goodies read, discard, refresh

Tuesday, September 7th, 2010

Grails docs are the best source to understand how to make best use of GORM methods and now the GORM Gotcha’s series By Peter Ledbrook is also making the docs easy to understand.
So many time it happens when the domain instance values gets updated without calling save method.It happens because the object is attached to hibernate session, to change this behavior we can use the method like read instead of get/load.
What read actually do is

Person person = Person.read(1)
println "Output -: ${person?.firstname}"  // Output -: Uday
person.firstname="Uday1"
println "Output -: ${person?.firstname}" // Output -: Uday1

The value is changed but it is not stored in the database. But the changes can be saved into the database if you explicitly call save().

The other approach could be removing the object from hibernate session, so that the changes made to the database do not get persisted to the database

Person person = Person.get(1)
println "Output -: ${person?.firstname}"  // Output -: Uday
person.firstname = "Uday1"
println "Output -: ${person?.firstname}" // Output -: Uday1
person.discard()
println "Output -: ${person?.firstname}"  // Output -: Uday1

In above example, none of the change made to the object do not get persisted to the database . Again it will save the changes if you explicitly call save().

One more good method is refresh() which is used to load the object again from the database, so all the changes made to object will be reverted. Though it is not advisable but sometimes if you want to get the object to its original stage you can do it by refresh.

Person person = Person.get(1)
println "Output -: ${person?.firstname}" // Output -: Uday
person.firstname = "Uday1"
println "Output -: ${person?.firstname}" // Output -: Uday1
person.refresh()
println "Output -: ${person?.firstname}" // Output -: Uday

These are the few goodies which are available with the GORM and we can use according to our use case :) .

Hope it helps

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

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

  • Share/Bookmark
Posted in Grails, Java tools

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

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

Creating Paged Media with Different Paged Modes Using CSS3

Friday, July 30th, 2010
Posted by Vivek Krishna

In one of our projects, we had to create PDF documents from HTML. The iText renderer was an excellent solution to do that. However, the tricky part was that the cover page had to be of portrait orientation and the rest of the document, of landscape orientation. After doing a fair share of searching on the web, I came across the Documentation for CSS3 Paged Media.

This could be achieved by creating an @page rule with a page name and then, using the page name in the element, which was going to enclose the body, for which we needed a particular style.

For example, since I needed the landscape mode on the inner pages, I had to create a @page rule in the CSS file as

@page content{
           size: A4 landscape;
}

And a css selector,(say a div, which was going to enclose such pages)

div .content{
          page: content;
}

If the HTML was something like,

<content in portrait mode>
<div class=”content”>
My contents here
</div>
<content in portrait mode>

“My contents here” would appear in a landscaped page.

Hope this helps

Vivek
vivek[at]IntelliGrape.com

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

  • Share/Bookmark
Posted in HTML-UI-CSS, Java tools

Generating stubs for SOAP calls using IntelliJ IDEA

Tuesday, July 13th, 2010
Posted by Sachin

Since working with SOAP calls in XML is very tiresome, we have libraries like axis and wsdl2java to generate stubs to make web-service client calls. I generated the stubs using IntelliJ IDEA to make SOAP calls in grails using the steps below.

1. Adding Framework Support

If the IntelliJ project does not already have the framework support, then add it by right clicking on the “ProjectName” project and selecting the “Add Framework Support”. Go to Web services client in left pane and select Apache Axis in the right pane. Also, specify the path where you want necessary files to be downloaded. It will prompt you to download files. Just click “Yes”.

2. Generate Java code from WSDL

Right click the project’s src/java directory, and select “Webservices >> Generate Java code from WSDL”. Now point to the URL and ensure that the “output path” points to “src/java” .

Using the generated stub, we should now be able to invoke web service calls by importing in the necessary classes where ever we want to use them.

No more haggling with XML.. cheers…!!!

~~With Regards~~

~~Sachin Anand~~

~~sachin@intelligrape.com~~

  • Share/Bookmark
Tags: , ,
Posted in Java tools

Grails Hibernate Filter Plugin a Life Saver

Tuesday, July 13th, 2010

The project I am currently working on is also accessible from the iPhone. In the last few months so many changes have been done on the web application (developed in groovy/grails). Now the client wants the same thing on iPhone as well. He has a separate development team for iPhone application. The iPhone application developer wanted to have soft delete mechanism for deleting an object. So they added new field in the database table named “deleted”.

Now we have to remove all such records from our every query in the project which have deleted true. So there were 6-7 domains which now have this mechanism of soft deletion.

That’s how our life became hell, we were unsure about what to do next, is it good to modify all the queries in the project which would be a lot of work.

I was also reading Hibernate books these days and found a very good thing in Hibernate about filters. So now I just need to look for how the filters work in Grails. In few seconds I found my “life saver” plugin for Grails i.e. http://www.grails.org/plugin/hibernate-filter. Everything is written in the plugin documentation but I would like to re-quote some of the documentation

My class was like

Class A{
String name
String address
Boolean deleted
}

After installing the plugin I just need to add a line in the domain and a property in datasource file and it will filter all the data with the condition that I put in filter. So my domain would become like this.

Class A{
String name
String address
Boolean deleted
} 
 
static hibernateFilters = {
        enabledFilter(condition: 'deleted=0', default: true)
    }

in Datasource.groovy file I need to write

import  org.grails.plugin.hibernate.filter.HibernateFilterDomainConfiguration
dataSource {
   …
   configClass = HibernateFilterDomainConfiguration.class
}

and I am done without looking at how many places I have used dynamic finders or queried the database for this domain.

I haven’t gone into the details of the plugin but it really saved a lot of work for me.

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

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

  • Share/Bookmark
Posted in Grails, Java tools

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

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

Jasper report – Pattern for Negative Numbers

Monday, May 3rd, 2010
Posted by Hitesh Bhatia

Recently had a requirement to print Currency values with a condition that negative numbers must be inside brackets.

It can be done by using pattern property in tag.

<textField pattern="#,#0;(#,##0)" >

the part before semicolon is for positive numbers and part following semicolon is for negative number.

____________________
Hitesh
hitesh@intelligrape.com
Intelligrape Software
____________________

  • Share/Bookmark
Posted in Java tools