35
Introducción a http://twitter.com/ highwayman [email protected] http://linkd.in/ davidsantamaria por David Santamaria

Introducción a [email protected] por David Santamaria

Embed Size (px)

Citation preview

Page 1: Introducción a  d.highwayman@gmail.com  por David Santamaria

Introducción a

http://twitter.com/[email protected]://linkd.in/davidsantamaria

por David Santamaria

Page 2: Introducción a  d.highwayman@gmail.com  por David Santamaria

Agenda

• ¿Que es Groovy?

• ¿Por que Groovy?

• Goodies.

• Mejoras respecto a Java.

• Comenzamos.

• Lenguaje Basicos.

Page 3: Introducción a  d.highwayman@gmail.com  por David Santamaria

¿Qué es Groovy?

Groovy es un lenguaje Dinamico para la JVM que permite el uso de caracteristicas de otros lenguajes como Ruby para la comunidad Java.

http://groovy.codehaus.org/

Page 4: Introducción a  d.highwayman@gmail.com  por David Santamaria

¿Qué mas es Groovy?

Groovy también es ...

agil, dinamico, compacto, sin curva de aprendizaje, con DSL, soporte de scripts, Totalmente OO, Integrado con Java (Sintaxis Java y Produce Bytecode).

Page 5: Introducción a  d.highwayman@gmail.com  por David Santamaria

¿Qué es Groovy? (para los developers)

Groovy es un "superset" de Java.Groovy = Java - Boiler Plate Code                + Dynamic Typing                + Closures                + DSL                + Builders                + Metaprograming                + GDK

                - Errores de compilacion                - Ligeramente mas lento

Page 6: Introducción a  d.highwayman@gmail.com  por David Santamaria

¿Por que Groovy?

• Java Platform!o Se ejecuta en la JVM (si hay una JVM puedes ejecutar Groovy).o Usa librerias Java.o Embebida en Aplicaciones de Escritorio Java.o Embebida en aplicaciones J2EEo Test con JUnito Debug con Eclipse, IntelliJ, Netbeans.o Code Coverage con Cobertura.

• No requiere aprender nuevas APIS (Jython, JRuby,...)• Rhino es interesante pero es JavaScript :)

Page 7: Introducción a  d.highwayman@gmail.com  por David Santamaria

Goodies

• Tipado Dinamico y estatico.• Totalmente orientado a objetos. (Todo es un Objeto)• Closures.• Sobrecarga de operadores.• Multimethods.• Declaracion Literal de Listas (Arrays), maps, ranges, y

expresiones regulares. (Soporte Nativo!)• Metaprogramación.• Y Mas...

o GPath.o Builders.o Groovy Beans.

Page 8: Introducción a  d.highwayman@gmail.com  por David Santamaria

HelloWorld.java

public class HelloWorld {public static void main(String[] args){HelloWorld hw = new HelloWorld();hw.setNombre("Groovy");System.out.println(hw.saluda());}

String nombre;public String getNombre() {  return nombre;  }public void setNombre(String nombre) {              this.nombre = nombre;         }

public String saluda(){ return "Hola " + nombre;}}

Page 9: Introducción a  d.highwayman@gmail.com  por David Santamaria

HelloWorld.groovy

public class HelloWorld {public static void main(String[] args){HelloWorld hw = new HelloWorld();hw.setNombre("Groovy");System.out.println(hw.saluda());}

String nombre;public String getNombre() {  return nombre;  }public void setNombre(String nombre) {              this.nombre = nombre;         }

public String saluda(){ return "Hola " + nombre;}}

Page 10: Introducción a  d.highwayman@gmail.com  por David Santamaria

HelloWorld.groovy

public class HelloWorld {public static void main(String[] args){HelloWorld hw = new HelloWorld()hw.setNombre("Groovy")System.out.println(hw.saluda())}

String nombre;public String getNombre() {  return nombre }public void setNombre(String nombre) {              this.nombre = nombre        }

public String saluda(){ return "Hola " + nombre}}

; opcionales!

Page 11: Introducción a  d.highwayman@gmail.com  por David Santamaria

HelloWorld.groovy

class HelloWorld {static void main(String[] args){HelloWorld hw = new HelloWorld()hw.setNombre("Groovy")System.out.println(hw.saluda())}

String nombre;String getNombre() {  return nombre }void setNombre(String nombre) {              this.nombre = nombre        }

String saluda(){ return "Hola " + nombre}}

public por defecto!

Page 12: Introducción a  d.highwayman@gmail.com  por David Santamaria

HelloWorld.groovy

class HelloWorld {static void main(String[] args){HelloWorld hw = new HelloWorld()hw.nombre("Groovy")System.out.println(hw.saluda())}

String nombre;

String saluda(){ return "Hola " + nombre}}

getters and setters autogenerados!

Page 13: Introducción a  d.highwayman@gmail.com  por David Santamaria

HelloWorld.groovy

class HelloWorld {static void main(String[] args){HelloWorld hw = new HelloWorld()hw.nombre("Groovy")System.out.println(hw.saluda())}

String nombre;

String saluda(){ "Hola " + nombre}}

return opcional!

Page 14: Introducción a  d.highwayman@gmail.com  por David Santamaria

HelloWorld.groovy

class HelloWorld {static void main(String[] args){HelloWorld hw = new HelloWorld()hw.nombre("Groovy")System.out.println(hw.saluda())}

def nombre;

def saluda(){ "Hola " + nombre}}

Tipado Dinamico!

Page 15: Introducción a  d.highwayman@gmail.com  por David Santamaria

HelloWorld.groovy

class HelloWorld {static void main(String[] args){HelloWorld hw = new HelloWorld()hw.nombre("Groovy")println(hw.saluda())}

def nombre;

def saluda(){ "Hola " + nombre}}

Incluido por defecto:• java.io.*• java.lang.*• java.math.BigDecimal• java.math.BigInteger• java.net.*• java.util.*• groovy.lang.*• groovy.util.*

Page 16: Introducción a  d.highwayman@gmail.com  por David Santamaria

HelloWorld.groovy

class HelloWorld {static void main(String[] args){HelloWorld hw = new HelloWorld()hw.nombre("Groovy")println(hw.saluda())}

def nombre

def saluda(){ "Hola ${nombre}" }}

GStrings!

Page 17: Introducción a  d.highwayman@gmail.com  por David Santamaria

HelloWorld.groovy

HelloWorld hw = new HelloWorld()hw.nombre("Groovy")println(hw.saluda())

class HelloWorld {def nombredef saluda(){ "Hola ${nombre}" }}

Declaracion de clases opcional para Scripts!

Page 18: Introducción a  d.highwayman@gmail.com  por David Santamaria

HelloWorld.groovy

HelloWorld hw = new HelloWorld()hw.nombre "Groovy"println hw.saluda()

class HelloWorld {def nombredef saluda(){ "Hola ${nombre}" }}

Parentesis opcionales en la mayoria de casos.

Page 19: Introducción a  d.highwayman@gmail.com  por David Santamaria

HelloWorld.java

public class HelloWorld {public static void main(String[] args){HelloWorld hw = new HelloWorld();hw.setNombre("Groovy");System.out.println(hw.saluda());}

String nombre;public String getNombre() {  return nombre;  }public void setNombre(String nombre) {              this.nombre = nombre;         }

public String saluda(){ return "Hola " + nombre;}}

Page 20: Introducción a  d.highwayman@gmail.com  por David Santamaria

HelloWorld.groovy

HelloWorld hw = new HelloWorld()hw.nombre "Groovy"println hw.saluda()

class HelloWorld {def nombredef saluda(){ "Hola ${nombre}" }}

Page 21: Introducción a  d.highwayman@gmail.com  por David Santamaria

Comenzamos!

• Descargamos la ultima version de Groovyhttp://groovy.codehaus.org/• Descomprimimos en un directorio.• Añadimos la variable de entorno GROOVY_HOME.

Y %GROOVY_HOME%/bin a la variable PATH.• Escribimos groovy -version

Page 22: Introducción a  d.highwayman@gmail.com  por David Santamaria

Comenzamos! (II)

groovyconsoleprintln "Hola Mundo!"Ctrl + R

Page 23: Introducción a  d.highwayman@gmail.com  por David Santamaria

Lenguaje: Strings and GStrings.

• Comillas Simples para Strings.

• Comillas dobles para GStrings: Son como Strings pero soportan expresiones: ${expression}.

• Strings multi-linea.

Page 24: Introducción a  d.highwayman@gmail.com  por David Santamaria

Lenguaje: Strings and GStrings.

• Slashy Strings: Como GStrings  con soporte para Expresiones Regulares.

• - Muchas mas operaciones...

http://groovy.codehaus.org/Strings+and+GStringhttp://groovy.codehaus.org/JN1525-Strings

Page 25: Introducción a  d.highwayman@gmail.com  por David Santamaria

Lenguaje: Numbers

Java:• Java soporta tipos primitivos y Objetos.• Tiene Wrappers para permitir la conversion.• Java 5+ hay autoboxing /autoUnboxing.

Groovy:• Todo es un objeto en el lenguaje.

o El realiza el autoboxing cuando es mezclado con Java.• BigDecimal es el tipo por defecto (excepto Integers).• Sobrecarga de operadores.

http://groovy.codehaus.org/JN0515-Integershttp://groovy.codehaus.org/JN0525-Decimalshttp://groovy.codehaus.org/JN0535-Floats

Page 26: Introducción a  d.highwayman@gmail.com  por David Santamaria

Lenguaje: Numbers

Page 27: Introducción a  d.highwayman@gmail.com  por David Santamaria

Lenguaje: Collections

Map map = new HashMap()map.put("nombre", "David")map.put("edad",30);

map.get("valor");

List list = new ArrayList(    Arrays.asList(    "primero", "segundo"));

list.add("tercero");

def map = [nombre: "David", edad:30]

map.valormap["valor"]

def list = ["primero","segundo"]

list << "tercero"

Syntaxis Nativa en colecciones:

Java: Groovy:

Page 28: Introducción a  d.highwayman@gmail.com  por David Santamaria

Lenguaje: Bucles

for (String s: list) {    System.out.println(s);}

for (int n=1; n<6; n++){    System.out.println(n);}

list.each {    println it}

l.upto 5,{    println it}

Java: Groovy:

Page 29: Introducción a  d.highwayman@gmail.com  por David Santamaria

Lenguaje: GDK

import java.io.*;public classReadFile {    public static void main(String[] args){        try{            BufferedReader br = new BufferedReader(                new FileReader(                    new File("file.txt")));            String line = null;            while ((line = br.readLine()) != null) {                System.out.println(line);            }        } catch(IOException e) {            e.printStackTrace();        }}

new File(file.txt).echLine { String line ->    println line}

Java:

Groovy:

Page 30: Introducción a  d.highwayman@gmail.com  por David Santamaria

Lenguaje: Closures

//sumadef sum = 0[1, 2, 3].each { item -> sum += item }println "Total ${sum}"

// listardef text = customers.collect{ item ->     item.name }.join(",")

// llamar a un Closuredef c = { name -> println "Hola ${name}"}c("David")

Definición de Closures

Page 31: Introducción a  d.highwayman@gmail.com  por David Santamaria

Lenguaje: Closures

//Simple Loops5.times { print it }-> 01234

//Strings'dog'.each { c -> println c } -> d -> o-> g

//Lists and Arrays[1,2,'dog'].each { print it }-> 12dog

//Maps['rod':33, 'james':35].each {    print "${it.key}=${it.value} " }-> james=35 rod=33

Iteración en Closures

Page 32: Introducción a  d.highwayman@gmail.com  por David Santamaria

Lenguaje: GDK

• Stringo contains(), count(), execute(), padLeft(),

center(), padRight(), reverse(), tokenize(), each(), etc.• Collection

o count(), collect(), join(), each(), reverseEach(), find/All(), min(), max(), inject(), sort(), etc.

• Fileo eachFile(), eachLine(), withPrintWriter(), write(), getText(),

etc.

Page 33: Introducción a  d.highwayman@gmail.com  por David Santamaria

Lenguaje: MarkupBuilder

import groovy.xml.*def page = new MarkupBuilder()page.html {    head { title 'Hola' }    body{        ul {            1.upto 5, { li "Mundo ${it}"}        }    }}

<html>  <head>    <title>Hola</title>  </head>  <body>    <ul>      <li>Mundo 1</li>      <li>Mundo 2</li>      <li>Mundo 3</li>      <li>Mundo 4</li>      <li>Mundo 5</li>    </ul>  </body></html>

Page 34: Introducción a  d.highwayman@gmail.com  por David Santamaria

Mas Groovy

- Groovy Doc:    http://groovy.codehaus.org/- Groovy Koans:    https://github.com/cjudd/groovy_koans

Page 35: Introducción a  d.highwayman@gmail.com  por David Santamaria

 

Preguntas...