Groovy
    &
  Grails
Victor Hugo Germano
      #lambda3   http://www.flickr.com/photos/montreal1976/4502659151
“Quando você programa em Groovy,
de várias formas você está escrevendo
       um tipo especial de Java.”

                               -Dierk König
                            Groovy in Action
Integração transparente
             com Java
Suporta Tipagem
    Estática          bytcode

     Groovy
 Sintaxe Similar Linguagem Dinâmica
                      para JVM
Meta Object Protocol
file.groovy            file.java




 bytecode             bytecode



   The Java Virtual Machine
http://www.flickr.com/photos/oskay/472097903/
Uma classe em Java
 public class HelloWorld {
   private String name;

     public String getName() {
       return name;
     }
     public void setName(String message) {
       this.name = message;
     }
     public String message() {
       return "Hello World of "+this.name;
     }
     public static void main(String[] args) {
       HelloWorld hello = new HelloWorld();
       hello.setName("Grooooooovy");
       System.out.println(hello.message());
     }
 }
A mesma classe
  em Groovy
 class HelloWorld {
   String name
   def message() {
      "Hello World of $name"
   }
 }
 def hello = new HelloWorld(name:"Grooovy")
 println hello.message()
http://www.flickr.com/photos/noideas/2323222802/




Conceitos Básicos
Conceitos Básicos

Se você já programa em Java,
você já programa em Groovy!



                    http://www.flickr.com/photos/jeyp/4149695639
Conceitos Básicos
         class Pessoa {
           String nome
           int idade
         }
       void setIdade(idade) {
         this.idade = idade - 4
       }

new Pessoa ( nome: “Zé”, idade: 7)
Conceitos Básicos
   def today = new Date()
   def tomorrow = today + 1


 assert today.before(tomorrow)
 assert tomorrow.after(today)
Operator Overloading
     a+b        a.plus(b)
     a-b       a.minus(b)
     a/b      a.multiply(b)
     a%b      a.modulo(b)
     a ** b   a.power(b)
     a&b        a.and(b)
      a[b]     a.getAt(b)
Operator Overloading
 class Pedido {
    def total
    def plus(Pedido pedido) {
       def result = this.total + pedido.total
       new Pedido(total:result)
    }
  }

  def pedido1 = new Pedido(total: 10)
  def pedido2 = new Pedido(total: 50)

  def pedido3 = pedido1 + pedido2

  println pedido3.total
Special Operatos
 Elvis operator
 def displayName = user.name ? user.name : “No one”
 def displayName = user.name ?: “No one”


  Operador Seguro
   de Navegação
def addr = user?.address?.toUppercase()
Groovy Strings

          http://www.flickr.com/photos/elianarei/3904613032/
Groovy Strings
   public String displayString() {
       return “<u>” + title + “</u> by ” +
               authorName + “, (“ +
               numberOfPages + “ pages)”;
   }


                   Interpolação
String displayString() {
  “<u>$title</u> by $authorName, ($numberOfPages pages)”;
}
Groovy Strings
String displayMultiLineString() {
  “““<u>$title</ul>
     by $authorName,
   ($numberOfPages pages)”””;
}
Collections

         http://www.flickr.com/photos/wisekris/183438282/
Collections
def frutas = [“Banana” , “Pera”, “Maçã” ]


def countries = [ br: “Brazil”,
          us: “United States”,
          ie: “Ireland” ]

println countries.br
Collections
for (c in countries) {
    println c
}


  countries.each {
     println it
  }
Collections
def list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
def sublist = list[0..5]


def square = { it * 2 }
[1, 2, 3].collect(square)== [2, 4, 6]
Collections
private List books;

   public List<Book> findByISBN(String isbnCode) {
      Book result = null;
      if(books != null && isbnCode != null) {
          for (Book book : books) {
              if(book != null && isbnCode.equals(book.getISBN()) ) {
                  result = book;
                  break;
              }
          }
      }
      return result;
   }
Collections
  List books;
	 Book findByISBN(String isbnCode){
	 	 books?.find({it?.isbn == isbnCode});
	 }

  List books;
	 List findAllByAuthor(String authorName){
	 	 books?.findAll({
          it?.author == authorName
          })
	 }
Groovy Truth
Groovy Truth
  def a = true
  def a = false
  assert a
  assert !b
Groovy Truth
def numbers = []
assert numbers // false

def numbers = [1, 2, 3]
assert numbers // true
 Coleções Vazias!
Groovy Truth
assert ‘Verdadeiro’ // true

assert ‘’ // false

          Strings!
Groovy Truth
assert null // false
assert 0 // false

assert (new Object()) // true
assert 1 // true
Objetos e Números!
Closures

      http://www.flickr.com/photos/brizzlebornandbred/4262145162/
Closures
{ Bloco de Código
       ou
 Pointeiro para
  um Método }
Closures
def refParaClosure ={
  parametros ->
  //Código..
}

refParaClosure(p1, p2...)
Let’s play!
     http://www.flickr.com/photos/rogerss1/3232663848
Arquivos
Em
Java!!!!
import java.io.*;
class FileRead 
{
   public static void main(String args[])
  {
      try{
    // Open the file that is the first 
    // command line parameter
    FileInputStream fstream = new FileInputStream("textfile.txt");
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
   BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
      System.out.println (strLine);
    }
    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}
def file = new File("textfile.txt")
 file.eachLine { line ->
   println line
  }




                      moonbug.org
Arquivos
def file = new File("textfile.txt")
file << ‘Escrevendo no arquivo’

    def dir = new File("c:")
    dir.eachFile {
      println it
    }
Duck Typing

        http://www.flickr.com/photos/catdonmit/2326033244/
Duck Typing
void cuidar(Pato pato) {
     pato.quack()
     pato.andar()
     pato.comer(new Comida(tipo: “peixe”))
 }
Duck Typing
 void fakePato = [
   andar: { },
   quack: { },
   comer: { Comida c -> }
        ]

cuidar(fakePato as Pato)
Metaprogramação
M.O.P.
Meta Object Protocol

Criando código
  gerador de código
Metaprogramação
           MetaClass
          ExpandoClass
    getProperty / setProperty
invokeMethod / invokeStaticMethod
         methodMissing
Metaprogramação
 "Florianópolis".totalDeLetras()

String.metaclass {
  totalDeLetras = { delegate.size() }
}
Builders
import groovy.xml.MarkupBuilder

def mkp = new MarkupBuilder()
mkp.html {
  head {
    title "Minicurso G&G"
  }
  body {
    div(class:"container") {
        p "Lambda3 & Globalcode going dynamic!"
      }
   }
}
http://www.flickr.com/photos/ttdesign/343167590




AST Transformation
AST Transformation
  Metaprogramação em tempo de compilação
public class T {
    public static final T instance = new T();
    private T() {}
    public T getInstance() { (...) }
}


   @Singleton class T { }
AST Transformation
class Pessoa {          class Endereco {
    String nome             String rua
    @Delegate               String cidade
    Endereco endereco       String pais
}                       }


       def pessoa = new Pessoa()
       pessoa.rua = “Avenida Paulista”
       pessoa.cidade = “Sao Paulo”
       pessoa.pais = “Brasil”
http://www.flickr.com/photos/jerica_chingcuangco/3659719599




Can you feel it?
GRAILS
Outro Framework Web?!
           JSPWidget
 Sombrero              Struts
  JSF   OpenXava      Turbine
      SwingWeb
VRaptor
       Cocoon           Calyxo
WebOnSwing           Wicket
        Maverick Tapestry
                 http://www.flickr.com/photos/nwardez/3089933582/in/photostream/
Java Web Development
              JSPWidget
              OpenXava
                Turbine
                  JSF
JEE Struts    Sombrero
              SwingWeb
1999


              VRaptor
              Cocoon
               Calyxo
               Wicket
             WebOnSwing
              Tapestry
              Maverick
                          http://www.itexto.net/devkico/?p=224
Java Web Development
                                       Hibernate


    JEE                 Gerenciar
      1999
                      Complexidade
                                        Spring       Aqui
                                                      jás

                                                   Java para
http://www.itexto.net/devkico/?p=224                 Web
Convenções
      Full Stack
      Scaffolding

Extensibilidade

          http://www.itexto.net/devkico/?p=224
Migrar tudo para
     Rails?
Experiência




Flexibilidade
GRAILS
       http://grails.org

   Groovy é a linguagem base
          Convenções!!

Ambiente Completo (“Full Stack”)

         Extensibilidade
Full Stack
                  Grails




                                              Groovy
Java Enterprise
 Edition (JEE)    Spring Hibernate SiteMesh

                             The Java
 The Java Language        Development Kit
                               (JDK)


           The Java Virtual Machine
Show me
some code!!

        http://www.flickr.com/photos/outime/4250568447
grails create-app library
   grails create-domain-class library.Book


    grails create-controller library.Book



       grails generate-all library.Book


               grails run-app
Forma & Conteúdo
Configuração
environments {
    development {
        dataSource {
            dbCreate = "create-drop"
            url = "jdbc:hsqldb:mem:devDB"
        }
    }
    test {
        dataSource {
            dbCreate = "update"
            url = "jdbc:hsqldb:mem:testDb"
        }
    }
    production {
        dataSource {
            dbCreate = "update"
            url = "jdbc:hsqldb:file:prodDb;shutdown=true"
        }
    }
}
Modelagem de Domínio
  Active Record pattern

        GROM
Groovy Relational Object Mapping
      Dynamic Finders
         Validations
    Hibernate Criterias
Request Handling
 Response / rendering


  Controllers
          “Pense em Servlets, só que melhores!”

Negociação de Conteúdo
     Data Binding
     Interceptors
Parecido com JSPs e ASP
HTML + GSP tags + Taglibs

       Views
   Layouts & Templates
Embedded Groovy Code
  MAS NÃO FAÇA!
Fácil e simples!
Similar ao Routes do Rails

 URL Mapping
      Validations
     URL Encoding
Transacionais por padrão
Guargam Regras de Negócio

  Service Layer
 Diferenciados por Escopo
   Dependency Injection
Testing
          http://www.flickr.com/photos/busyprinting/4671731838
Plugins
IDEs
  http://www.flickr.com/photos/22280677@N07/2504310138/
Comunidade
       http://www.flickr.com/photos/badwsky/48435218/
Comunidade
   http://groovy.codehaus.org
          http://grails.org
      http://grailsbrasil.com/
http://github.com/grails/grails-core
 Grails: um guia rápido e indireto
Tá, e daí?




Quem usa de Verdade?
Quem usa de Verdade?
http://www.wired.com/            http://www.sky.com/




  http://iiea.com                       http://cmrf.org


             http://grails.org/Testimonials
Obrigado!

twitter.com/victorhg
www.lambda3.com.br

              Use it! Share it!
                Remix it!

Minicurso groovy grails