Script Groovy: Editar un campo de una lista de recursos

03/06/2015       Sergio Raposo       Código - Snippet, Programación

Suele ser muy habitual que tengamos que añadir un campo a un recurso ya existente y darle valor, o simplemente editar masivamente un campo ya existente. Veremos en este artículo como hacer un script en groovy para hacerlo de la forma más fácil posible.

En primer lugar debemos crear un fichero json donde tengamos toda la información que deseamos actualizar, en concreto tendremos que crear un array de objetos con 3 campos:

  • path
  • field
  • value

El json sería algo como:

[{"path":"RUTA_RECURSO","field":"NOMBRE_CAMPO_XML","value":"VALOR_A_GUARDAR"},{...},...]

Una vez que tenemos el json creado como recurso en OpenCms, hacemos un script groovy:


import java.util.Locale
import groovy.xml.*
import org.opencms.file.*
import org.opencms.main.*
import org.opencms.xml.content.CmsXmlContent
import org.opencms.xml.content.CmsXmlContentFactory
import org.opencms.xml.types.I_CmsXmlContentValue
import groovy.json.JsonSlurper

class ScriptUpdateXML{
    
    CmsObject cmsObject;
    StringBuffer log = new StringBuffer();    

    public ScriptUpdateXML(){
        
    }
    
    public void init(def cms){
        
        //Configuracion                
        def resourceType = "RESOURCE_TYPE_NAME"; // CAMBIAR
        def jsonPath = "/FOLDER/FICHERO.json"; // CAMBIAR
        
        cmsObject = cms;        
        printLine("************************************",true);
        printLine("Actualizacion contenido XML",true);
        printLine("************************************",true);        
        
        //Leemos el json con los datos
        def json = loadJson(jsonPath);
        
        //Recorremos todos los elementos del json
        json.each {
            def path = it.path;
            def field = it.field;
            def valueField = it.value;
            
            try{            
                printLine("Actualizando el recurso "+path+" ...",false);                    
                editField(path, field, valueField)
                printLine(" OK ");
            }catch (Exception ex){
                printLine(" ERROR: "+ex.getMessage());
            }            
        }
        
        /******* FIN ********/        
        printLine("\n\n",true);
        printLine("************************************",true);
        printLine("FINAL Actualizacion contenido XML",true);
        printLine("************************************",true);    
        
    }
    
    private void printLine(String mensaje, boolean finLinea){
        if(finLinea){
            println(mensaje);
        }else{
            print(mensaje);
        }
    }
    
    private void printLine(String mensaje){
        printLine(mensaje,true);
    }
    
    private void editField(String resourcePath, String field, String value){
        
        //Bloqueamos el recurso
        cmsObject.lockResource(resourcePath);
        
        //Leemos el CmsFile
        CmsFile resource = cmsObject.readFile(resourcePath);
        CmsXmlContent xmlContent = CmsXmlContentFactory.unmarshal(cmsObject, resource);
        
        //Editamos el campos
        setStringValue(xmlContent, field, value);
        
        //Escribimos el recurso en BBDD
        resource.setContents(xmlContent.marshal());
        cmsObject.writeFile(resource);        
        
        //Desbloqueamos el recurso
        cmsObject.unlockResource(resourcePath);        
        
    }
    
    private void setStringValue(CmsXmlContent xmlContent, String elementName, String elementValue) {
                
        I_CmsXmlContentValue actualValue = xmlContent.getValue(elementName, cmsObject.getRequestContext().getLocale());
        if(actualValue==null && "".equals(elementValue)){
            // noop
        }else{
            if(actualValue==null){
                actualValue = xmlContent.addValue(cmsObject, elementName, cmsObject.getRequestContext().getLocale(), 0);
            }
            if("".equals(elementValue) && actualValue.getMinOccurs()==0){
                xmlContent.removeValue(elementName, cmsObject.getRequestContext().getLocale(), 0);
            }else{
                actualValue.setStringValue(cmsObject, elementValue);
            }
        }
    }

    private loadJson(String path)
    {
        //Leemos el contenido del fichero
        CmsFile file = cmsObject.readFile(path);
        String content = new String(file.getContents(), CmsEncoder.ENCODING_UTF_8);
        
        //Parseamos ahora para generar el json
        def slurper = new JsonSlurper()
        def result = slurper.parseText(content)
    }    
}

 

Para ejecutar el script en groovy, podéis consultar el pasado artículo sobre como llamar a una clase Groovy desde una JSP.

 

 Groovy, Script, Update, Actualización, Edición