ReportConfigUtils.java 13.8 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.wcm.api.Page
 *  com.day.cq.wcm.webservicesupport.Configuration
 *  com.day.cq.wcm.webservicesupport.ConfigurationManager
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.nodetype.NodeType
 *  org.apache.sling.api.resource.PersistenceException
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ValueMap
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.analytics.sitecatalyst.impl.util;

import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.webservicesupport.Configuration;
import com.day.cq.wcm.webservicesupport.ConfigurationManager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.nodetype.NodeType;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ReportConfigUtils {
    public static final String NT_POLLCONFIGFOLDER = "cq:PollConfigFolder";
    public static final String NT_SLING_FOLDER = "sling:Folder";
    public static final String PROP_SOURCE = "source";
    public static final String PROP_DATE_FROM = "dateFrom";
    public static final String PROP_DATE_TO = "dateTo";
    public static final String PROP_ID = "id";
    public static final String PROP_TOP = "top";
    public static final String PROP_MANAGED_POLLCOFNIG = "managedPollConfig";
    public static final String METRICS_REPORTS_SOURCE = "screport:default";
    public static final String REPORT_DESCRIPTION = "reportDescription";
    public static final String REPORT_METRICS = "metrics";
    public static final String REPORT_ELEMENTS = "elements";
    public static final String REPORT_CONFIGS_ROOT = "reportConfigs";
    private static final String RT_SITECATALYST = "cq/analytics/components/sitecatalyst";
    private static final String POLLCONFIG_PREFIX = "aem-analytics-integration-";
    private static final Logger logger = LoggerFactory.getLogger(ReportConfigUtils.class);

    public static void addReport(Node parentNode, String nodeReportName, String managedPollConfigName, List<String> elements, List<String> metrics, String dateFrom, String dateTo, String analyticsRoot, String destinationChildNode) {
        try {
            Node reportConfig = parentNode.addNode(nodeReportName, "cq:PollConfigFolder");
            reportConfig.setProperty("source", "screport:default");
            reportConfig.setProperty("managedPollConfig", managedPollConfigName);
            reportConfig.setProperty("getAllItems", true);
            reportConfig.setProperty("saveOnPage", destinationChildNode);
            reportConfig.setProperty("preferPublishReports", true);
            reportConfig.setProperty("resolveByPageName", true);
            Node reportDescription = reportConfig.addNode("reportDescription", "sling:Folder");
            reportDescription.setProperty("dateFrom", dateFrom);
            reportDescription.setProperty("dateTo", dateTo);
            Node reportElements = reportDescription.addNode("elements", "sling:Folder");
            for (int elIdx = 0; elIdx < elements.size(); ++elIdx) {
                Node reportElement = reportElements.addNode(String.valueOf(elIdx), "sling:Folder");
                reportElement.setProperty("id", elements.get(elIdx));
                reportElement.setProperty("top", 10000);
            }
            Node reportMetrics = reportDescription.addNode("metrics", "sling:Folder");
            for (int metricsIdx = 0; metricsIdx < metrics.size(); ++metricsIdx) {
                Node metricConfig = reportMetrics.addNode(String.valueOf(metricsIdx), "sling:Folder");
                metricConfig.setProperty("id", metrics.get(metricsIdx));
            }
        }
        catch (RepositoryException e) {
            logger.error(e.getMessage(), (Throwable)e);
        }
    }

    public static void recursivelyRemoveNodes(Node pageNode, List<String> targetNodeNames) {
        try {
            Node pageContentNode = pageNode.getNode("jcr:content");
            for (String removeNodeName : targetNodeNames) {
                if (!pageContentNode.hasNode(removeNodeName)) continue;
                pageContentNode.getNode(removeNodeName).remove();
            }
            NodeIterator childNodes = pageNode.getNodes();
            while (childNodes.hasNext()) {
                Node child = childNodes.nextNode();
                if (!child.isNodeType(pageNode.getPrimaryNodeType().getName())) continue;
                ReportConfigUtils.recursivelyRemoveNodes(child, targetNodeNames);
            }
        }
        catch (Exception e) {
            logger.error("Can't remove child nodes!", (Throwable)e);
        }
    }

    public static Page getPageBySCConfig(Resource startContentResource, Resource analyticsConfig, ConfigurationManager configurationManager) {
        Page startPage = (Page)startContentResource.adaptTo(Page.class);
        String scConfigPath = analyticsConfig.getPath();
        if (scConfigPath.endsWith("jcr:content")) {
            scConfigPath = scConfigPath.replaceAll("/jcr:content$", "");
        }
        boolean foundPage = false;
        while (!foundPage && startPage != null) {
            ValueMap properties = startPage.getProperties();
            String[] cloudServiceConfigs = (String[])properties.get("cq:cloudserviceconfigs", (Object)new String[0]);
            Configuration scConfig = configurationManager.getConfiguration("sitecatalyst", cloudServiceConfigs);
            if (scConfig != null && scConfig.getPath().equals(scConfigPath)) {
                logger.debug("Found root page having SC config " + scConfigPath + " : " + startPage.getPath());
                foundPage = true;
                continue;
            }
            startPage = startPage.getParent();
        }
        return startPage;
    }

    public static void updateCustomReportConfigs(Resource analyticsConfig, Resource contentResource, ConfigurationManager configurationManager) throws PersistenceException {
        Page targetPage = ReportConfigUtils.getPageBySCConfig(contentResource, analyticsConfig, configurationManager);
        ResourceResolver resolver = contentResource.getResourceResolver();
        if (targetPage != null) {
            String[] reportConfigs;
            Resource customAnalyitcsDataResource = analyticsConfig.getChild("jcr:content/customanalyticsdata");
            ArrayList<String> customMetrics = new ArrayList<String>();
            if (customAnalyitcsDataResource != null) {
                for (Resource customMetricConfigResource : customAnalyitcsDataResource.getChildren()) {
                    ValueMap metricProps = (ValueMap)customMetricConfigResource.adaptTo(ValueMap.class);
                    String metricId = (String)metricProps.get("id", null);
                    if (metricId == null) continue;
                    customMetrics.add(metricId);
                }
            }
            boolean createRootConfig = false;
            Resource analyticsReports = ReportConfigUtils.getAnalyticsReportConfigsResource(targetPage);
            if (analyticsReports == null) {
                analyticsReports = targetPage.getContentResource().getChild("analytics");
                createRootConfig = true;
            }
            for (String reportConfig : reportConfigs = new String[]{"last30DaysCustomDataReportConfig", "last30DaysPrevCustomDataReportConfig", "last90DaysCustomDataReportConfig", "last90DaysPrevCustomDataReportConfig", "thisYearCustomDataReportConfig", "lastYearCustomDataReportConfig"}) {
                Resource reportConfigResource = analyticsReports.getChild(reportConfig);
                if (reportConfigResource == null) continue;
                resolver.delete(reportConfigResource);
            }
            if (createRootConfig) {
                analyticsReports = resolver.create(analyticsReports, "reportConfigs", null);
            }
            ReportConfigUtils.addReport((Node)analyticsReports.adaptTo(Node.class), reportConfigs[0], "aem-analytics-integration-last30Days", Arrays.asList("page"), customMetrics, "-29d", "+0d", "cq:meta", "last30Days");
            ReportConfigUtils.addReport((Node)analyticsReports.adaptTo(Node.class), reportConfigs[1], "aem-analytics-integration-last30DaysPrev", Arrays.asList("page"), customMetrics, "-59d", "-30d", "cq:meta", "last30DaysPrev");
            ReportConfigUtils.addReport((Node)analyticsReports.adaptTo(Node.class), reportConfigs[2], "aem-analytics-integration-last90Days", Arrays.asList("page"), customMetrics, "-89d", "+0d", "cq:meta", "last90Days");
            ReportConfigUtils.addReport((Node)analyticsReports.adaptTo(Node.class), reportConfigs[3], "aem-analytics-integration-last90DaysPrev", Arrays.asList("page"), customMetrics, "-179d", "-90d", "cq:meta", "last90DaysPrev");
            ReportConfigUtils.addReport((Node)analyticsReports.adaptTo(Node.class), reportConfigs[4], "aem-analytics-integration-thisYear", Arrays.asList("page"), customMetrics, "thisYear", "thisYear", "cq:meta", "thisYear");
            ReportConfigUtils.addReport((Node)analyticsReports.adaptTo(Node.class), reportConfigs[5], "aem-analytics-integration-lastYear", Arrays.asList("page"), customMetrics, "lastYear", "lastYear", "cq:meta", "lastYear");
        } else {
            logger.warn("Can't find the first page having " + analyticsConfig.getPath() + " SC configuration!");
        }
    }

    public static void addAnalytics(Resource resource, Resource analyticsConfigResource, ConfigurationManager configManager) {
        ResourceResolver resolver = resource.getResourceResolver();
        Resource analyticsRes = resource.getChild("analytics");
        try {
            Resource reportConfigsRoot;
            if (analyticsRes == null) {
                Node contentNode = (Node)resource.adaptTo(Node.class);
                contentNode.addMixin("cq:metaMixin");
                Node analyticsNode = contentNode.addNode("analytics", "nt:unstructured");
                analyticsNode.setProperty("sling:resourceType", "cq/analytics/components/sitecatalyst");
                analyticsRes = resolver.getResource(analyticsNode.getPath());
            }
            if ((reportConfigsRoot = analyticsRes.getChild("reportConfigs")) == null) {
                reportConfigsRoot = resolver.create(analyticsRes, "reportConfigs", (Map)new HashMap<String, Object>(){});
            }
            ReportConfigUtils.udpateSiteMetricsReports(reportConfigsRoot);
            ReportConfigUtils.updateCustomReportConfigs(analyticsConfigResource, resource.getParent(), configManager);
        }
        catch (Exception e) {
            logger.error(e.getMessage(), (Throwable)e);
        }
    }

    private static void udpateSiteMetricsReports(Resource reportConfigsRoot) {
        try {
            if (reportConfigsRoot != null) {
                String[] reportConfigs;
                for (String reportConfig : reportConfigs = new String[]{"last30DaysReportConfig", "last30DaysPrevReportConfig", "last90DaysReportConfig", "last90DaysPrevReportConfig", "thisYearReportConfig", "lastYearReportConfig"}) {
                    Resource reportConfigResource = reportConfigsRoot.getChild(reportConfig);
                    if (reportConfigResource == null) continue;
                    reportConfigsRoot.getResourceResolver().delete(reportConfigResource);
                }
                Node reportConfigsRootNode = (Node)reportConfigsRoot.adaptTo(Node.class);
                ReportConfigUtils.addReport(reportConfigsRootNode, reportConfigs[0], "aem-analytics-integration-last30Days", Arrays.asList("page"), Arrays.asList("pageviews", "visitors", "averagetimespentonpage"), "-29d", "+0d", "cq:meta", "last30Days");
                ReportConfigUtils.addReport(reportConfigsRootNode, reportConfigs[1], "aem-analytics-integration-last30DaysPrev", Arrays.asList("page"), Arrays.asList("pageviews", "visitors", "averagetimespentonpage"), "-59d", "-30d", "cq:meta", "last30DaysPrev");
                ReportConfigUtils.addReport(reportConfigsRootNode, reportConfigs[2], "aem-analytics-integration-last90Days", Arrays.asList("page"), Arrays.asList("pageviews", "visitors", "averagetimespentonpage"), "-89d", "+1d", "cq:meta", "last90Days");
                ReportConfigUtils.addReport(reportConfigsRootNode, reportConfigs[3], "aem-analytics-integration-last90DaysPrev", Arrays.asList("page"), Arrays.asList("pageviews", "visitors", "averagetimespentonpage"), "-179d", "-90d", "cq:meta", "last90DaysPrev");
                ReportConfigUtils.addReport(reportConfigsRootNode, reportConfigs[4], "aem-analytics-integration-thisYear", Arrays.asList("page"), Arrays.asList("pageviews", "visitors", "averagetimespentonpage"), "thisYear", "thisYear", "cq:meta", "thisYear");
                ReportConfigUtils.addReport(reportConfigsRootNode, reportConfigs[5], "aem-analytics-integration-lastYear", Arrays.asList("page"), Arrays.asList("pageviews", "visitors", "averagetimespentonpage"), "lastYear", "lastYear", "cq:meta", "lastYear");
            }
        }
        catch (Exception e) {
            logger.error(e.getMessage(), (Throwable)e);
        }
    }

    public static Resource getAnalyticsReportConfigsResource(Page rootPage) {
        Resource reportConfigsRes = null;
        try {
            reportConfigsRes = rootPage.getContentResource().getChild("analytics").getChild("reportConfigs");
        }
        catch (Exception e) {
            logger.error("Can't get the analytics reports config root resource!", (Throwable)e);
        }
        return reportConfigsRes;
    }

}