SlideShare una empresa de Scribd logo
GROOGLEGROOGLE
Groovy + Google = Groogle
PRESENTACIÓNPRESENTACIÓN
Jorge Aguilera
@jagedn
jorge.aguilera@puravida-so ware.com
QUÉ VAMOS A VERQUÉ VAMOS A VER
DSL
Groogle
Puedo (seguro) estar equivocado en algo (o en todo)
de lo que veremos

DSLDSL
https://martinfowler.com/books/dsl.html
— Martin Fowler
DSLs are small languages, focused on a
particular aspect of a so ware system. You
can’t build a whole program with a DSL,
but you o en use multiple DSLs in a system
mainly written in a general purpose
language.
EJEMPLOSEJEMPLOS
Gradle (Closures)
repositories {
mavenCentral()
jcenter()
maven {
url "https://dl.bintray.com/puravida-software/repo"
}
}
Spring Integration (Builder)
IntegrationFlows.from("example")
.channel(this.inputChannel())
.filter((Integer p) -> p > 0)
.transform(Object::toString)
.channel(MessageChannels.queue())
.get();
INVENTADOINVENTADO
Plot
plot {
function "cos(sin(x))" and "x*cos(e*x)" and "t^4/x"
from (-3) incrementing 0.01 to 3
}
http://groovy-lang.gitlab.io/101-
scripts/javafx/build_dsl.html
DSL GROOVYDSL GROOVY
características del propio lenguaje
Maps
Closure con @DelegatesTo
PROPIAS DE GROOVYPROPIAS DE GROOVY
// 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
MAPS (DE CLOSURES)MAPS (DE CLOSURES)
def busca(n){
[ en : { lista->
for(int i=0; i<lista.length;i++){
if(lista[i]==n)
return n
}
return null
}]
}
busca 8 en 1,23,43,12,4/2,8
CLOSURESCLOSURES
class EmailSpec{
void from(String from) { println "From: $from"}
void to(String... to) { println "To: $to"}
void subject(String subject) { println "Subject: $subject"}
}
class EmailBuilder{
def email( @DelegatesTo(strategy=Closure.DELEGATE_ONLY,
value=EmailSpec) Closure cl) {
def email = new EmailSpec()
def code = cl.rehydrate(email, email, email)
code.resolveStrategy = Closure.DELEGATE_ONLY
code()
}
}
GROOGLEGROOGLE
Groogle es un proyecto abierto que ofrece un DSL para
acceder a servicios de Google
GOOGLE API’SGOOGLE API’S
Conjunto de API’s que permiten el acceso a servicios de
Google (Gmail, Drive, Sheet, y un largo etcetera)
Casi todas son REST (pero complejas) así que hay librerías
Java, Python, etc
https://developers.google.com/api-client-library/java/
LIBRERÍA Y DSLLIBRERÍA Y DSL
Groogle comenzó como librería para autentificación pero
ha evolucionado a ofrecer DSL específicas en cada
servicio, aunque pueden ser usadas en conjunto.
Uso directo en GroovyScripts
Groogle está implementado en Groovy pero se puede usar
desde Java 8 mediante lambdaS (no está muy fino)
Descargar como dependencias desde jCenter
MOTIVACIÓNMOTIVACIÓN
Script para 101-groovy-scripts que accediera al Calendar de
un usuario para hacer un gráfico usando sus eventos.
(
)
https://groovy-lang.gitlab.io/101-
scripts/google/calendar.html
CASOS DE USOCASOS DE USO
Compartir información con clientes
Volcar una tabla a un Sheet compartido (o viceversa)
Gestionar eventos de un calendario de forma programada
Servicio REST de una hoja + ficheros en Drive
etc
LENGUAGES/ENTORNOSLENGUAGES/ENTORNOS
Groovy script
Java ( min 8)
Grails, Ratpack
Dockerizado
SUBPROYECTOSSUBPROYECTOS
Autentificación (OAuth y de servicio) [x]
Drive [x]
Sheet [x]
Calendar [x]
Chart (en beta y con futuro incierto) [ ]
Gmail [ ]
Team [ ]
siguiente según demanda [ ]
UPLOAD A FILE WITH GOOGLEUPLOAD A FILE WITH GOOGLE
DriveSample.java
private static File uploadFile(boolean useDirectUpload) throws IOExce
File fileMetadata = new File();
fileMetadata.setTitle(UPLOAD_FILE.getName());
FileContent mediaContent = new
FileContent("image/jpeg", UPLOAD_FILE);
Drive.Files.Insert insert = drive.files().insert(fileMetadata, mediaC
MediaHttpUploader uploader = insert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(useDirectUpload);
uploader.setProgressListener(new FileUploadProgressListener());
return insert.execute();
}
UPLOAD A FILE WITH GROOGLEUPLOAD A FILE WITH GROOGLE
DriveScript.instance.uploadFile{
content new File('test.docx')
saveAs GoogleDoc
}
AUTENTIFICACIÓNAUTENTIFICACIÓN
groogle-core
Crear una aplicación en la consola de Google junto
con unas credenciales. Necesitamos descargar el json
y poder acceder a él (como resource, file, etc)

FORMAS DE IDENTIFICARSEFORMAS DE IDENTIFICARSE
Autentificación OAuth2: el usuario selecciona la cuenta
con la que trabajar
Cuenta de Servicio. Diferentes usuarios permiten acceder
a alguno de sus recursos
TIPSTIPS
Definir los roles que vamos a usar (Drive, Calendar, Sheet …)
Se crea una carpeta $HOME/.credentials/${appname} donde
guardar los tokens
LOGIN OAUTHLOGIN OAUTH
Se abre una ventana en un navegador y
seleccionamos cuenta de usuario

GroogleScript.instance.login{
applicationName 'groogle-example'
withScopes CalendarScopes.CALENDAR, DriveScopes.DRIVE, SheetsScop
usingCredentials '/client_secret.json'
asService false
}
LOGIN SERVICIOLOGIN SERVICIO
GroogleScript.instance.login{
applicationName 'groogle-example'
withScopes CalendarScopes.CALENDAR, DriveScopes.DRIVE, SheetsScop
usingCredentials '/groogle-688bcfc07d1b.json'
asService true
}
DRIVEDRIVE
Buscar ficheros/carpetas en el Drive con filtros
Subir ficheros de nuestro local (y convertirlos
automaticamente)
Bajar ficheros de Drive
BUSCAR FICHEROSBUSCAR FICHEROS
DriveScript.instance.with{
login{
applicationName 'groogle-example'
withScopes DriveScopes.DRIVE
usingCredentials '/groogle-688bcfc07d1b.json'
asService true
}
withFiles {
nameStartWith 'ABC'
batchSize 20
eachFile { file ->
println """
$file.id $file.name
$file.createdDate $file.fileSize ${file.content?.size
}
}
}
SUBIR FICHEROSSUBIR FICHEROS
DriveScript.instance.uploadFile{
name 'hola_caracola.csv'
mimeType 'text/csv'
content new ByteArrayInputStream('h1,h2n100,200'.bytes)
saveAs GoogleSheet
}
SHEETSHEET
Abrir un SpreadSheet
Navegar por las filas de un Sheet
Escribir y leer en un Sheet
LEER SHEETLEER SHEET
SheetScript.instance.withSpreadSheet spreadSheetId, { spreadSheet ->
withSheet 'Hoja 1',{ sheet ->
def str = A2
println "A2 vale $str"
def R2 = readCell("A2")
println "A2 vale con readCell $R2"
def A2B2 = readRows("A2", "B2")
A2B2.each{
println it
}
}
}
ESCRIBIR SHEETESCRIBIR SHEET
SheetScript.instance.withSpreadSheet spreadSheetId, { spreadSheet ->
withSheet 'Hoja 1',{ sheet ->
A1 = 'Hola'
B1 = 'Caracola'
}
}
CALENDARCALENDAR
Navegar por los eventos de un Calendar
Escribir en un Calendar
NUEVO EVENTONUEVO EVENTO
CalendarScript.instance.createEvent groogleCalendarId, {
it.event.summary = "quedada"
allDay new Date().format('yyyy-MM-dd')
}
LEER EVENTOSLEER EVENTOS
CalendarScript.instance.withCalendar( groogleCalendarId,{
batchSize(20)
eachEvent{ WithEvent withEvent->
println "Evento $withEvent.event.summary"
}
})
MODIFICAR EVENTOMODIFICAR EVENTO
CalendarScript.instance.withCalendar( groogleCalendarId,{ WithCalenda
batchSize(20)
eachEvent{ WithEvent withEvent->
withEvent.event.summary = "modificado ${new Date()}"
moveTo new Date().format('yyyy-MM-dd')
}
})
DEMO TIMEDEMO TIME

Más contenido relacionado

PDF
Write Gradle Plugins
PDF
Groovy 2.5 and 3.0 (Spanish)
PDF
Write gradle plugins escribir y publicar tus plugins de gradle made easy_
PDF
Tu api ha muerto larga vida a tu dsl
ODP
Usando Django con Docker
PDF
Android bootcamp 101 v2.0
PDF
Django: el framework web definitivo
DOCX
Configuración de github
Write Gradle Plugins
Groovy 2.5 and 3.0 (Spanish)
Write gradle plugins escribir y publicar tus plugins de gradle made easy_
Tu api ha muerto larga vida a tu dsl
Usando Django con Docker
Android bootcamp 101 v2.0
Django: el framework web definitivo
Configuración de github

Similar a Groogle (20)

PPTX
Google Cloud Platform y Python
PDF
Un poco más allá con grails. PrimerViernes
DOC
Template paper-2015
PPTX
Taller de Grails
PDF
Configuración y uso Google Drive en Android
PDF
PPTX
Presentacion node
PDF
Servicios web
PDF
Tarea 5
PDF
Tarea 5
PDF
Tarea 5
PDF
Documento Web2Py
PPT
Django - Plataforma de sitios web
PDF
Tutorial hacer un crud con prado
PPT
TAREA 5
PPT
TAREA 5
PPT
TAREA 5
PPT
PPT
Charla grails
Google Cloud Platform y Python
Un poco más allá con grails. PrimerViernes
Template paper-2015
Taller de Grails
Configuración y uso Google Drive en Android
Presentacion node
Servicios web
Tarea 5
Tarea 5
Tarea 5
Documento Web2Py
Django - Plataforma de sitios web
Tutorial hacer un crud con prado
TAREA 5
TAREA 5
TAREA 5
Charla grails
Publicidad

Último (6)

PPTX
Derechos_de_Autor_y_Creative_Commons.pptx
DOCX
trabajo programacion.docxxdxxxddxdxxdxdxxxdxxdxdxd
PPTX
Conceptos basicos de Base de Datos y sus propiedades
PDF
Su punto de partida en la IA: Microsoft 365 Copilot Chat
PPTX
sistemas de informacion.................
PDF
AutoCAD Herramientas para el futuro, Juan Fandiño
Derechos_de_Autor_y_Creative_Commons.pptx
trabajo programacion.docxxdxxxddxdxxdxdxxxdxxdxdxd
Conceptos basicos de Base de Datos y sus propiedades
Su punto de partida en la IA: Microsoft 365 Copilot Chat
sistemas de informacion.................
AutoCAD Herramientas para el futuro, Juan Fandiño
Publicidad

Groogle