Archive for the 'Nenhuma' Category


Blog paused 0

Hey all,

This blog will be ‘paused’ for a while.
I’m running on some new apps for clients and this is taking my most time.

I’ll be back soon, thanks a lot, and keep on.

@lucastex

New Grails and Groovy related online board 1

Hello all,

A new Online Board is running up! GR8Forums.org is an online board to group questions, tips, discussions, knowlodge sharing and other stuff that are around Groovy Stuff… This means

  • Grails
  • Groovy
  • Gradle
  • Gaelyk
  • Gant
  • Any other gr8 stuff it should be there

C’mon, register online and introduce yourself here: http://gr8forums.org/viewtopic.php?f=21&t=3.
Come join and bring your groovy friends to the newest gr8 family.

[]s,

Viewing XML files in Safari 0

Oh, if you use Mac and Safari, viewing XML files is definitely one of worst things ever.
You have to open it and then use the ‘view source’ option to handle it.

This Safari Plugin called XMLView Plugin can make things easier. :) Just download it and uncompress it on your $HOME/Library/Internet Plug-Ins folder.

Close and reopen your Safari, and open any xml. You’ll se a well-formated XML with syntax highlight and expand/colapse options.

If you’re not following me on twitter, you own me a dollar for this one.

:)

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

A metaprogramação em linguagens dinâmicas 0

Vamos imaginar que gostaríamos de “adicionar comportamentos específicos” aos nossos objetos já escritos. Neste caso, usando a pura, tradicional, cafona e obsoleta orientação a objetos, estaríamos travados e acabaríamos por optar por uma composição de objetos, ou quem sabe uma generalização, certo? Uma das maiores vantagens (e perigos caso o programador seja na verdade um macaco de código), é o uso da metaprogramação. A metaprogramaçao nos permite exatamente isto, adicionar funções, e alterar o “esqueleto comportamental” de classes e objetos, por exemplo.

Para uma classe onde temos nosso cachorro, que anda:

class Dog {
  def walk() {
    println “walking…”
  }
}


se quisessemos definir um método para que ele latisse em runtime, faríamos da seguinte maneira:

def dog = new Dog()
dog.walk() //walking…

//Neste ponto, se fizermos a chamada dog.bark() teremos
//uma exception por estarmos chamando um método inexistente.
//Poderíamos contornar o erro com a implementação do methodMissing
//como dito no outro post, ou então da seguinta maneira

dog.metaClass.bark = {
  println “au.”
}

//Pronto, após isto, é só latir
dog.bark() //au.

Poderíamos também trabalhar com parâmetros da função

dog.metaClass.bark = { vezes ->
vezes.times {
println “au.”
}
}

dog.bark(5)
//au.
//au.
//au.
//au.
//au.

Neste caso, definimos o comportamento do método bark() em runtime, para um objeto já existente. Se quisessemos agora, unir os comportamentos de um objeto, em outro, poderíamos usar o recurso de mixin de objetos, que traz as definições de métodos e funçoes de um objeto para outro. Tendo a definição de um pato, onde:

class Duck {
  def quack() {
    println “quack!”
  }
}

Fica fácil fazer com que o pato ande como um cachorro! (absorvendo a função definida na classe Dog) :)

def duck = new Duck()
duck.quack() //quack!

//dedo de deus
duck.metaClass.mixin Dog

duck.walk() //walking

É isso aí.

[]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,

issues on my dreamhost hosting. 0

Some of you may ‘ve noticed that my blog was not responsing the hole day… Sorry about that. I just moved from a shared hosting to a private server (so I can run grails here) and DH just broke my server config.

Terrible…

Making a readeable code, more and more readeable 4

One thing groovy and grails really rocks, is the legibility of the generated code. It’s amazing how this Java code below

Contact boringObject = new Contact();
boringObject.setNome("Lucas");
boringObject.setIdade(24);
boringObject.setEmail("lucastex@gmail.com");
boringObject.setPhone("55 11 9999.9999");
boringObject.setDateCreated(new java.util.Date());

can turn into this beautiful code:

def c = new Contact()
c.name = "Lucas"
c.age = 24
c.email = "lucastex@gmail.com"
c.phone = "55 11 9999.9999"
c.dateCreated = new Date()

Yeah, I know, this is simple and it’s already done in most frameworks via OGNL and reflection, but groovy bring this feature natively and makes the code human-readeable removing all unnecessary commas, parenthesis and other symbols. Groovy brings the code to the closest natural reading language I ever saw! You can see this by studying the GORM dynamic finders, that is a real good example of what I’m saying; you think, you transcript and that’s the code.

Another useful feature, to make the code more readeable, is the with builder block. Imagine the snippet above, all properties that we’re setting, we’re setting in the same object, so why do we have to mention the object everytime? So, you can use this block to set everything in the same object. Try the code above:

def cb = new Contact()
cb.with {
   name = "Katie"
   age = 24
   email = "katie@xpto.com"
   phone = "55 11 8888.8888"
   dateCreated = new Date()
}

That’s why I like groovy so much, you won’t waste your time on “syntax learning”. All you need to do is read the code! :)

Follow me on twitter and subscribe my blog’s feed!

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

[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

Web Analytics