A simple grails custom validator 3

While writing a simple CRUD with #grails, client asked me to validate pogo’s birth date (had to be in the last year). In this cases, we can’t just use regular validators, cause their are static. So we can solve this using our own custom validators, so simple and useful.

static constraints = {
	//...
	borned(validator: {
		return (it > new Date()-365)
	})
	//...
}

That’s it, this way every time a new instance is validated (during save or manually), a new date will be created and compared to it. (no I don’t care about leap years).

Already following me on twitter?

[]s,

Defining load order and dependencies to your grails plugins 0

Hello all,

I’m buiding a simple Grails Plugin that will use GORM dynamic finders and methods, but as we should know, the create-plugin grails command just install a fresh skeleton of your grails application, without any other dependencies.

First of all, you shoud install the hibernate plugin inside your plugin. Don’t worry, the hibernate will not be packaged with your plugin, but will be there to your plugin classes use.

grails install-plugin hibernate

So, now your plugin have the hibernate plugin installed and will be capable to use GORM facilities. But, if people wants to use your plugin, they will have to have hibernate plugin installed, correct? I know it cames by default in our grails application, but can be uninstalled. So we have to find some way to make our plugin dependent on hibernate plugin. Asking on the grails-user list and reading this topic in grails.org wiki, I remembered on two plugin configurations that can help us:

  • dependsOn
  • loadAfter

The dependsOn it’s a map inside our XptoGrailsPlugin that tells witch plugins our one depends, it takes the name of the respective plugin and its version, in my case, that’s what I did:

def dependsOn = ["hibernate":"1.1 > *"]

So, our plugin will depend on grails hibernate plugin, and at least the 1.1 version of it, none previous will be accepted and any future ones will be ok!

But sometimes this is not enougth, besides being dependent, our plugin uses dynamic finders, and runtime added method on our domain classes, so, it’ll only be successfully loaded after hibernate plugin load and adds this methods. To achieve this, we’ll use the other tag, the loadAfter to tell that our plugin will wait hibernate plugin to be loaded and the load itself.

def loadAfter = ['hibernate']

That’s it. Doing this we’ll make things work as we wanted.

PS.: just noticed, right now that Graeme Rocher pushed to github’s grails master branch, a commit that will install de default plugins into new plugin projetcs too. This sounds cool, and will avoid us the first step above, the plugin installation. Here is the commit id and link: 9cb23f5b835b633cf43079ca7e58e29c64bd3b3c

Yuuuuh!!!! We got Grails 1.1.1! 0

As I said earlier, we got Grails 1.1.1 today!!

Take a look in the links below:

But watch out! People in the grails mailing list noticed some broken stuff in the build when trying to upgrade. A little workaround is availabe in this mail thread, just keep looking this Thread, probably we’ll get something here!

Thanks!!

Looking forward Grails 1.1.1 1

Hi,

Yesterday Guillaume Laforge annouced that finally groovy 1.6.3 is out. That means we’ll have the Grails 1.1.1 release in a few days (hoping this for today). Graeme Rocher said that with groovy 1.6.3 released, Grails 1.1.1 is imminent.

So let’s wait!

I’m specially waiting this release since it corrects a little bug in WAR generation using the –nojars options.
Ohhh, and of course, with Grails 1.1.1 we’ll have support to use Grails in the Google Java App Engine!!

Thanks Guillaume and Graeme!

[]s,

Esperando o Grails 1.1.1 0

Hum,

Ontem saiu oficialmente o Groovy 1.6.3, e isto quer dizer que hoje ou no máximo ainda essa semana estaremos com a release oficial do Grails 1.1.1.

Como disse o Graeme Rocher ontem no twitter, com o release do Groovy 1.6.3, o Grails 1.1.1 é iminente. :P
Estou esperando esta versão pois corrige um bug na criação de WARs usando a opção –nojars

Além de que é claro, com o Grails 1.1.1 poderemos usar o plugin do GAE para criar aplicações Grails no Google Java App Engine!!

Estamos aguardando ansiosamente.

[]s,

Working with Excel and Grails 2

I found this 2 links in grailsbrasil.com forum.
It’s a nice feature to include in your system for that situations when user have to input a large amount of data.

First example shows how user can upload the excel file, and your system automatically load all the spreadsheet data into domain objects. And this one, shows the reverse way, by loading your domain objects into an excel file using JExcelAPI.

Recommend!

[]s,

[4/25] Jasper Reports in Grails with Dynamic-Jasper 9

This tutorial will talk about producing Jasper PDF reports (or any other format you’d like) in you grails app.  I took a look in grails plugins portal I found two plugins that could be used to do this.  The Jasper Plugin and the DynamicJasper Plugin. Depending on what you really need you’ll choose one.

I see the JasperPlugin as a more customizable plugin since you’ll use it o link to an existing jasper report (.jrxml / .jasper) you have. You’ll have some work building it, modeling it and sometimes even “drawing” it, but if you really need to do your and just your jasper, I recommend this one (congratulations for the Brazilians responsible for this plugin).

Otherwise (and covered in this tutorial), if you just need a simple report for your domain classes (an poor-but-effective PDF view of your scaffold listing) like I need in one project here, the DynamicJasper Plugin is gonna let you rock!

It’s a simple, and versatile plugin that generate its output entirely dynamic. This means that you won’t need to open iReport and show us your drawing skills (as a good programmer, you may suck drawing!).

We’ll work only with the Entities Report that Dynamic Jasper offer us, if you need complex queries on the reports, I recommend you reading the “named reports” in the plugins official documentation.

Are you following me and reading my blog’s feed? Be the first to know when I publish some interesting article signing up to my feed and following me on twitter!

Tutorial Info

Groovy Version: 1.6
Grails Version: 1.1
Plugin Version: 0.5
Plugin Documentation: http://grails.org/plugin/dynamic-jasper
Download: source code

Basic setup

Well, our example this time will be a simple agenda, so, let’s create our agenda app, install the dynamic jasper plugin and then create our domain class with some constraints.

grails create-app agenda
grails install-plugin dynamic-jasper
grails create-domain-class Contact

Our initial Contact class will be this one

class Contact {
   String name
   String nickname
   Date bornAt
   String email
   String website
   String phone
   String mobilePhone
   String gender

   static constraints = {
      name(maxLength: 255)
      nickname(nullable: true)
      bornAt(nullable:true)
      email(email:true)
      website(link:true, nullable:true)
      phone()
      mobilePhone()
      gender(inList:["M","F"])
   }
}

Running the application and making it reportable

That’s it, you can run your application and test it if you want. Now we’re going to create our first report, the simplest one we can have. To do this just add this code to your domain class:

static def reportable = [:]

This map notation will tell what fields will be shown in the report and what options of it you’re configuring. As we do not specified any, all propeties will be there and the default report will be generated.

After this you can visit the report generator url at http://localhost:8080/agenda/djReport/index?entity=contact and this will generate a simple report file (no extension, you should add .pdf) of your contacts.

Very very simple, hã!

More options (personalization)

Now let’s configure some basic options of our report. First of all, I’ll not get all this properties in our agenda report, let’s get only the main fields (nick, phone, email):

def static reportable = [
   columns: ['nickname', 'email', 'phone']
]

You can run again the report, it will be similar to this one:

report

Now, there are some other basic options you might want to configure, like the filename, the report title and other stuff:

title: The report’s title, by default if you do not set anything it will be “[entity-name] report”.
fileName: The name that the response file generated will have
columns: the columns shown

def static reportable = [
   title: 'My agenda',
   fileName: 'agenda',
   columns: ['nickname', 'email', 'phone']
]

Second report

This three will help you start in this great plugin. Take a look in the plugin’s page to see all you can do.

It’s a simple but powerful plugin, you can adjust all the page layout, group properties, change the column titles, everything that does not involve the usual iReport drawing process.

Important Note

This note may be valid to other plugins either, but since grails 1.1, the installed plugins is not available in the project’s folder but in your HOME_DIR/.grails/1.1/projects/<project>/plugins

So, if you want to use advanced configuration of this (and others) plugin, you shoud enter its folder in ~/.grails/1.1/projects/agenda/plugins/, and get the configuration file of it, (in our case, DynamicJasperConfig.groovy) in its conf folder and save in our agenda/conf folder.

This file holds all plugin configuration and it can be used to setup the report layout and configure the named reports I said before.

Again, take a look in the plugin page and you’ll find everything you need! This is just an introduction of the plugin!

[]s,

Are you following me and reading my blog’s feed? Be the first to know when I publish some interesting article signing up to my feed and following me on twitter!

Multi-Tenant plugin. Incredible! 0

Today I was reading the old mails that I couldn’t read from last week and I read about the Multi-Tenant plugin for grails.

It’s an awesome plugin that solves your biggest problem if you have an simple application that you’ll sell its service for a bunch of people. You always think about having multiple instances of it, one for each user, correct? And you say:

– Ohhh no, I’ll have to have a lot of app servers!

So you start thinking about having a “customerId” for each domain class of your application. You’ll be lucky if you do not forget to use this identifier in some query…

Multi-Tenant plugin does all this boring job for you, you just annotate your domain class and configures a DNS resolver, telling the plugin that any request coming from www.xpto1.com will be the first customer and www.xpto2.com the second one.

Everything will be carefully watched so you’ll not have to worry about.

Don’t forget about this plugin, will save me. Hope it can help you! Read all docs about it here: http://grails.org/plugin/multi-tenant

Discovering your grails application version 0

In many projects around, one of the requisites is that our customer should know what version of the application was running in the environment. The first approach that people reaches is to insert a comment in the HTML source code or some static page that contains this info.

Using grails, we manage our application versions using the set-version grails command as you should know. After creating your grails application, the default version your application assumes is the 0.1. After some development you’re highly recommended on changing this. There is infinite approaches on managing app versions, I really like this one:

grails set-version 20090403-1

That says this is the first (1) version of today (2009 april’s third). After that, whe you create your war, the version will be appended in the war file’s name.

Ok, now that you have your application “versioned”, you can retrieve it with this simple line:

def version = grailsApplication.metadata['app.version']

Simple and useful!!! This will get the grailsApplication reference, that can get this information for you.

Are you following me and reading my blog’s feed? Be the first to know when I publish some interesting article signing up to my feed and following me on twitter!

[3/25] Building a RSS Reader with Quartz Plugin – Grails Tutorial 4

Are you reading my blog’s feed? Be the first to know when I publish some interesting article signing up to my feed and following me on twitter!

 

Groovy Version: 1.6
Grails Version: 1.1
Plugin Version: 0.4.1-SNAPSHOT
Plugin Docs: http://grails.org/plugin/quartz
Download Resources: source code screencast 1 screencast 2

Hello,

In this tutorial, we’ll talk about the Quartz plugin used to schedule jobs executions in your application. The plugin is build on top of the Quartz Job Scheduler Library from OpenSymphony. OpenSympony is the company that built the WebWork framework, that is now called Struts2 after Apache “aquisition”.

“Scheduling jobs” is very useful in your application to cover background needs. Some tasks you’ll need to execute undercover your application some times (invalidating old users that have not logged for more than 1 month) or even async processes that you’ll have to do if you do not have a JMS infrastructure, for example, sending e-mails to a lot of people.

In our example, we’ll build a simple RSS Reader that will use the quartz plugin to schedule fetchs it will be done in the feeds and insert in the database. Our application will mainly have one domain class called Post (seen in the last tutorial), a Feed domain class to store our feeds and a similar RSS Parser from technorati.  (Yes, I love the RSS format).

Initially, we’ll create the app, install the quartz plugin, create the domain classes and the Feed scaffold structure

grails create-app feedreader
cd feedreader
grails install-plugin quartz
grails create-domain-class Post

We’ll insert the Post domain class code

class Post {
    String title
    String link
    String body
}

We have to create the Feed domain class and its scaffold structure.

grails create-domain-class Feed
class Feed {
    String word
    String url
}

Scaffolding…

grails generate-all Feed

screencast-1
screencast

After this, we’ll create our Technorati Feed Parser from this code above.

class TechnoratiService {
    boolean transactional = false
    def parseAndSave(rss) {
        def rssObj = new XmlSlurper().parse(rss)
        rssObj.channel.item.each {
            def post = new Post(title: it.title.toString(),
                    link: it.link.toString(),
                    body: it.description.toString())
            post.save()
            println "Post [${post}] saved."
        }
    }
}

We’ll run our application using the grails run-app command and insert some feeds. Note that we’ve configured our datasource to use hsqldb storing in the filesystem instead of regular memory setup. 

Note that we have one JobController that Quartz install for us, forget about it, ok? We’ll create our own job after the second screencast.

screencast-2
screencast

Now, we have to understant some quartz properties and commands. 

When we install the quatz plugin, it installs another command for us the grails create-job MyJob, with it we’ll create our FeedParserJob. Note that we use convention over configuration with all jobs having *Job names. 

grails create-job FeedParser

Job classes have to implement the execute() method. This method is the one that Quartz will trigger when it’s time to execute the job. To define when the job it will be executed and what’s the interval between executions, I suggest you read the plugin documentation witch shows N ways to do this. In our example we’ll use a cron expression similar to *N*X OS systems setting our job to execute once in five minutes.

Our cron expression will be like this:  “0 0/5 * * * ?”

Depending on your jobs requisites, it may run concurrently with another instance of it or not. In our case, we’ll not start other job execution if the last on is still running. To prevent this behavior, we can set the concurrent property to false

def concurrent = false

Our job will essentially look for the feeds we’ve inserted on the database, and for each one it will call the Technorati service asking for new Posts. The final source for our job is the one below:

class FeedParserJob {
    def concurrent = false
    def cronExpression = "0 0/5 * * * ?"
    
    def technoratiService

    def execute() {
        def feedList = Feed.findAll()
        for (Feed feed : feedList) {
            println "Reading feed ${feed.word} @ ${feed.url}"
            technoratiService.parseAndSave(feed.url)
        }
    }
}

As you can see in the example above, you can inject any spring bean in your job, just declare it as I did with my TechnoratiService! :) (this is really great!)

That’s it, if you run you application you’ll see that every 5 minutes (minutes 0,5,10,15…) the job will be called and every posts technorati returns will be inserted on your database. Note that in this simple example we did not check if the post had been already inserted in the database before inserting it, this will just grow our database with a lot of instances representing the same post. This can be avoided checking if the post already exists before inserting it  (just check if you have any Post with the same link), but I’ll left this for you!

Before finish this, let’s just improve a little bit our post list view.

 

Tela de posts

 

 

Now, try to enrich its interface, adding some ajax to get only the new posts since the last fech! Maybe you can start from this your new Google Reader killer! :P

Now, let me know, are you using this plugin in your production environment? What for? What kind of jobs you do with it? 

Thanks!

Are you reading my blog’s feed? Be the first to know when I publish some interesting article signing up to my feed and following me on twitter!

 

Next tutorial: [4of25] Jasper Plugin

Past tutorials:
        [2of25] Searchable Plugin
        [1of25] AcegiSecurity Plugin

Next Page »

Web Analytics