Last active
December 10, 2015 21:48
-
-
Save HiroNakamura/4497100 to your computer and use it in GitHub Desktop.
Ejemplos de Groovy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //http://codemonkeyjunior.blogspot.mx/ | |
| //10 | |
| /* | |
| public class Groov{ | |
| static main(args) { | |
| println "valor: "+UserStatus.ACTIVE.getStatusCode(); | |
| } | |
| } | |
| enum UserStatus { | |
| PENDING("P"), ACTIVE("A"), INACTIVE("I"), DELETED("D"); | |
| private String statusCode; | |
| private UserStatus(String s) { | |
| statusCode = s; | |
| } | |
| public String getStatusCode() { | |
| return statusCode; | |
| } | |
| } | |
| */ | |
| //9 | |
| /* | |
| public class Groov{ | |
| Servicio servicio | |
| public Groov(Servicio serv){ | |
| servicio=serv | |
| } | |
| public void activa(){ | |
| servicio.ver() | |
| } | |
| static main(args) { | |
| new Groov(new Esfera(2.9)).activa() | |
| } | |
| } | |
| abstract class Servicio{ | |
| public abstract double volumen(); | |
| public abstract void ver(); | |
| } | |
| class Esfera extends Servicio{ | |
| private double radio; | |
| public Esfera(double r){ | |
| radio=r; | |
| } | |
| @Override | |
| public double volumen(){ | |
| return (4*Math.PI*Math.pow(radio,3))/3; | |
| } | |
| @Override | |
| public void ver(){ | |
| println "volumen obtenido: "+volumen(); | |
| } | |
| } | |
| */ | |
| //8 http://groovy.codehaus.org/groovy-jdk/ | |
| /* | |
| public class Groov{ | |
| static main(args) { | |
| println "nombre de la clase: "+new Groov().getClass().getName() | |
| Class<Groov> clase= Groov.class | |
| println clase | |
| //en Scala: | |
| //val stringClass = classOf[String] | |
| //println(stringClass) | |
| } | |
| } | |
| */ | |
| //7 | |
| /* | |
| class Groov{ | |
| static main(args) { | |
| try{ | |
| def num="123" | |
| int entero=Integer.parseInt(num) | |
| }catch(e){ | |
| println "error: "+e | |
| } | |
| } | |
| } | |
| */ | |
| //6 | |
| /* | |
| class Gato{ | |
| def foo(){} | |
| } | |
| gato = new Gato() | |
| assert gato.metaClass.respondsTo("maulla").isEmpty() | |
| gato.metaClass."maulla" = {-> "Miauuuu!!!"} | |
| assert !gato.metaClass.respondsTo(gato, "maulla").isEmpty() | |
| println gato.maulla() | |
| gato.foo() | |
| gato.metaClass."foo" = {-> "fooMensaje!!!"} // Esto es una fregonería :) | |
| println gato.foo() | |
| */ | |
| //5 rodrigo salado anaya | |
| /* | |
| class Perro{ | |
| def aulla(){def sonido = 'Guauuuu!!!'} | |
| } | |
| class Lobo{ | |
| def aulla(){def sonido = 'Auuuuuu!!!'} | |
| } | |
| class Gato{ | |
| def maulla(){def sonido = 'Miauuuu!!!'} | |
| } | |
| animales = [new Perro(), new Lobo(), new Gato()] | |
| animales.each { | |
| println it.metaClass.respondsTo(it, "aulla").isEmpty() == false? | |
| it.aulla(): | |
| it.maulla() | |
| }; | |
| */ | |
| /* | |
| animales.each { //El gato truena | |
| println it.aulla() | |
| }; | |
| */ | |
| //4 | |
| /* | |
| rodrigo salado anaya | |
| listaTokens = [] | |
| funciones = ["System","out","println","imprime","mayusculas","==","=","+","-",".","(",")","'"] | |
| codigo = """a = 3; | |
| b = 14; | |
| r =a+b- 23+ 45; | |
| imprime r; | |
| System.out.println('hola');""" | |
| def escanea(String codigo){ | |
| codigo.split(";").each({sentencia -> separaFunciones sentencia}) | |
| listaTokens.each({tokens -> tokens.each({token -> print "[" + token + "]"}) println ""}) | |
| } | |
| def separaFunciones(String sentencia){ | |
| funciones.each({funcion -> sentencia = sentencia.replace(funcion, " " + funcion + " ")}); | |
| listaTokens.add sentencia.replaceAll("\\s+", " ").trim().split(" ") | |
| } | |
| escanea codigo | |
| */ | |
| //4 | |
| /* | |
| import java.util.Scanner | |
| public class Groov{ | |
| static main(args) { | |
| Scanner tec=new Scanner(System.in) | |
| def entrada="" | |
| println "Introduce dato: " | |
| entrada=tec.nextLine() | |
| println entrada.substring(0,3) | |
| def lista=[] | |
| def otra=[] | |
| for(int i=0;i<entrada.length();i++){ | |
| def c= entrada.charAt(i) | |
| String cad=String.valueOf(c) | |
| lista[i]=cad | |
| otra[i]=i | |
| } | |
| println otra | |
| println lista | |
| } | |
| } | |
| */ | |
| //3 | |
| /* | |
| public class Groov{ | |
| def num1=0 | |
| def num2=0 | |
| public String toString(){ | |
| "una simple cadena" | |
| } | |
| public int sum(){ | |
| num1+num2 | |
| } | |
| static main(args) { | |
| println new Groov().toString() | |
| println "suma: "+new Groov(num1: 21,num2: 32).sum() | |
| } | |
| } | |
| */ | |
| //2 | |
| /* | |
| class Groov{ | |
| static main(args) { | |
| getCaracteres("Fernando") | |
| } | |
| static void getCaracteres(String palabra){ | |
| char[] caracteres = new char[palabra.length()]; | |
| for (int i = 0; i < palabra.length(); i++) { | |
| caracteres[i] = (char)palabra.charAt(i); | |
| println caracteres | |
| } | |
| } | |
| } | |
| */ | |
| //1 | |
| /* | |
| class Groov{ | |
| static main(args) { | |
| java.util.Random rnd=new java.util.Random() | |
| int cont=0 | |
| def lista=[] | |
| for(char c='a';c <= 'z';c++){ | |
| println c | |
| lista[cont]=(char)c | |
| cont++ | |
| } | |
| println "no elementos $cont" | |
| println "lista ${lista}" | |
| } | |
| } | |
| */ | |
| //50 | |
| /* | |
| def acepta={func,param-> | |
| func(param) | |
| } | |
| def msg={it-> | |
| println "Hola ${it}" | |
| } | |
| acepta(msg,"Fernando") | |
| */ | |
| //49 | |
| /* | |
| def fernando="fernando" | |
| def camila=null | |
| println fernando ?: "daniel" | |
| println camila ?: "camila" | |
| */ | |
| //48 | |
| /* | |
| //http://groovyconsole.appspot.com/ | |
| def sum(int... numbers) { | |
| def total = 0 | |
| numbers.each { total += it } | |
| total | |
| } | |
| assert sum(1,3,5,7,9) == 25 | |
| */ | |
| //47 | |
| /* | |
| def name = 'GROOVY' | |
| def substring = name[1..-1] | |
| assert substring == 'ROOVY' | |
| */ | |
| //46 | |
| /* | |
| def list = [0, 1, 2, 3, 4] | |
| def total = 0 | |
| list.each { | |
| total += it | |
| } | |
| assert total == 10 | |
| */ | |
| //45 | |
| /* | |
| def list = [0, 1, 2, 3, 4] | |
| def total = 0 | |
| for (x in list) { | |
| total += x | |
| } | |
| assert total == 10 | |
| */ | |
| //44 | |
| /* | |
| class Person { | |
| String first | |
| String last | |
| } | |
| Person.metaClass.properties.each { p -> | |
| println "${p.name} = ${p.type}" | |
| } | |
| */ | |
| //43 | |
| /* | |
| for(arg in args) | |
| { | |
| println arg | |
| } | |
| */ | |
| //42 | |
| /* | |
| def script = ''' | |
| def first = """${data.first}""" | |
| def last = """${data.last}""" | |
| return first + ' ' + last | |
| ''' | |
| def data = [first:'Montgomery',last:'Scott'] | |
| def shell = new GroovyShell( new Binding(data:data) ) | |
| def result = shell.evaluate(script) | |
| println result | |
| */ | |
| //41 | |
| /* | |
| def script = ''' | |
| def x = 31 | |
| def y = 1 | |
| return x * y | |
| ''' | |
| def shell = new GroovyShell() | |
| def result = shell.evaluate(script) | |
| println result | |
| */ | |
| //40 | |
| /* | |
| def numeros=[60,5,32,0,21,200,98,2,5,33,32] | |
| println numeros | |
| println numeros.sort() | |
| println numeros.unique() | |
| */ | |
| //39 | |
| /* | |
| def numeros=[45,6,0,32,21,2] | |
| println numeros.sort() | |
| */ | |
| //38 | |
| /* | |
| def numeros=[1,2,3] | |
| def result= numeros == [1,2,3] ? "pertenecen" : "no pertenecen" | |
| println result | |
| assert numeros == [1,2,3] | |
| */ | |
| //37 | |
| //http://www.groovyexamples.org/ | |
| /* | |
| class Animal { } | |
| class Dog extends Animal { } | |
| class Cat extends Animal { } | |
| dog = new Dog() | |
| cat = new Cat() | |
| assert dog in Dog | |
| assert dog in Animal | |
| assert cat in Cat | |
| assert cat in Animal | |
| */ | |
| //36 | |
| /* | |
| def map = [name:'Kraken',size:'Huge'] | |
| assert map.containsKey('size') | |
| assert !map.containsKey('birthDate') | |
| */ | |
| //35 | |
| /* | |
| // Create a simple class | |
| class Person { | |
| def first | |
| def last | |
| } | |
| // Create the mixin class | |
| class PersonMixin { | |
| def getFullName() { | |
| "${first} ${last}" | |
| } | |
| } | |
| // Apply the mixin | |
| Person.mixin PersonMixin | |
| def person = new Person(first:'Hugh',last:'Jackman') | |
| assert 'Hugh' == person.first | |
| assert 'Jackman' == person.last | |
| assert 'Hugh Jackman' == person.fullName | |
| */ | |
| //34 | |
| /* | |
| def message = 'hello' | |
| println message.hashCode() | |
| */ | |
| //33 | |
| /* | |
| def list = [1,3,5] | |
| assert list.contains(3) | |
| assert !list.contains(4) | |
| assert 3 in list | |
| assert !(4 in list) | |
| */ | |
| //32 | |
| /* | |
| def num1 = "12345" | |
| def num2 = "123.45" | |
| assert num1.isInteger() | |
| assert !num2.isInteger() | |
| */ | |
| //31 | |
| /* | |
| def listA = [1,2,3] | |
| def listB = [4,5,6] | |
| listA.addAll(listB) | |
| assert listA == [1,2,3,4,5,6] | |
| */ | |
| //30 | |
| //http://kunaldabir.blogspot.mx/2011/12/groovy-substring.html | |
| /* | |
| println "teststring"[2..4] | |
| */ | |
| //29 | |
| //http://www.groovyexamples.org/tag/eachline/ | |
| /* | |
| inicio() | |
| def inicio(){ | |
| println "cmd /c help".execute().text | |
| } | |
| */ | |
| //28 | |
| /* | |
| def url = new URL("http://www.google.com.mx/") | |
| url.eachLine{line-> | |
| println line | |
| } | |
| */ | |
| //27 | |
| /* | |
| def dir = new File(".") | |
| dir.eachFile{file-> | |
| println file.isDirectory() ? "DIR: ${file}" : "FILE: ${file}" | |
| } | |
| */ | |
| //26 | |
| /* | |
| def dir = new File(".") | |
| dir.eachFile{file-> | |
| if(file.isFile()){ | |
| println "FILE: ${file}" | |
| }else if(file.isDirectory()){ | |
| println "DIR: ${file}" | |
| }else{ | |
| println "Uh, I'm not sure what it is..." | |
| } | |
| } | |
| */ | |
| //25 | |
| /* | |
| def dir = new File(".") | |
| dir.eachFile{file-> | |
| println file | |
| } | |
| */ | |
| //24 | |
| /* | |
| enum DAY{ | |
| MONDAY, TUESDAY, WEDNESDAY, THURSDAY, | |
| FRIDAY, SATURDAY, SUNDAY | |
| } | |
| DAY.each{ | |
| println it | |
| } | |
| (DAY.MONDAY..DAY.FRIDAY).each{ | |
| println it | |
| } | |
| */ | |
| //23 | |
| /* | |
| def today = new Date() | |
| def nextWeek = today + 7 | |
| (today..nextWeek).each{ | |
| println it | |
| } | |
| */ | |
| //22 | |
| /* | |
| def range = 5..10 | |
| range.each{ | |
| println it | |
| } | |
| */ | |
| //21 | |
| /* | |
| def name = "Jane Smith" | |
| println "replace spaces" | |
| name.each{ | |
| if(it == " "){ | |
| print "_" | |
| }else{ | |
| print it | |
| } | |
| } | |
| */ | |
| //20 | |
| /* | |
| def name = "Jane Smith" | |
| name.each{letter-> | |
| println letter | |
| } | |
| */ | |
| //19 | |
| /* | |
| def list = ["Java", "Groovy", "JavaScript"] | |
| println list.class | |
| // java.util.ArrayList | |
| def map = ["Java":"server", "Groovy":"server", "JavaScript":"web"] | |
| println map.class | |
| // null | |
| map.class = "I am a map element" | |
| println map.class | |
| // I am a map element | |
| println map.getClass() | |
| // class java.util.LinkedHashMap | |
| */ | |
| //18 | |
| /* | |
| def map = ["Java":"server", "Groovy":"server", "JavaScript":"web"] | |
| println map.get("Java") | |
| println map.Java | |
| */ | |
| //17 | |
| /* | |
| def mapa=["jug01":"Fernando","jug02":"Pepe","jug03":"Camila"] | |
| mapa.each{k,v-> | |
| println "llave: $k , valor: $v" | |
| } | |
| */ | |
| //16 | |
| /* | |
| new FileReader('C:/Users/fernando/Documents/Ejemplos/archivo.dat').eachLine(4){line, number-> | |
| println "$number $line" | |
| } | |
| */ | |
| //15 | |
| /* | |
| def archivo=new File("archivo.dat") | |
| archivo.write("Un archivo por cada \nlinea del \nscript") | |
| archivo.eachLine(){ lines-> | |
| println "$lines" | |
| } | |
| */ | |
| //14 | |
| /* | |
| class Ejemplo{ | |
| def nombre="" | |
| def edad=0 | |
| } | |
| static main(args) { | |
| def obj=new Ejemplo(nombre:"Fernando",edad:31) | |
| println "nombre ${obj.nombre} y edad ${obj.edad}" | |
| } | |
| */ | |
| //13 | |
| /* | |
| import javax.swing.JOptionPane as jP | |
| def nombre=jP.showInputDialog("Nombre:") | |
| println "nombre: $nombre" | |
| jP.showMessageDialog(null,"Hola "+nombre.toString()) | |
| */ | |
| //12 | |
| /* | |
| def clos1={ | |
| -> "closure 1" | |
| } | |
| def clos2={ | |
| -> "$clos1" | |
| } | |
| println "how deep is deep? $clos2" | |
| println "how deep is deep? ${{-> "deeper and ${{-> "clos1"}}"}}" | |
| */ | |
| //11 | |
| /* | |
| def x=9 | |
| def y=3 | |
| assert 12==(x+y) | |
| */ | |
| //10 | |
| /* | |
| def cad="Cadena" | |
| def fecha="Hoy es ${new Date()}" | |
| def suma=cad+fecha | |
| assert cad instanceof String | |
| assert fecha instanceof GString | |
| assert suma instanceof String | |
| */ | |
| //9 | |
| /* | |
| class Greet { | |
| def name | |
| Greet(who) { name = who[0].toUpperCase() + | |
| who[1..-1] } | |
| def salute() { println "hola $name!" } | |
| } | |
| g = new Greet('Fernando') // create object | |
| g.salute() | |
| */ | |
| //8 | |
| //http://groovy.codehaus.org/Using+Enums | |
| /* | |
| enum Coin { | |
| penny(1), nickel(5), dime(10), quarter(25) | |
| Coin(int value) { this.value = value } | |
| private final int value | |
| public int value() { return value } | |
| } | |
| assert Coin.values().size() == 4 | |
| def pocketMoney = 2 * Coin.quarter.value() + 5 * Coin.dime.value() | |
| assert pocketMoney == 100 | |
| // another way to do above | |
| def coins = [ Coin.quarter ] * 2 + [ Coin.dime ] * 5 | |
| println coins // => [ quarter, quarter, dime, dime, dime, dime, dime ] | |
| println coins.sum{ it.value() } // => 100 | |
| */ | |
| //7 | |
| /* | |
| enum TipoDocumento{ | |
| DOC,DOCX,PDF,XML,TXT | |
| } | |
| def determinarTipo(TipoDocumento tipoDocumento){ | |
| switch(tipoDocumento) { | |
| case tipoDocumento.PDF: | |
| println "es un documento PDF" | |
| break | |
| case tipoDocumento.XML: | |
| println "es un documento XML" | |
| break | |
| default: | |
| println "un documento cualquiera" | |
| break | |
| } | |
| } | |
| determinarTipo(TipoDocumento.PDF) | |
| determinarTipo(TipoDocumento.XML) | |
| determinarTipo(TipoDocumento.TXT) | |
| */ | |
| //6 | |
| /* | |
| import groovy.sql.* | |
| import groovy.grape.Grape | |
| static void main(String ... args)throws Exception { | |
| if(args.size()==0){ | |
| throw new Exception("error: debes introducir datos") | |
| }else{ | |
| def usuario=args[0] | |
| def clave=args[1] | |
| println "usuario: "+args[0] | |
| inicio(usuario,clave) | |
| } | |
| } | |
| @Grapes([ | |
| @Grab('mysql:mysql-connector-java:5.1.12'), | |
| @GrabConfig(systemClassLoader=true) | |
| ]) | |
| def inicio(usuario,clave){ | |
| println "bienvenido: ${usuario}" | |
| Sql sql=Sql.newInstance("jdbc:mysql://localhost/agenda",usuario,clave,"com.mysql.jdbc.Driver") | |
| sql.eachRow("select * from usuarios") { | |
| println "Usuarios de la base: ${it.nomb_us}" | |
| } | |
| } | |
| */ | |
| //5 | |
| /* | |
| static main(args) { | |
| def mapa=["jug01":"Fer","jug02":"Camila","jug03":"Pepe"] | |
| println "mapa: "+mapa | |
| mapa.each(){ | |
| println "llave: "+it.key+"- valor:"+it.value | |
| } | |
| } | |
| */ | |
| //4 | |
| //http://lineadecodigo.com/groovy/crear-un-xml-con-groovy/ | |
| /* | |
| def sw = new StringWriter() | |
| def xml = new groovy.xml.MarkupBuilder(sw) | |
| xml.libros{ | |
| libro(autor:"Cervantes","El Quijote") | |
| libro(autor:"Homero","La Iliada") | |
| libro(autor:"Camilo Jose Cela","Viaje a la Alcarria") | |
| libro(autor:"Camilo Jose Cela","La Colmena") | |
| libro(autor:"Valerio Massimo Manfredi","Talos de Esparta") | |
| libro(autor:"Valerio Massimo Manfredi","La òltima Legin") | |
| } | |
| println sw | |
| */ | |
| //3 | |
| //http://kerflyn.wordpress.com/2010/06/25/list-comprehension-in-groovy/ | |
| //L = [x**2 for x in range(1, 11) if x % 2 == 0] #en python | |
| /* | |
| assert 0..2==[0,1,2] | |
| assert (0..2).collect{it**2}==[0,1,4] | |
| def lista=[0,1,2] | |
| lista=(0..2).findAll({it%2==0}).collect{it**2} | |
| println lista | |
| lista=(0..2).findAll({x -> x%2==0}).collect{x -> x**2} | |
| println lista | |
| //println((0..2).collect { randomString(3) }) | |
| //M = dict([(C[i], i) for i in range(len(C))]) | |
| //assert (1..5).inject(0) { oldValue, element -> element + oldValue } == 15 | |
| //(1..C.size()).inject([:]) { m, i -> m[C[i-1]] = i; m } | |
| */ | |
| //2 | |
| /* | |
| def lista=[new Date(),"Fernando",45,0.00999] | |
| lista.each(){ | |
| println "${it}" | |
| } | |
| */ | |
| //1 | |
| /* | |
| static main(args) { | |
| new Class03("Fernando").datos("Fernando",31,54,155).ver() | |
| } | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment