Você está na página 1de 32

Construindo uma comunidade mais forte

Liferay Portugal Users Group - Meetup #14

Groovy Script
Marcel Tanuri
Senior Consultant at Inetum
Bem vindos

Inetum Portugal

Developer
Marcel Tanuri
marcel.tanuri@gmail.com
Java, Liferay, JavaScript
https://github.com/marceltanuri
https://www.linkedin.com/in/marceltanuri/

2
Sobre o que vamos falar?

O uso da linguagem groovy como ferramenta de script


e automação na plataforma Liferay.

+
Como configurar um ambiente de desenvolvimento
groovy, utilizando eclipse IDE e plugins, para maior
agilidade desde a codificação até a execução
3
Por que falar sobre groovy?

O groovy é uma ferramenta poderosa nas mãos de


desenvolvedores Liferay. Permite executar comandos
em toda API do Liferay de forma rápida e simples

4
Por que configurar um ambiente groovy?

Sem um ambiente para desenvolvimento, os scripts


precisam ser escritos e executados diretamente no
console web do Liferay. Este console não conta com
nenhum auxílio de autocomplete, javadoc, avisos de
erros, alertas, etc

5
GROOVY | INTRODUÇÃO

Apache Groovy is a powerful, optionally typed and dynamic language, with static-typing and static compilation capabilities,
for the Java platform aimed at improving developer productivity thanks to a concise, familiar and easy to learn syntax. It
integrates smoothly with any Java program, and immediately delivers to your application powerful features, including scripting
capabilities, Domain-Specific Language authoring, runtime and compile-time meta-programming and functional programming.

6
GROOVY | INTRODUÇÃO

Dynamically compile Byte code

LIFERAY API

JVM

7
GROOVY | INTRODUÇÃO

• Console Script desde as versões mais antigas

• Possibilidade de explorar toda API Liferay via script groovy

• Automação de tarefas, atualização ou exclusão de conteúdos

8
GROOVY | LIFERAY CONSOLE

Menu > Painel de Controlo >


Administração do Servidor >
Certificado

9
GROOVY | LIFERAY CONSOLE

PRÓS CONTRAS
• Não salva o script digitado no browser
• Acesso rápido
• Reload da página ou perda da sessão causa a
• Toda API Liferay disponível perda do código

• Zero configuração • Não possui avisos sobre erros de compilação


• Não possui autocomplete ou sugestões de
código
• Não exibe javadoc

10
GROOVY | COM ECLIPSE IDE

Gradle plugin
Groovy plugin execute script
New project Liferay release from CLI

Show script
result

11
GROOVY | COM ECLIPSE IDE

PRÓS
• Avisos sobre erros de compilação durante a
codificação do script
• Javadoc
• Autocomplete para toda a API do Liferay
• Código sempre salvo CONTRAS
• Maior organização e segurança • Necessário configuração da IDE

12
GROOVY | COM ECLIPSE IDE

PRÉ REQUISITOS
1. Eclipse 4.20 +
build.gradle
2. Groovy plugin for eclispe plugins {
id 'java-library'
id 'groovy'

3. Liferay IDE Plugin for eclipse }

repositories {
jcenter()
4. liferay-gogo-script }

dependencies {
api 'org.apache.commons:commons-math3:3.6.1'
implementation 'com.google.guava:guava:28.0-jre'
testImplementation 'junit:junit:4.12'
implementation group: "com.liferay.portal", name: "release.portal.api", version: "7.2.0"
compileOnly group: "javax.portlet", name: "portlet-api", version: '3.0.0'
compileOnly group: 'javax.servlet', name: 'servlet-api', version: '2.5'
implementation fileTree(dir: '../../modules/services-db/ama-db/ama-db-api/build/libs', include: '*.jar')
implementation group: 'org.codehaus.groovy', name: 'groovy-all', version: '2.5.14'

13
GROOVY | COM ECLIPSE IDE

CONFIGURAÇÃO
1. Iniciar novo projeto groovy
2. Adicionar natureza gradle
3. Adicionar Liferay release API às dependências do projeto – build.gradle
4. Codificar o script
5. Copiar e colar o script no console web do Liferay

Exemplo: https://github.com/marceltanuri/groovy-for-liferay

14
GROOVY | COM ECLIPSE IDE

new Command(“DEMONSTRAÇÃO”).start()
SCRIPTS | Encontra ocorrência em qualquer versão de conteúdo – 7.2

import com.liferay.journal.service.JournalArticleLocalServiceUtil

def groupId = 20142


def ocurrency = "@gmail.com"

def getArticles = JournalArticleLocalServiceUtil.getArticles(groupId, -1, -1)

getArticles.each {
val ->
def indexOf = val.content.indexOf(ocurrency)
if (indexOf>0) {
println( val.articleId + ", " + val.version + ", " +
val.content.substring(indexOf-10, indexOf+10))
}
}
SCRIPTS | Exibe configurações de todas as páginas de um filtro – 7.2

package pt.ama.scripts.groovy.novolayout21.datarepair.utils

import com.liferay.portal.kernel.model.Layout
import com.liferay.portal.kernel.service.LayoutLocalServiceUtil
import com.liferay.portal.kernel.util.UnicodeProperties

import groovy.transform.Field

/**
* @author marcel.tanuri
*
* Reveal portlets name and preferences in the given page and column
*
* @param groupId Group where script will run
* @param privateLayout Type of page (private when true, public when false) that will processed
* @param parentFriendlyUrl Friendly URL of the parent page. All children pages will be processed
* @param column Column where the portlet will be inspect
*
*/
SCRIPTS | Exibe configurações de todas as páginas de um filtro – 7.2

@Field groupId = 35020


@Field debug = true
@Field includeParent = false
@Field includeChild = true
def privateLayout = false
def parentFriendlyURL = "/servicos"

Layout layout = LayoutLocalServiceUtil.fetchLayoutByFriendlyURL(groupId, privateLayout, parentFriendlyURL)

if(includeParent) {
getAllPreferences(layout);
}

if (includeChild) {
def childrenPages = layout.getChildren();
childrenPages.each { child ->
getAllPreferences(child);
}
}
SCRIPTS | Exibe configurações de todas as páginas de um filtro – 7.2

def getAllPreferences(Layout layout) {


try {
UnicodeProperties up = layout.getTypeSettingsProperties()

println("Page URL: " + layout.getFriendlyURL())


println("Plid: " + layout.getPlid())

println("Page Settings:")
println(up)

println("Theme ID: " + layout.getThemeId())

println("===========================================")
} catch (Exception e) {
println(e)
}
}
SCRIPTS | Atualiza definição de tema para todas as páginas de um filtro – 7.2

import com.liferay.portal.kernel.model.Layout
import com.liferay.portal.kernel.model.LayoutRevision
import com.liferay.portal.kernel.service.LayoutLocalServiceUtil
import com.liferay.portal.kernel.service.LayoutRevisionLocalServiceUtil
import com.liferay.portal.kernel.util.UnicodeProperties
import com.liferay.portal.kernel.workflow.WorkflowConstants

import groovy.transform.Field

/**
* @author marcel.tanuri
*
* Reveal portlets name and preferences in the given page and column
*
* @param groupId Group where script will run
* @param privateLayout Type of page (private when true, public when false) that will processed
* @param parentFriendlyUrl Friendly URL of the parent page. All children pages will be processed
* @param column Column where the portlet will be inspect
*
*/
SCRIPTS | Atualiza definição de tema para todas as páginas de um filtro – 7.2

@Field groupId = 35020


@Field debug = true
@Field includeParent = false
@Field includeChild = true
def privateLayout = false
def parentFriendlyURL = "/servicos"
def newThemeId = "eportugal_WAR_eportugaltheme"

Layout layout = LayoutLocalServiceUtil.fetchLayoutByFriendlyURL(groupId, privateLayout, parentFriendlyURL)

if(includeParent) {
updateThemeId(layout, newThemeId);
}

if (includeChild) {
def childrenPages = layout.getChildren();
childrenPages.each { child ->
updateThemeId(child, newThemeId);
}
}
SCRIPTS | Atualiza definição de tema para todas as páginas de um filtro – 7.2

def updateThemeId(Layout layout, String newThemeId) {


try {
UnicodeProperties up = layout.getTypeSettingsProperties()

println("Page URL: " + layout.getFriendlyURL())


println("Plid: " + layout.getPlid())

println("actual themeID: " + layout.getThemeId())

layout.setThemeId(newThemeId)
LayoutLocalServiceUtil.updateLookAndFeel(layout.getGroupId(), layout.isPrivateLayout(),
layout.getLayoutId(), newThemeId, layout.getColorSchemeId(), layout.getCss())
persistLayoutChanges(layout)

Layout updatedLayout = LayoutLocalServiceUtil.fetchLayout(layout.getPlid())


println("new themeID: " + updatedLayout.getThemeId())

println("===========================================")
} catch (Exception e) {
println(e)
}
}
SCRIPTS | Atualiza definição de tema para todas as páginas de um filtro – 7.2

def persistLayoutChanges(Layout layout) {


LayoutRevision lastLayoutRevision =
LayoutRevisionLocalServiceUtil.fetchLastLayoutRevision(layout.getPlid(),
false)

//update layout as ready to publish


LayoutRevisionLocalServiceUtil.updateStatus(layout.getUserId(),
lastLayoutRevision.getLayoutRevisionId(),
WorkflowConstants.STATUS_APPROVED, null)
}
SCRIPTS | Exibe conteúdo de arquivo XML do Servidor

import org.apache.commons.lang.StringEscapeUtils

println(StringEscapeUtils.escapeXml("cat /home/tcp_ping_transport.xml".execute().text))
liferay-gogo-script | INTRODUÇÃO

O liferay-gogo-script permite que scripts groovy sejam


executados directamente da linha de comando, ou seja,
sem a necessidade de copiar e colar o script no console
do Liferay via browser

25
liferay-gogo-script | IMPORTANTE

Gogo shell should only be run from the command line


in development environments. In production
environments, run Gogo shell in the Control Panel, as
demonstrated in Using the Gogo Shell

https://learn.liferay.com/dxp/latest/en/liferay-internals/fundamentals/using-the-gogo-shell/command-line-gogo-shell.html

26
liferay-gogo-script | INSTALAÇÃO

PRÉ REQUISITOS
1. Sistema Operacional Linux ou MacOS
2. telnet e expect são necessários
3. Adicionar a propriedade developer às propriedades do portal
include-and-override=portal-developer.properties
CONFIGURAÇÃO
1. Clonar o projeto
2. Exportar o diretório do projeto na variável de ambiente PATH
3. Conceder permissões ao diretório

27
liferay-gogo-script | LIMITAÇÕES

1. Incompatibilidade com sistema operacional Windows a não ser através de WSL (Windows
Subsystem Linux).

2. WSL2 com connection refused para localhost ou 127.0.0.1. Necessário fazer downgrade
para WSL1. wsl.exe --set-version Ubuntu 1

3. Class not found exception para pacotes da Liferay API que não sejam
com.liferay.portal.kernel.* Requer uso do serviceLocator

28
liferay-gogo-script | CONTRIBUIÇÕES

https://github.com/slemarchand/liferay-gogo-scripts/

29
Outros exemplos de script
https://help.liferay.com/hc/pt/articles/360018174811-Script-Examples
https://liferay.dev/blogs/-/blogs/pandora-s-box-for-liferay-the-groovy-
edition
https://github.com/slemrchand/liferay-admin-scripts
https://github.com/marceltanuri/groovy-for-liferay

30
Mais info
https://liferay.dev/blogs/-/blogs/thats-groovy-man
https://liferay.dev/blogs/-/blogs/unleash-the-power-of-gogo-shell
https://groovy-lang.org/

31
Construindo uma comunidade mais forte

Meetup: https://www.meetup.com/Liferay-Portugal-User-Group/

LinkedIn: https://www.linkedin.com/groups/12125960/

Youtube: https://www.youtube.com/channel/UCOJiHlf2FNDpdV_zifzqXnA

Você também pode gostar