De Groovy …​ e Sancho Panza

Antón R. Yuste - @antonmry - OptareSolutions & VigoJUG

E ti, de quen ves sendo?

speaker = [
    name: 'Antón R. Yuste',
    company: 'Optare Solutions',
    oss: 'GaliBots committer and founder',
    twitter: '@antonmry',
    github: 'antonmry',
    extraDescription: ['VigoJUG co-organiser',
         '''Misc OSS contribs (Gradle plugins,
            docker images, SIP & WebRTC...)''',
         'surfer wannabe',]
].each{ k, v -> println "${k}:${v}" }

Axenda

  • ¿Sancho Panza?

  • Instalación

  • Scripting e prototipado

  • Xestión de dependencias e de configuración

  • Probas unitarias e de integración

  • DSLs (Jenkins, JMeter, SoapUI)

  • As tuas propias DSLs

¿Sancho Panza?

sancho

Groovy, VigoJUG, VigoJUG, Groovy

  • Sintaxe moi similar a Java

  • Sinxelo e moi expresivo

  • Orientado a obxectos…​ e funcional

  • Tipado…​ se queres

  • Dinámico…​ ou estático

  • Usado por Netflix, Oracle, Google, etc.

Groovy no mapa da JVM

groovy-island

Exemplo

Calcular a potencia de dous nun array

[0, 1, 2, 3, 4, ..., n]
sancho
[0, 1, 2, 4, 8, ..., 2^n]

Java 7

import java.util.ArrayList;
import java.util.List;

class PowersOfTwoJava7 {

    public static void main(String[] args) {
        List list = new ArrayList();

        for (int i = 0; i < 10; i++) {
           list.add(i);
        }

        for (int i = 0; i < list.size(); i++) {
            System.out.println((int) Math.pow(2, i));
        }
    }

}

Java 8

import java.util.stream.IntStream;

class PowersOfTwoJava8 {

    public static void main(String[] args) {

        IntStream.range(0, 9)
                .map(i -> (int) Math.pow(2, i))
                .forEach(System.out::println);

    }
}

Groovy

(0..<10).forEach() { println 2 ** it }

Instalación con SDKMAN

Moi doado

curl -s "https://get.sdkman.io" | bash
sdk install groovy
sdk install gradle
sdk install sshoogr

Info: sdkman.io

Scripting e prototipado

@Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7.1')

import groovyx.net.http.RESTClient

def jokes = new RESTClient('http://tambal.azurewebsites.net')
def resp = jokes.get( path: '/joke/random/' )

assert resp.status == 200

println "Joke: " + resp.data.joke

Demo scripting

Xestión de dependencias con Gradle

apply plugin: 'java'

sourceCompatibility = 1.7

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'log4j', name: 'log4j', version: '1.0'
    testCompile group: 'junit', name: 'junit', version: '4.+'
}

Xestión da configuración con sshoogr

remoteSession('user2:654321@localhost:2222') {
  exec 'rm -rf /tmp/*'
  exec 'touch /var/lock/my.pid'
  remoteFile('/var/my.conf').text = "enabled=true"
}

Probas unitarias con Spock

def "HashMap accepts null key"() {
  setup:
  def map = new HashMap()

  when:
  map.put(null, "elem")

  then:
  notThrown(NullPointerException)
}

Probas E2E con Geb

import geb.Browser

Browser.drive {
    go "http://myapp.com/login"

    assert $("h1").text() == "Please Login"

    $("form.login").with {
        username = "admin"
        password = "password"
        login().click()
    }

    assert $("h1").text() == "Admin Section"
}

DSLs (Jenkins, JMeter, SoapUI)

pipeline {
    agent any

    stages {
        stage('Build') {
            steps {
                sh 'make'
            }
        }
        stage('Test'){
            steps {
                sh 'make check'
                junit 'reports/**/*.xml'
            }
        }
    }
}

Custom DSLs

// equivalent to: turn(left).then(right)
turn left then right

// equivalent to: take(2.pills).of(chloroquinine).after(6.hours)
take 2.pills of chloroquinine after 6.hours

// equivalent to: paint(wall).with(red, green).and(yellow)
paint wall with red, green and yellow

// with named parameters too
// equivalent to: check(that: margarita).tastes(good)
check that: margarita tastes good

// with closures as parameters
// equivalent to: given({}).when({}).then({})
given { } when { } then { }

¡Gracias!

VigoJUG

  • Un meetup o derradeiro martes de cada mes

  • ¿Te animas cunha charla?. Licencias de JetBrains ;-)

  • Involucrar as empresas locais

  • Outros grupos locais (mañá JS!)

  • Canal de slack #VigoJUG en http://phpvigo.slack.com

sponsors

O reto

  • Exercicio de programación breve (30 minutos) en GitHub

  • PRs (un directorio por cada usuaria)

  • Unha semana antes: se fecha e lanzamos enquisa (Twitter?, +1 en Github?)

  • Charla lostrego no seguinte meetup

Kahoot

kahoot

Quiz 1

// Saved in file ".java"
class A{
	public static void main(String args[]){
		System.out.println("Hello java");
	}
}

Quiz 2

Collection<String> coll = new ArrayList<>();
coll.add("Fred"); coll.add("Jim"); coll.add("Sheila");
System.out.println("coll is " + coll);
coll.remove(0); // line n1
System.out.println("coll is " + coll);

Quiz 3

Path p = Paths.get("a", "b", "cee"); // line n1
System.out.println(p.endsWith(Paths.get("b", "cee")));
System.out.println(p.endsWith(Paths.get("ee")));

Quiz 4

class A {
    int x = 1;

    public static void main(String [] args) {
        System.out.println("x is " + x);
    }
}

Quiz 5

class A {
    public static void main(String [] args) {
        A a = new B();
    }
}

class B extends A {
}

Quiz 6

def it = 4
(0..<10).forEach() { println 2 ** it + " " }