groovy llink Jahia 7.3 Jahia 8

How to change the value of the external links in JCR?

Question

How to change the value of the external links in JCR?

Answer

Here is the Groovy script to achieve this task:

import org.jahia.api.Constants
import org.jahia.tools.patches.LoggerWrapper
import org.jahia.services.content.JCRCallback
import org.jahia.services.content.JCRNodeWrapper
import org.jahia.services.content.JCRSessionWrapper
import org.jahia.services.content.JCRTemplate
import org.jahia.services.content.JCRPublicationService

import javax.jcr.NodeIterator
import javax.jcr.RepositoryException
import javax.jcr.query.Query

final LoggerWrapper logger = log

final String nodeTypeName = "jnt:externalLink"
final String jUrl = "j:url"
final String jUuid= "jcr:uuid"
final String jNodename = "j:nodename"
final String urlFound
final String nodeName
final String uuid
final String[] urlToFind = ["http://www.google.fr","http://www.google.en"]
final String[] urlToReplace = ["http://www.google.com","http://www.google.com"]


JCRTemplate.getInstance().doExecuteWithSystemSession(null, Constants.EDIT_WORKSPACE, new JCRCallback() {
    @Override
    Object doInJCR(JCRSessionWrapper session) throws RepositoryException {

        final String stmt = "SELECT * FROM [" + nodeTypeName + "] WHERE ISDESCENDANTNODE(&#quot;/sites/covea&#quot;)"
        final NodeIterator iteratorSites = session.getWorkspace().getQueryManager().createQuery(stmt, Query.JCR_SQL2).execute().getNodes()
        while (iteratorSites.hasNext()) {
            JCRNodeWrapper node = iteratorSites.nextNode() as JCRNodeWrapper
            urlFound = node.getPropertyAsString(jUrl)

            for(i = 0; i < urlToFind.length; i++)
                if (urlFound.equals(urlToFind[i]))
                {
                    nodeName = node.getPropertyAsString(jNodename)
                    uuid = node.getPropertyAsString(jUuid)
                    node.setProperty(jUrl,urlToReplace[i])
                    session.save()
                    JCRPublicationService.getInstance().publishByMainId(uuid)
                    log.info("URL: "+urlToFind[i]+" of Node name: "+nodeName+" replaced by URL: "+urlToReplace[i]+" in Default and Live workspaces")
                }

        }
        return null
    }
})