AnalyticsPageInfoProvider.java 12.4 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.commons.inherit.HierarchyNodeInheritanceValueMap
 *  com.day.cq.wcm.api.Page
 *  com.day.cq.wcm.api.PageInfoProvider
 *  com.day.cq.wcm.webservicesupport.Configuration
 *  com.day.cq.wcm.webservicesupport.ConfigurationManager
 *  com.day.cq.wcm.webservicesupport.ConfigurationManagerFactory
 *  javax.servlet.http.Cookie
 *  org.apache.commons.lang.StringUtils
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Properties
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.sling.api.SlingHttpServletRequest
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ValueMap
 *  org.apache.sling.api.wrappers.ValueMapDecorator
 *  org.apache.sling.commons.json.JSONException
 *  org.apache.sling.commons.json.JSONObject
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.analytics.sitecatalyst.impl;

import com.day.cq.analytics.sitecatalyst.impl.util.AnalyticsDemoStatistics;
import com.day.cq.analytics.sitecatalyst.impl.util.ReportConfigUtils;
import com.day.cq.commons.inherit.HierarchyNodeInheritanceValueMap;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageInfoProvider;
import com.day.cq.wcm.webservicesupport.Configuration;
import com.day.cq.wcm.webservicesupport.ConfigurationManager;
import com.day.cq.wcm.webservicesupport.ConfigurationManagerFactory;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.Cookie;
import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.wrappers.ValueMapDecorator;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(metatype=0, immediate=1)
@Service
@Properties(value={@Property(name="pageInfoProviderType", value={"sites.listView.info.provider.analytics"})})
public class AnalyticsPageInfoProvider
implements PageInfoProvider {
    public static final String providerType = "analytics";
    private static final Logger log = LoggerFactory.getLogger(AnalyticsPageInfoProvider.class);
    public static final String TREND_KEY_SUFFIX = "trend";
    public static final String TIMEFRAME_COOKIE_NAME = "analytics-data-timeframe";
    public static final String SELECTED_COLUMNS_COOKIE_NAME = "aem-listview-show-columns";
    public static final long METRIC_VALUE_EMPTY = 0;
    public static final long METRIC_VALUE_PENDING = -1;
    public static final long METRIC_VALUE_NOT_AVAILABLE = -2;
    private static final Map<String, String> previousReportNameMapping = new HashMap<String, String>(){};
    @Reference
    private ConfigurationManagerFactory cfgMgrFactory;

    public void updatePageInfo(SlingHttpServletRequest request, JSONObject info, Resource resource) throws JSONException {
        Configuration analyticsConfig;
        Page page = (Page)resource.adaptTo(Page.class);
        JSONObject analyticsInfo = new JSONObject();
        log.debug("Compiling the custom analytics data for the page information");
        if (page != null && ((analyticsConfig = this.getAnalyticsConfig(page)) != null || AnalyticsDemoStatistics.isDemoDataEnabled(page))) {
            String metricHolderName = this.getMetricHolderName(request);
            String previousMetricHolderName = previousReportNameMapping.get(metricHolderName);
            if (metricHolderName == null) {
                log.error("Could not determine the analytics data node name!");
            }
            ValueMap currentAnalyticsProperties = this.getPageStatistics(page, metricHolderName, analyticsConfig, request);
            Set allCurrentAnalyticsProperties = new HashSet();
            if (currentAnalyticsProperties != null) {
                allCurrentAnalyticsProperties = currentAnalyticsProperties.keySet();
            }
            ValueMap previousAnalyticsProperties = this.getPageStatistics(page, previousMetricHolderName, analyticsConfig, request);
            for (String analyticsProp : allCurrentAnalyticsProperties) {
                double previousValue;
                if (analyticsProp.matches("[a-zA-Z]+\\:.*")) continue;
                int trend = 0;
                double currentPropValue = currentAnalyticsProperties != null ? (Double)currentAnalyticsProperties.get(analyticsProp, (Object)0.0) : 0.0;
                long currentLongPropValue = (long)currentPropValue;
                double d = previousValue = previousAnalyticsProperties != null ? (Double)previousAnalyticsProperties.get(analyticsProp, (Object)0.0) : 0.0;
                if (currentPropValue >= 0.0 && previousValue >= 0.0) {
                    trend = Long.signum((long)(currentPropValue - previousValue));
                }
                String unPrefixedAnalyticsProp = analyticsProp.replace("analytics_", "");
                if (currentPropValue > (double)currentLongPropValue) {
                    analyticsInfo.put(unPrefixedAnalyticsProp, currentPropValue);
                } else {
                    analyticsInfo.put(unPrefixedAnalyticsProp, currentLongPropValue);
                }
                analyticsInfo.put(unPrefixedAnalyticsProp + "trend", trend);
            }
        }
        info.put("analytics", (Object)analyticsInfo);
    }

    private String getMetricHolderName(SlingHttpServletRequest request) {
        Cookie timeframeCookie = request.getCookie("analytics-data-timeframe");
        if (timeframeCookie != null) {
            return timeframeCookie.getValue();
        }
        return "last30Days";
    }

    private Configuration getAnalyticsConfig(Page page) {
        Configuration analyticsConfig = null;
        HierarchyNodeInheritanceValueMap contentPageProperties = new HierarchyNodeInheritanceValueMap(page.getContentResource());
        String[] services = (String[])contentPageProperties.getInherited("cq:cloudserviceconfigs", (Object)new String[0]);
        analyticsConfig = this.cfgMgrFactory.getConfigurationManager(page.getContentResource().getResourceResolver()).getConfiguration("sitecatalyst", services);
        return analyticsConfig;
    }

    private ValueMap getPageStatistics(Page page, String analyticsDataHolder, Configuration analyticsConfig, SlingHttpServletRequest request) {
        ValueMap statisticsProps = null;
        if (analyticsConfig != null) {
            log.debug("Searching SC data on page " + page.getPath() + " on child node " + analyticsDataHolder);
            Resource pageAnalyticsDataResource = page.getContentResource("cq:meta/" + analyticsDataHolder);
            if (pageAnalyticsDataResource != null) {
                statisticsProps = (ValueMap)pageAnalyticsDataResource.adaptTo(ValueMap.class);
            } else {
                log.debug("No SC data for page " + page.getPath());
            }
            statisticsProps = this.updateMissingStatistics(page, statisticsProps, analyticsDataHolder, analyticsConfig, request);
        } else if (AnalyticsDemoStatistics.isDemoDataEnabled(page)) {
            log.debug("Generating random demo analytics data for page " + page.getPath() + " on child node " + analyticsDataHolder);
            statisticsProps = AnalyticsDemoStatistics.generateRandomStatistics();
        }
        return statisticsProps;
    }

    private ValueMap updateMissingStatistics(Page page, ValueMap pageStatistics, String analyticsDataHolder, Configuration analyticsConfig, SlingHttpServletRequest request) {
        ConfigurationManager cfgMgr = this.cfgMgrFactory.getConfigurationManager(request.getResourceResolver());
        Page rootPage = ReportConfigUtils.getPageBySCConfig((Resource)page.adaptTo(Resource.class), analyticsConfig.getContentResource(), cfgMgr);
        if (rootPage != null) {
            Calendar pageCreationDate = (Calendar)page.getProperties().get("jcr:created", Calendar.class);
            if (pageCreationDate == null) {
                pageCreationDate = (Calendar)((ValueMap)page.adaptTo(ValueMap.class)).get("jcr:created", Calendar.class);
            }
            String[] reportConfigRelativePaths = new String[]{"analytics/reportConfigs/" + analyticsDataHolder + "ReportConfig", "analytics/reportConfigs/" + analyticsDataHolder + "CustomData" + "ReportConfig", "analytics/" + analyticsDataHolder + "ReportConfig", "analytics/" + analyticsDataHolder + "CustomData" + "ReportConfig"};
            ValueMap allMetrics = null;
            for (String reportConfigRelativePath : reportConfigRelativePaths) {
                allMetrics = this.collectMetrics(allMetrics, rootPage, pageCreationDate, reportConfigRelativePath, request);
            }
            if (allMetrics != null) {
                if (pageStatistics != null) {
                    for (String analyticsProp : pageStatistics.keySet()) {
                        allMetrics.put((Object)analyticsProp, pageStatistics.get((Object)analyticsProp));
                    }
                }
                pageStatistics = allMetrics;
            }
        }
        return pageStatistics;
    }

    private ValueMap collectMetrics(ValueMap metricProperties, Page rootPage, Calendar pageCreationDate, String reportConfigRoot, SlingHttpServletRequest request) {
        Resource reportDescription = rootPage.getContentResource().getChild(reportConfigRoot + "/" + "reportDescription");
        if (reportDescription != null) {
            if (metricProperties == null) {
                metricProperties = new ValueMapDecorator(new HashMap());
            }
            ValueMap reportDescProps = reportDescription.getValueMap();
            long lastSuccessfulImport = (Long)reportDescProps.get("cq:lastSuccessfulImport", (Object)0);
            Resource reportMetrics = reportDescription.getChild("metrics");
            if (reportMetrics != null) {
                for (Resource reportMetric : reportMetrics.getChildren()) {
                    ValueMap reportMetricConfig = reportMetric.getValueMap();
                    String metricName = (String)reportMetricConfig.get("id", (Object)"");
                    long metricValue = pageCreationDate != null && lastSuccessfulImport >= pageCreationDate.getTimeInMillis() ? 0 : -1;
                    metricProperties.put((Object)("analytics_" + metricName), (Object)metricValue);
                }
            }
            for (String configuredMetricColumn : this.getSelectedColumns(request)) {
                if (metricProperties.get((Object)("analytics_" + configuredMetricColumn)) != null) continue;
                metricProperties.put((Object)("analytics_" + configuredMetricColumn), (Object)-2);
            }
        }
        return metricProperties;
    }

    private List<String> getSelectedColumns(SlingHttpServletRequest request) {
        ArrayList<String> selectedColumns = new ArrayList<String>();
        Cookie selectedColumnsHolder = request.getCookie("aem-listview-show-columns");
        if (selectedColumnsHolder != null) {
            String[] columnNames;
            String selectedColumnsStr = "";
            try {
                selectedColumnsStr = URLDecoder.decode(selectedColumnsHolder.getValue(), "utf-8");
            }
            catch (Exception e) {
                log.error("Can't decode string!", (Throwable)e);
            }
            for (String selectedColumn : columnNames = selectedColumnsStr.split(",")) {
                if (!StringUtils.isNotBlank((String)selectedColumn)) continue;
                selectedColumns.add(selectedColumn);
            }
        }
        return selectedColumns;
    }

    protected void bindCfgMgrFactory(ConfigurationManagerFactory configurationManagerFactory) {
        this.cfgMgrFactory = configurationManagerFactory;
    }

    protected void unbindCfgMgrFactory(ConfigurationManagerFactory configurationManagerFactory) {
        if (this.cfgMgrFactory == configurationManagerFactory) {
            this.cfgMgrFactory = null;
        }
    }

}