Archive for the 'Tech' Category


Grails 1.2 Milestone 2 is out! 0

Yeah!! Graeme just announced rigth now that grails 1.2-M2 is out!
I’ve already talked about some changes and improvements in my twitter, but now is officially!

Check the release notes here: http://www.grails.org/1.2-M2+Release+Notes, the changelog, and download it to upgrade your applications!

Docs, as usual available here: http://grails.org/doc/latest

Later, I’ll write a post about the new features, probably one by one, come back!

Following me on twitter?

[]s,

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,

Interceptando métodos inexistentes em Groovy 2

As linguagens dinâmicas estão ganhando um espaço considerável hoje em dia. Para dar um exemplo do poder dessas linguagens, criei um exemplo simples em Groovy (linguagem Java que roda “em cima” da JVM).

Uma das características dessas linguagens, é poder aproveitar a criatividade do desenvolvedor. Daí temos como exemplo uma função que pode ser definida em nossos objetos chamada methodMissing. Essa função é chamada quando algum método não encontrado é chamado em algum objeto. Caso não seja definida, aí sim temos o comportamento padrão do Java, uma exception apontando a falta do método.

No twitter, o @cmilfont perguntou ao @fabiokung sobre um builder de HTML que ele tinha feito em ruby com o mesmo princípio. Usar o methodMissing. Quando eu vi este builder, fiquei pasmo com a simplicidade e objetividade, e tudo isso originou este post. Coloquei alguns tratamentos que não existiam, para valores de atributos das tags.

O exemplo utiliza o poder da função methodMissing para criar um “Builder”, ou então um construtor de HTML dinâmico com base em pseudo-métodos chamados pelo cliente. Imaginem a função abaixo:

def methodMissing(String name, params) {
	if (params[0] instanceof Closure) {
		println "< ${name}>"
		params[0].call()
		println "< / ${name}>"
	} else if (params[0] instanceof String) {
		println "< ${name}>${params[0]}< ${name}>"
	} else if (params[0] instanceof Map) {
		print "< ${name}"
		params[0].each() {chave, valor ->
			print " ${chave}=\"${valor}\""
		}
		if (params.length > 1) {
			if (params[1] instanceof Closure) {
				println ">"
				params[1].call()
				println ""
			}
		} else println " />"
	}
}

No primeiro if, resgatando o parâmetro do tipo closure, apenas faz a chamada a esta closure, para que o novo método seja chamado entre “TAGS” que são o nome do método criado dinâmicamente… Já no caso do parâmetro ser uma String, é encarada como conteúdo inteno da tag e renderizada desta maneira.

Se um map for passado como parâmetro, a interpretação é tida como vários atributos da tag html (método inexistente), e caso ainda tenhamos uma outra closure ali como parâmetro, o comportamento é repetido :)

Com este exemplo, poderíamos construir um simples HTML com o seguinte trecho de código (script) groovy:

html {
    head {
        title "teste de titulo"
    }
    body {
        div(id:3, class:"odd") {
            p "meu texto"
        }
        div id:5, class:"xpto"
    }
}

Prontinho, a JVM com o trecho acima cria nosso super-mega-ultra-elaborado trecho de HTML:

< html >
< head >
< title >teste de titulo< / title >
< / head >
< body >
< div id="3" class="odd" >
< p >meu texto< / p >< / div >
< div id="5" class="xpto" / >
< / body >
< / html >

Groovy é uma linguagem de script muito bacana e poderosa, e como roda em cima da JVM, não é nada mais que Java puro. Pode com certeza e MUITA eficiência substituir aqueles scripts shell que temos em algumas aplicações, trazendo para os desenvolvedores mais liberdade (de chamar um jar com funcionalidades, por exemplo), e conforto (de não depender de alguém de infra estrutura, ou de conhecimento em shell script).

Fica aí a dica e o exemplo do poder…

Valeu!

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,

Understanding Groovy Categories 5

Have you ever used Groovy Categories? Do you even know what its stands for?

Groovy Categories is a great feature from Groovy (inherted from Objective-C) that allows you to have some kind of “extended” control on a class. The category just “add” some more funcionality to your class when you want. It’s different from creating another class that extends from the first one, this approach holds a little more functionality-oriented talk… :)

Categories is nothing more than a Groovy class that you’ve implemented before that effectly adds your functionality. The syntax is very simple and all you have to do, is tell to the runtime environment you’re now using the category.

use (the category class you want to use) {
    //all your code here can access the category funcionality
}
//back to normal code

That’s it. Groovy Core comes with some Categories (ServletCategory, DOMCategory and TimeCategory). The one we use more is the TimeCategory, that adds some calculation methods for us.

Let’s imagine we want to add some days in our current date, using Java you remember how you should do, don’t you?

Get a Calendar Instance, retrieve this calendar’s date, add the ammount of days using the strangest and creepiest method ever and then get the calendar’s date again (actually, get only its time and create a date with it):

//creepiest method
myCalendarInstance.add(Calendar.DAY_OF_MONTH, 10);

You can see in the TimeCategory’s javadoc (link above) that it defines some methods like “getHours(), getDays(), getMinutes()”. This methods we don’t have in some usual Date class, but when we use the TimeCategory object, they just get available for us. The example below show us what should happen when we use the TimeCategory:

Date now = new Date()
println now //just show when am I :) 

use(org.codehaus.groovy.runtime.TimeCategory) {
    now = now + 15.days
}

println now //shows us when we'll be in 15 days!

This will be our output after running this small script:

Sat May 02 02:25:57 BRT 2009
Sun May 17 02:25:57 BRT 2009

That’s it, try the code above and the others methods the TimeCategory gives to you: years, months, hours, minutes and seconds.

Thanks! Be the first to know when I publish some interesting article signing up my feed and following me on twitter!

Changing the default locale for your grails application 5

Thank god grails has a wonderful i18n native support. It’s great change all your application language just by setting one more parameter in the URL (lang). If you do not know this behaviour, check this out.

But sometimes you have to preset the default language because not all your applications will be in english, yap ? To make this you’ll have to set your localeResolver in your resources.groovy spring configuration file. just add this code to it. (note that my code is setting my language to brazilian portuguese – pt_BR)

//this is your resources.groovy file
//
beans = {
   localeResolver(org.springframework.web.servlet.i18n.SessionLocaleResolver) {
      defaultLocale = new Locale("pt","BR")
      java.util.Locale.setDefault(defaultLocale)
   }
}

[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:[&quot;M&quot;,&quot;F&quot;])
   }
}

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!

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!

Next Page »

Web Analytics