2. O que é Groovy
Groovy é uma linguagem ágil dinâmica
para a plataforma Java com muitas
funcionalidades inspiradas de
linguagens como Python, Ruby e
Smalltalk, disponibilizando tais
funcionalidades para os
desenvolvedores Java em uma sintaxe
muito semelhante a Java.
7. Executando
• groovysh: Inicia o command-line shell, que é utilizado para
executar código Groovy interativamente. O código é
executado em tempo real, comando-a-comando."
• groovyConsole: Inicia a interface gráfica que também é
usada para executar código groovy interativamente; além
disso, o groovyConsole é carregado e executa os scripts
Groovy.
• groovy: Inicia o interpretador que executa scripts Groovy.
12. Groovy Beans
• Métodos públicos por padrão
• Métodos de acesso por padrão
• Acesso simplificado a atributos de Beans
13. Groovy Beans
class Car {
String name
}
def car = new Car();
car.setName(‘Civic’);
car.getNome(); //Civic
14. Outer Field Access
class Bean {
public Integer value
def getValue() {
value + 1
}
}
def bean = new Bean();
bean.getValue(); //Inner Field Access
car.@value; //Outer Field Access
15. GStrings
def nick = 'Gina'
def book = 'Groovy in Action'
assert "$nick is $book" == 'Gina is Groovy in Action'
27. Size
Com Groovy sempre que é preciso saber
o tamanho de um objeto utiliza-se o
método size().
O Java varia entre length, size(),
getLength(), e groupCount().
28. Operadores
x+y Plus x.plus(y) Number, String, Collection
x-y Minus x.minus(y) Number, String, Collection
Number, String,
x++ Next x.next(y)
Range
29. Sobrecarga de
Operadores
class Dinheiro {
def valor
Dinheiro (valor) { this.valor = valor }
Dinheiro plus (Dinheiro other) {
new Dinheiro(this.valor + other.valor)
}
}
Dinheiro a = new Dinheiro(1)
Dinheiro b = new Dinheiro(10)
Dinheiro c = a + b
30. GStrings
me = 'Tarzan'
you = 'Jane'
line = "me $me - you $you"
assert line == 'me Tarzan - you Jane'
assert line instanceof GString
assert line.strings[0] == 'me '
assert line.strings[1] == ' - you '
assert line.values[0] == 'Tarzan'
assert line.values[1] == 'Jane'
42. Import as
import thirdparty.MathLib as TwiceHalfMathLib
import thirdparty2.MathLib as IncMathLib
def math1 = new TwiceHalfMathLib()
def math2 = new IncMathLib()
assert 3 == math1.half(math2.increment(5))
44. GroovyObject
public interface GroovyObject {
public Object invokeMethod(String name, Object args);
public Object getProperty(String property);
public void setProperty(String property, Object newValue);
public MetaClass getMetaClass();
public void setMetaClass(MetaClass metaClass);
}
Also Interception and Proxies
51. Template
def mensagem = '''
Querido amigo ${destinatario}
Gostaria de pedir que me ajudasse a realizar essas ${tarefas.size} tarefas:
<% tarefas.each() { %> - ${it}
<% } %>
'''
def engine = new groovy.text.SimpleTemplateEngine();
def template = engine.createTemplate(mensagem);
def parametros = [
destinatario: 'Zé das Couves',
tarefas: ['comprar um ovo de páscoa', 'regar as plantas']
]
print template.make(parametros).toString()
Querido amigo Zé das Couves
Gostaria de pedir que me ajudasse a realizar essas 2 tarefas:
- comprar um ovo de páscoa
- regar as plantas
53. Groovylets
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd" >
<web-app>
<display-name>Groovlet Demonstrator</display-name>
<description>
Showing the use of Groovlets for Groovy in Action
</description>
<servlet>
<servlet-name>Groovy</servlet-name>
<servlet-class>groovy.servlet.GroovyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Groovy</servlet-name>
<url-pattern>*</url-pattern>
</servlet-mapping>
</web-app>
54. Groovylets
html.html{
head { title 'Groovlet Demonstrator' }
body {
h1 'Variables in the Binding:'
table(summary:'binding') {
tbody {
binding.variables.each { key, value ->
tr {
td key.toString()
td(value ? value.toString() : 'null')
}
}
}
}
}
}
55. Groovylets + Templates
<html>
<head>
<title>Think of a Number</title>
</head>
<body>
<h1>Think of a Number</h1>
Your guess $guess is <%
switch (guess) {
case goal : out << 'correct!'; break
case {it < goal} : out << 'too low' ; break
case {it > goal} : out << 'too high'; break
}
%>
<p>What"s your guess (0..100)?</p>
<form action='Templater.groovy'>
<input type='text' name='guess'>
<button type='submit'>Guess</button>
<button type='submit' name='restart' value='true'>New Game
</button>
</form>
</body>
</html>
def engine = new groovy.text.SimpleTemplateEngine()
def source = getClass().classLoader.getResource('/Number.template.html')
def template = engine.createTemplate(source)
out << template.make(goal:50, guess:49)
56. Groovy Shell
final GroovyShell groovyShell = new GroovyShell();
final String result = (String) groovyShell.evaluate(" new File('.').eachFile { println it } ");
System.out.println(result);