minicurso groovy grails
DESCRIPTION
O fato de existirem inúmeras linguagens que rodam na JVM já não é novidade nenhuma, principalmente com o sucesso de Scala e JRuby. Seguindo a linha das principais linguagens do mercado, Groovy apresenta-se como uma ótima alternativa para aqueles que querem tentar uma nova linguagem, mas ainda gostam na sintaxe Java. Ganhando popularidade nos últimos tempos, Groovy é uma linguagem dinâmica inspirada em Python, Ruby e Smalltalk que pode ampliar e muito a produtivade em seu dia-a-dia. Quanto tempo você leva para fazer um site utilizando as principais ferramentas Java? Pois em Grails isso pode ser ainda mais rápido! Inspirado no framework Ruby on Rails, Grails tem ganhado popularidade entre as opções para desenvolvimento web devido ao seu alto grau de integração com a plataforma Java, e adicionando a isso conceitos como interceptors, tag libs, Groovy Servers Pages (GSP), além de uma grande variedade de plugins para facilitar ainda mais o desenvolvimento web.TRANSCRIPT
http://www.flickr.com/photos/montreal1976/4502659151
Groovy&
GrailsVictor Hugo Germano
#lambda3
“Quando você programa em Groovy, de várias formas você está escrevendo
um tipo especial de Java.”
-Dierk KönigGroovy in Action
GroovyLinguagem Dinâmica
para JVMMeta Object Protocol
bytcodeSuporta Tipagem
Estática
Integração transparente com Java
Sintaxe Similar
file.groovy file.java
The Java Virtual Machine
bytecode bytecode
http://www.flickr.com/photos/oskay/472097903/
Uma classe em Javapublic 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()); }}
class HelloWorld { String name def message() { "Hello World of $name" } }def hello = new HelloWorld(name:"Grooovy")println hello.message()
A mesma classeem Groovy
Conceitos Básicos
http://www.flickr.com/photos/noideas/2323222802/
Conceitos Básicos
Se você já programa em Java, você já programa em Groovy!
http://www.flickr.com/photos/jeyp/4149695639
Conceitos Básicosclass Pessoa { String nome int idade}
new Pessoa ( nome: “Zé”, idade: 7)
void setIdade(idade) {this.idade = idade - 4
}
Conceitos Básicosdef today = new Date()def tomorrow = today + 1
assert today.before(tomorrow)assert tomorrow.after(today)
Operator Overloadinga + 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 Overloadingclass 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
def addr = user?.address?.toUppercase()
Elvis operatordef displayName = user.name ? user.name : “No one”def displayName = user.name ?: “No one”
Operador Seguro de Navegação
Groovy Strings
http://www.flickr.com/photos/elianarei/3904613032/
Groovy Stringspublic String displayString() { return “<u>” + title + “</u> by ” +
authorName + “, (“ + numberOfPages + “ pages)”;
}
InterpolaçãoString 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/
Collectionsdef frutas = [“Banana” , “Pera”, “Maçã” ]
def countries = [ br: “Brazil”, us: “United States”, ie: “Ireland” ]
println countries.br
Collections
countries.each {println it
}
for (c in countries) {println c
}
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]
Collectionsprivate 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; }
List books; Book findByISBN(String isbnCode){ books?.find({it?.isbn == isbnCode}); }
Collections
List books; List findAllByAuthor(String authorName){ books?.findAll({
it?.author == authorName})
}
Groovy Truth
Groovy Truthdef a = truedef a = falseassert aassert !b
Groovy Truthdef numbers = [] assert numbers // false
def numbers = [1, 2, 3]assert numbers // trueColeções Vazias!
Groovy Truthassert ‘Verdadeiro’ // true
assert ‘’ // false
Strings!
Groovy Truthassert null // falseassert 0 // false
assert (new Object()) // trueassert 1 // true
Objetos e Números!
Closures
http://www.flickr.com/photos/brizzlebornandbred/4262145162/
Closures { Bloco de Código
ouPointeiro para um Método }
def refParaClosure ={ parametros ->
//Código..}
refParaClosure(p1, p2...)
Closures
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
Arquivosdef 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 Typingvoid 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çãoMetaClass
ExpandoClass
getProperty / setProperty
invokeMethod / invokeStaticMethod
methodMissing
"Florianópolis".totalDeLetras()
String.metaclass { totalDeLetras = { delegate.size() }}
Metaprogramação
import groovy.xml.MarkupBuilder
def mkp = new MarkupBuilder()mkp.html {
head {title "Minicurso G&G"
}body {
div(class:"container") { p "Lambda3 & Globalcode going dynamic!" } }}
println mkp
Builders
AST Transformation
http://www.flickr.com/photos/ttdesign/343167590
AST Transformation
public class T { public static final T instance = new T(); private T() {}
public T getInstance() { (...) }}
Metaprogramação em tempo de compilação
@Singleton class T { }
AST Transformationclass Pessoa {
String nome@DelegateEndereco endereco
}
class Endereco {String ruaString cidadeString pais
}
def pessoa = new Pessoa()pessoa.rua = “Avenida Paulista”pessoa.cidade = “Sao Paulo”pessoa.pais = “Brasil”
Can you feel it?
http://www.flickr.com/photos/jerica_chingcuangco/3659719599
GRAILS
Outro Framework Web?!
Struts
JSF
Tapestry
Cocoon
Maverick
Sombrero
VRaptor
Wicket
OpenXava
JSPWidget
Calyxo
Turbine
WebOnSwing
SwingWeb
http://www.flickr.com/photos/nwardez/3089933582/in/photostream/
JSF
Tapestry
Cocoon
Maverick
Sombrero
VRaptor
Wicket
OpenXavaJSPWidget
Calyxo
Turbine
WebOnSwing
SwingWebStruts
http://www.itexto.net/devkico/?p=224
JEE1999
Java Web Development
Java para Web
Aquijás
JEE1999
http://www.itexto.net/devkico/?p=224
GerenciarComplexidade
Hibernate
Spring
Java Web Development
http://www.itexto.net/devkico/?p=224
Convenções
Full Stack
Scaffolding
Extensibilidade
Migrar tudo para Rails?
Flexibilidade
Experiência
Ambiente Completo (“Full Stack”)
Groovy é a linguagem base
Convenções!!
Extensibilidade
GRAILShttp://grails.org
Java Enterprise Edition (JEE) SiteMesh
The Java LanguageThe Java
Development Kit (JDK)
Hibernate
Gro
ovy
Spring
The Java Virtual Machine
Grails
Full Stack
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 run-app
grails generate-all library.Book
Forma & Conteúdo
Configuraçãoenvironments { 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
Dynamic Finders
Validations
Hibernate Criterias
GROMGroovy Relational Object Mapping
“Pense em Servlets, só que melhores!”
Interceptors
Request Handling
Negociação de Conteúdo
Response / rendering
Data Binding
Controllers
Parecido com JSPs e ASP
HTML + GSP tags + Taglibs
Embedded Groovy Code
MAS NÃO FAÇA!
Layouts & Templates
Views
URL Encoding
Similar ao Routes do Rails
Validations
URL Mapping
Fácil e simples!
Guargam Regras de Negócio
Diferenciados por Escopo
Service Layer
Transacionais por padrão
Dependency Injection
Testing
http://www.flickr.com/photos/busyprinting/4671731838
Plugins
IDEshttp://www.flickr.com/photos/22280677@N07/2504310138/
Comunidadehttp://www.flickr.com/photos/badwsky/48435218/
http://grailsbrasil.com/
http://grails.org
http://groovy.codehaus.org
Grails: um guia rápido e indireto
http://github.com/grails/grails-core
Comunidade
Tá, e daí?
Quem usa de Verdade?
http://www.wired.com/
http://grails.org/Testimonials
http://www.sky.com/
http://iiea.com http://cmrf.org
Quem usa de Verdade?
Obrigado!
twitter.com/victorhg
Use it! Share it!Remix it!
www.lambda3.com.br