Download Groovy - T3chFest

Document related concepts
no text concepts found
Transcript
Cambia la forma de desarrollar
tus aplicaciones web
Leganés, 6-7 Febrero 2014
@fatimacasau
!
¿Qué vamos a ver?
!
¿Qué es?
!
Características
!
Getting Started
!
Features + Código
@t3chfest 2014
@fatimacasau
JVM
!
Dinámico
!
Tiempo de ejecución
!
@CompileStatic (versión 2.x)
!
Ruby, Phyton, Smaltalk
@t3chfest 2014
@fatimacasau
Groovy ~ Java
!
Sencillo + Expresivo = Coding by Convention
!
GDK - Groovy Development Kit (JDK extension)
!
Groovy ~ Superversión de Java
@t3chfest 2014
@fatimacasau
Getting Started
!
Descarga:
!
Terminal:
http://groovy.codehaus.org/Download
$ groovysh
$ groovyconsole
!
Web Console: http://groovyconsole.appspot.com/
!
IDEs:
!
@t3chfest 2014
@fatimacasau
Features
!
OOP
!
Clases: Getters/Setters y constructores autogenerados
!
Closures
!
Sobrecarga de operadores
!
Soporte nativo para cadenas (Gstrings) y collecciones
@t3chfest 2014
@fatimacasau
HelloWorld.java
class HelloWorld {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String greet() {
return "Hello " + name;
}
public static void main(String[] args) {
HelloWorld helloWorld = new HelloWorld();
helloWorld.setName("Groovy");
System.out.println(helloWorld.greet());
}
}
@t3chfest 2014
@fatimacasau
HelloWorld.groovy
class HelloWorld {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String greet() {
return "Hello " + name;
}
public static void main(String[] args) {
HelloWorld helloWorld = new HelloWorld();
helloWorld.setName("Groovy");
System.out.println(helloWorld.greet());
}
}
@t3chfest 2014
@fatimacasau
HelloWorld.groovy (groovy style)
!
class HelloWorld {
def name
def greet() {
"Hello $name"
}
}
!
def helloWorld = new HelloWorld(name: "Groovy")
println helloWorld.greet()
@t3chfest 2014
@fatimacasau
GStrings
// Múltiples líneas con y sin salto de línea (también con triple ")
assert '''hello,
world''' == 'hello,\nworld‘
!
assert 'hello, \
world' == 'hello, world‘
!
// Sustitución de variables con dobles comillas
def name = 'Groovy'
assert "hello $name, how are you today?" == "hello Groovy, how are you
today?
!
def a = 'How are you? '
assert "The phrase '$a' has length ${a.size()}" =="The phrase 'How are you?'
has length 12"
@t3chfest 2014
@fatimacasau
Listas
def list = [5, 6, 7, 8]
assert list.get(2) == 7
assert list[2] == 7
!
assert
!
list instanceof java.util.List
def emptyList = []
assert emptyList.size() == 0
!
emptyList.add(5)
assert emptyList.size() == 1
!
emptyList << 3
assert emptyList.size() == 2
!
emptyList << 'Groovy'
assert emptyList.size() == [5, 3, 'Groovy']
@t3chfest 2014
@fatimacasau
Rangos
// an inclusive range
def range = 5..8
assert range instanceof java.util.List
assert range.size() == 4
assert range[2] == 7
assert range.contains(5)
assert range.contains(8)
// lets use a half-open range
range = 5..<8
assert range.size() == 3
assert range.contains(5)
assert ! range.contains(8)
assert range.from == 5
assert range.to == 7
!
range = 'a'..'d'
assert range == ['a','b','c','d']
@t3chfest 2014
@fatimacasau
Mapas
def map = [name: "Gromit", likes: "cheese", id: 1234]
assert map instanceof java.util.Map
!
assert map.get("name") == "Gromit"
assert map.get("id") == 1234
!
assert map["name"] == "Gromit"
assert map ['id'] == 1234
!
assert map.name == "Gromit"
assert map.id == 1234
!
def emptyMap = [:]
assert emptyMap.size () == 0
!
map.foo = 4
assert map.foo == 4
@t3chfest 2014
@fatimacasau
Closures
!
Bloques de código
!
Pueden asignarse a variables
!
Tienen variables implícitas
!
Pueden utilizar variables externas
!
Pueden pasarse como argumento de métodos
@t3chfest 2014
@fatimacasau
Closures
!
def
!
myConst = 5
def incByConst = { num ->
num + myConst
}
!
println
!
incByConst(10) // => 15
//variable implícita it
def clos = { print it }
clos( "hi there" ) //prints "hi there"
@t3chfest 2014
@fatimacasau
Loopsy estructuras de control
if(){}else{}
!
while(){}
!
for(i in [1,2,3]){}
for(i=0;i<5;i++){}
for(i=0;j=10;i<10;i++;j--){}
for(i=0;…;i<10;…;n++){}
!
[1,2,3].each{ println it }
[“a”,“b”,“c”].eachWithIndex(){it,i-> println “$i : $it”}
!
3.times(){…}
5.upto(10){…}
10.1.downto(1.1){…}
0.step(10,2){…}
(1.. 5).each{…}
@t3chfest 2014
@fatimacasau
La ‘verdad’ en Groovy
@t3chfest 2014
Falso
Verdad
Null
new Object()
0
1
[]
[1,2,3]
[:]
[name:'fatima']
""
'abc'
@fatimacasau
Sobrecarga de Operadores
Operator
Method
a == b
a != b
a.equals(b) or
a.compareTo(b) == 0 **
!a.equals(b)
a <=> b
a.compareTo(b)
a > b
a.compareTo(b) > 0
a >= b
a.compareTo(b) >= 0
a < b
a.compareTo(b) < 0
No NullPointerException
@t3chfest 2014
@fatimacasau
Otros Operadores
!
Not operator (!)
!expresion
!
Spread operator (*.)
list*.attribute
!
Safe navigation operator (?.)
object?.attribute
!
Elvis operator (?:)
a = a?:""
@t3chfest 2014
@fatimacasau
Más…
!
Groovy SQL
!
sql.execute('insert into people (firstName, lastName) values (?,?)',
[firstName, lastName])
sql.eachRow('Select * from Person') {}
!
Dates
!
plus(), minus(), after(), before()
GregorianCalendar, String.format(String format, GregorianCalendar c)
!
Expresiones regulares
!
"potatoe" ==~ /potatoe/
!
Files
eachFile(), eachDir(), eachLine()…
@t3chfest 2014
@fatimacasau
Libros
!
@t3chfest 2014
@fatimacasau
!
Documentación oficial
!
Groovy Codehaus: http://groovy.codehaus.org/Documentation
!
!
Ejercicios
!
Groovy Koans:
https://github.com/cjudd/groovy_koans
!
!
@t3chfest 2014
@fatimacasau
¿Qué vamos a ver?
!
¿Qué es?
!
Principios y filosofía
!
Ventajas
!
Getting Started
!
Arquitectura
@t3chfest 2014
@fatimacasau
Plataforma para el desarrollo de aplicaciones web
JavaEE
!
Construido sobre un conjunto de frameworks
consolidados
!
Apoyado por una extensa librería de plugins
!
Soluciona todas las necesidades en el desarrollo de
aplicaciones web
!
Facilita el desarrollo de dichas aplicaciones
!
Utiliza GROOVY como lenguage
@t3chfest 2014
@fatimacasau
!
!
!
!
!
!
!
!
!
!
Tomcat y H2 incluidos para desarrollo rápido
@t3chfest 2014
@fatimacasau
Principios y filosofía
!
Patrón MVC (Modelo, Vista, Controlador)
!
CoC (Convention over Configuration)
Nombres descriptivos
Localización de ficheros que indican lo que son
Paradigma Coding by Convention de GROOVY
!
DRY (Don’t Repeat Yourself)
!
Inyección de dependencias
@t3chfest 2014
@fatimacasau
¿Por qué?
!
Menos código + menos errores = ++productividad
!
Fly reloading
!
Abstracción de los frameworks sobre los que se
asienta
!
Línea de comandos (run-app, war, install-plugin…)
!
Eliminación de XML’s gracias a CoC
!
Extensa librería de plugins
@t3chfest 2014
@fatimacasau
Getting Started
!
JDK
!
y JAVA_HOME
Download: http://grails.org/download
!
Terminal:
$ grails run-app
$ grails>
!
IDE’s:
!
Crear una aplicación
!
grails> create-app myApp
@t3chfest 2014
@fatimacasau
Comandos
grails [environment]* [command name]
!
Environments: dev, test, prod
!
Custom Environment: -Dgrails.env=myEnv
!
Comandos más usados:
run-app
war
clean
install-plugin
test-app
create-domain-class
create-controller
ceate-service
generate-all
@t3chfest 2014
@fatimacasau
Configuración
!
Config.groovy
!
Ejemplo: my.property.text = “hola”
Acceso: grailsApplication.config.my.property.text
BuildConfig.groovy
!
Datasource.groovy
!
Bootstrap.groovy
!
ApplicationResources.groovy
!
UrlMappings.groovy
@t3chfest 2014
@fatimacasau
Environments
!
grails.util.Environment
!
Custom environments
!
Detección de entornos:
!
environments {
production{
configureForDevelopment()
}
…
}
_______________________________________
import grails.util.Environment
!
switch (Environment.current) {
case Environment.DEVELOPMENT
configureForDevelopment()
break
…
}
@t3chfest 2014
@fatimacasau
Arquitectura MVC
!
!
Modelo - domains (GORM), services (Spring)
!
Vista – views & templates (gsp’s), TagLibs
!
Controlador – controllers & actions, filtros
@t3chfest 2014
@fatimacasau
GORM
!
Grails Object Relational Mapping (Hibernate 3)
!
Clases de dominio
getters y setters implícitos
constructores por defecto
eventos
!
Mapeos sin configuración
!
save(), delete(), list(), count()…
!
Constraints para validación
!
namedQueries
@t3chfest 2014
@fatimacasau
GORM
!
Mapeo de relaciones
One-To-One, One-To-Many, Many-To-Many
!
Finders dinámicos
findAllBy(), findBy(), findWhere()…
!
Para búsquedas más complejas
HQL, criterias, detachedCriterias, executeQueries
!
Ordenación y paginación
sort, order, max, offset …
@t3chfest 2014
@fatimacasau
Controllers
!
Actions
!
Closures
Métodos que reciben parámetros que vienen del formulario
Redirect de otros actions, mappings
Renders de vistas, templates, texto, json, xml
Command Objects
!
Objeto flash para enviar messages
!
Filtros que interceptan controllers, actions, views
@t3chfest 2014
@fatimacasau
Servicios
!
Spring
!
Inyección automática en:
!
Otros servicios
Controllers
Domains
TagLibs
@t3chfest 2014
class MyService {
def anyMethod(){
//…
}
}
_______________________________________
class MyController {
def myService
def anyAction(){
//…
myService.anyMethod(…)
//…
}
}
@fatimacasau
GSP’s
!
Groovy Server Pages
!
Templates, includes
Reutilización de código
!
Extensa librería de Tags sin configuración
g:each, g:if, g:form, g:formRemote,
g:formatDate, g:link, g:remoteLink,
g:remoteFunction, g:datePicker, g:set …
@t3chfest 2014
@fatimacasau
URL Mappings
!
class UrlMappings {
static mappings = {
!
"/product"(controller: "product", action: "list")
"/"(view: "/index") // map the root URL
"/product/$id"(controller: "product")
"403"(controller: "errors", action: "forbidden")
"/product/$id"(controller:"product") {
action = [GET:"show", PUT:"update", DELETE:"delete“,
POST:"save"]
}
name accountDetails: "/details/$acctNumber" {
controller = 'product' action = 'accountDetails'
}
}
}
@t3chfest 2014
@fatimacasau
Deployment
!
Command line
!
Para ejecutar
!
Puerto por defecto 8080: grails run-app
Especificar puerto: grails -Dserver.port=8090 run-app
!
Generar un war:
!
Entorno de producción por defecto: grails war
Especificar entorno: grails -Dgrails.env=myEnv war
@t3chfest 2014
@fatimacasau
Más…
!
jQuery
!
Ajax
!
Creación de Plugins
!
SpringSecurity Plugin
!
I18n
!
Testing con Spock integrado
!
Scripts: Gant
!
Injección de dependencias con
!
Spring: Spring DSL’s, resources.groovy
Scaffolding – No recomendado
@t3chfest 2014
@fatimacasau
Documentación de grails
!
http://grails.org/doc/latest/guide/
Listas de correo
!
http://grails.org/Mailing+lists
Grails Blog
!
http://grails.org/blog
Issue Tracker
!
http://jira.grails.org/browse/GRAILS
Grupo de Google – Grails en Castellano
http://groups.google.es/group/grailsencastellano
@t3chfest 2014
@fatimacasau
Eventos
@t3chfest 2014
@fatimacasau
@t3chfest 2014
@fatimacasau