Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Groovy&Grails: Cambia la forma de desarrollar tus aplicaciones web

Paradigma
February 28, 2014

Groovy&Grails: Cambia la forma de desarrollar tus aplicaciones web

Fátima Casaú, especializada en Groovy & Grails y en Metodologías Ágiles, nos explicó en esta charla cómo Groovy & Grails están revolucionando el desarrollo de aplicaciones web.

Paradigma

February 28, 2014
Tweet

More Decks by Paradigma

Other Decks in Technology

Transcript

  1. @fatimacasau
    Cambia la forma de desarrollar
    tus aplicaciones web
    Leganés, 6-7 Febrero 2014

    View Slide

  2. @fatimacasau
    ¿Qué vamos a ver?
    ¿Qué es?
    Características
    Getting Started
    Features + Código
    @t3chfest 2014

    View Slide

  3. @fatimacasau
    JVM
    Dinámico
    Tiempo de ejecución
    @CompileStatic (versión 2.x)
    Ruby, Phyton, Smaltalk
    @t3chfest 2014

    View Slide

  4. @fatimacasau
    Groovy ~ Java
    Sencillo + Expresivo = Coding by Convention
    GDK - Groovy Development Kit (JDK extension)
    Groovy ~ Superversión de Java
    @t3chfest 2014

    View Slide

  5. @fatimacasau
    Getting Started
    Descarga: http://groovy.codehaus.org/Download
    Terminal:
    Web Console: http://groovyconsole.appspot.com/
    IDEs:
    @t3chfest 2014
    $ groovysh $ groovyconsole

    View Slide

  6. @fatimacasau
    Features
    OOP
    Clases: Getters/Setters y constructores implícitos
    Closures
    Sobrecarga de operadores
    Soporte nativo para cadenas (Gstrings) y
    colecciones
    @t3chfest 2014

    View Slide

  7. @fatimacasau
    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
    HelloWorld.java

    View Slide

  8. @fatimacasau
    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
    HelloWorld.groovy

    View Slide

  9. @fatimacasau
    !
    class HelloWorld {
    def name
    def greet() {
    "Hello $name"
    }
    }
    !
    def helloWorld = new HelloWorld(name: "Groovy")
    println helloWorld.greet()
    @t3chfest 2014
    HelloWorld.groovy (groovy style)

    View Slide

  10. @fatimacasau
    @t3chfest 2014
    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"

    View Slide

  11. @fatimacasau
    @t3chfest 2014
    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']

    View Slide

  12. @fatimacasau
    @t3chfest 2014
    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']

    View Slide

  13. @fatimacasau
    @t3chfest 2014
    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

    View Slide

  14. @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

    View Slide

  15. @fatimacasau
    @t3chfest 2014
    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"

    View Slide

  16. @fatimacasau
    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
    Loopsy estructuras de control

    View Slide

  17. @fatimacasau
    La ‘verdad’ en Groovy
    @t3chfest 2014
    Falso Verdad
    Null new Object()
    0 1
    [] [1,2,3]
    [:] [name:'fatima']
    "" 'abc'

    View Slide

  18. @fatimacasau
    Sobrecarga de Operadores
    @t3chfest 2014
    Operator Method
    a == b a.equals(b) or
    a.compareTo(b) == 0 **
    a != b !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

    View Slide

  19. @fatimacasau
    Otros Operadores
    Not operator (!)
    !expresión
    Spread operator (*.)
    list*.attribute
    Safe navigation operator (?.)
    object?.attribute
    Elvis operator (?:)
    a = a?:""
    @t3chfest 2014

    View Slide

  20. @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

    View Slide

  21. @fatimacasau
    Libros
    !
    @t3chfest 2014

    View Slide

  22. @fatimacasau
    !
    Documentación oficial
    !
    Groovy Codehaus: http://groovy.codehaus.org/Documentation
    !
    !
    Ejercicios
    !
    Groovy Koans:
    https://github.com/cjudd/groovy_koans
    !
    !
    @t3chfest 2014

    View Slide

  23. @fatimacasau
    ¿Qué vamos a ver?
    ¿Qué es?
    Principios y filosofía
    Ventajas
    Getting Started
    Arquitectura
    @t3chfest 2014

    View Slide

  24. 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
    @fatimacasau
    @t3chfest 2014

    View Slide

  25. !
    !
    !
    !
    !
    !
    !
    !
    !
    !
    Tomcat y H2 incluidos para desarrollo rápido
    @fatimacasau
    @t3chfest 2014

    View Slide

  26. 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
    @fatimacasau
    @t3chfest 2014

    View Slide

  27. ¿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
    @fatimacasau
    @t3chfest 2014

    View Slide

  28. Getting Started
    JDK y JAVA_HOME
    Download: http://grails.org/download
    Terminal:
    IDE’s:
    Crear una aplicación
    grails> create-app myApp
    $ grails run-app $ grails>
    @fatimacasau
    @t3chfest 2014

    View Slide

  29. Comandos
    !
    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
    grails [environment]* [command name]
    @fatimacasau
    @t3chfest 2014

    View Slide

  30. 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
    @fatimacasau
    @t3chfest 2014

    View Slide

  31. 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

    }
    @fatimacasau
    @t3chfest 2014

    View Slide

  32. Arquitectura MVC
    Modelo - domains (GORM), services (Spring)
    Vista – views & templates (gsp’s), TagLibs
    Controlador – controllers & actions, filtros
    @fatimacasau
    @t3chfest 2014

    View Slide

  33. 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
    @fatimacasau
    @t3chfest 2014

    View Slide

  34. 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 …
    @fatimacasau
    @t3chfest 2014

    View Slide

  35. 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
    @fatimacasau
    @t3chfest 2014

    View Slide

  36. Servicios
    !
    Spring
    !
    Inyección automática en:
    !
    Otros servicios
    Controllers
    Domains
    TagLibs
    class MyService {
    def anyMethod(){
    //…
    }
    }
    _______________________________________
    class MyController {
    def myService
    def anyAction(){
    //…
    myService.anyMethod(…)
    //…
    }
    }
    @fatimacasau
    @t3chfest 2014

    View Slide

  37. 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 …
    @fatimacasau
    @t3chfest 2014

    View Slide

  38. 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'
    }
    }
    }
    @fatimacasau
    @t3chfest 2014

    View Slide

  39. 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
    @fatimacasau
    @t3chfest 2014

    View Slide

  40. 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
    @fatimacasau
    @t3chfest 2014

    View Slide

  41. 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
    @fatimacasau
    @t3chfest 2014

    View Slide

  42. Eventos
    @fatimacasau
    @t3chfest 2014

    View Slide

  43. @fatimacasau
    @t3chfest 2014
    https://github.com/fatimacasau/blog-example-grails-app

    View Slide