ImpressionsImporter.java 15.8 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.commons.inherit.HierarchyNodeInheritanceValueMap
 *  com.day.cq.polling.importer.ImportException
 *  com.day.cq.polling.importer.Importer
 *  com.day.cq.statistics.StatisticsService
 *  com.day.cq.wcm.webservicesupport.Configuration
 *  com.day.cq.wcm.webservicesupport.ConfigurationManager
 *  com.day.cq.wcm.webservicesupport.ConfigurationManagerFactory
 *  com.day.crx.statistics.Entry
 *  javax.jcr.Node
 *  javax.jcr.PathNotFoundException
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  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.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ValueMap
 *  org.apache.sling.commons.json.JSONArray
 *  org.apache.sling.commons.json.JSONException
 *  org.apache.sling.commons.json.JSONObject
 *  org.apache.sling.commons.osgi.OsgiUtil
 *  org.apache.sling.discovery.InstanceDescription
 *  org.apache.sling.discovery.TopologyEvent
 *  org.apache.sling.discovery.TopologyEvent$Type
 *  org.apache.sling.discovery.TopologyEventListener
 *  org.apache.sling.discovery.TopologyView
 *  org.apache.sling.settings.SlingSettingsService
 *  org.osgi.service.component.ComponentContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.analytics.sitecatalyst;

import com.day.cq.analytics.sitecatalyst.ImpressionsEntry;
import com.day.cq.analytics.sitecatalyst.SitecatalystException;
import com.day.cq.analytics.sitecatalyst.SitecatalystUtil;
import com.day.cq.analytics.sitecatalyst.SitecatalystWebservice;
import com.day.cq.commons.inherit.HierarchyNodeInheritanceValueMap;
import com.day.cq.polling.importer.ImportException;
import com.day.cq.polling.importer.Importer;
import com.day.cq.statistics.StatisticsService;
import com.day.cq.wcm.webservicesupport.Configuration;
import com.day.cq.wcm.webservicesupport.ConfigurationManager;
import com.day.cq.wcm.webservicesupport.ConfigurationManagerFactory;
import com.day.crx.statistics.Entry;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Dictionary;
import java.util.Set;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
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.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.apache.sling.commons.osgi.OsgiUtil;
import org.apache.sling.discovery.InstanceDescription;
import org.apache.sling.discovery.TopologyEvent;
import org.apache.sling.discovery.TopologyEventListener;
import org.apache.sling.discovery.TopologyView;
import org.apache.sling.settings.SlingSettingsService;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Deprecated
@Component(metatype=1, label="Day CQ Analytics SiteCatalyst Impressions Importer", description="Imports SiteCatalyst Page Impressions periodically into CQ")
@Service
@Properties(value={@org.apache.felix.scr.annotations.Property(name="importer.scheme", value={"sitecatalyst"}, propertyPrivate=1)})
public class ImpressionsImporter
implements Importer,
TopologyEventListener {
    private final Logger log;
    @org.apache.felix.scr.annotations.Property(label="Import interval", description="Import interval in milliseconds. Default is set to 43200000 (12h).", longValue={43200000})
    protected static final String REPORT_INTERVAL = "cq.analytics.sitecatalyst.importer.inverval";
    private static final long DEFAULT_INTERVAL = 43200000;
    private long reportInterval;
    @org.apache.felix.scr.annotations.Property(label="Enabled", description="Indicator if importer is enabled or disabled.", boolValue={1})
    private static final String ENABLED = "cq.analytics.sitecatalyst.importer.enabled";
    private static final boolean DEFAULT_ENABLED = false;
    private boolean enabled;
    @Reference
    private SlingSettingsService settingsService;
    @Reference
    private SitecatalystWebservice webservice;
    @Reference
    private StatisticsService statService;
    @Reference
    private ConfigurationManagerFactory cfgManagerFactory;
    private boolean isLeader;

    public ImpressionsImporter() {
        this.log = LoggerFactory.getLogger(this.getClass());
        this.isLeader = false;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public void importData(String scheme, String dataSource, Resource target) throws ImportException {
        block30 : {
            if (this.enabled) {
                if (!this.isLeader) {
                    this.log.info("Import skipped on slave instance");
                    return;
                }
                try {
                    Resource pageResource = target.getParent().getParent();
                    HierarchyNodeInheritanceValueMap pageProperties = new HierarchyNodeInheritanceValueMap(pageResource);
                    Node analytics = (Node)target.getParent().adaptTo(Node.class);
                    String lastAttempt = "0";
                    if (analytics.hasProperty("cq:lastAttempt")) {
                        lastAttempt = analytics.getProperty("cq:lastAttempt").getString();
                    }
                    Configuration configuration = null;
                    String[] services = (String[])pageProperties.getInherited("cq:cloudserviceconfigs", (Object)new String[0]);
                    ConfigurationManager cfgManager = this.cfgManagerFactory.getConfigurationManager(target.getResourceResolver());
                    if (services.length > 0) {
                        configuration = cfgManager.getConfiguration("sitecatalyst", services);
                    }
                    if (configuration == null) {
                        this.log.error("SiteCatalyst configuration not found");
                        return;
                    }
                    if (this.isImporterDisabledFromConfig(configuration)) {
                        return;
                    }
                    String reportSuiteID = SitecatalystUtil.getReportSuites(this.settingsService, configuration);
                    if (lastAttempt.startsWith("waiting")) {
                        String reportID = lastAttempt.replace("waiting-", "");
                        try {
                            String response = this.webservice.getReport(configuration, reportID);
                            JSONObject jsonObj = new JSONObject(response);
                            JSONObject report = jsonObj.optJSONObject("report");
                            if (report != null) {
                                JSONArray data = report.getJSONArray("data");
                                String lastAttemptDate = analytics.getProperty("cq:lastAttemptDate").getString();
                                String statsBasePath = "/var/statistics/pages" + analytics.getPath().replace("/jcr:content/analytics", "");
                                this.log.info("Report contains data items: " + data.length());
                                for (int i = 0; i < data.length(); ++i) {
                                    JSONObject pageData = data.getJSONObject(i);
                                    this.setStatsData(statsBasePath, lastAttemptDate, pageData.getString("name"), pageData.getJSONArray("counts").getString(0), target.getResourceResolver(), this.statService);
                                }
                                this.log.info("Report " + reportID + " imported");
                                break block30;
                            }
                            Long errorId = jsonObj.optLong("error");
                            String errorMsg = jsonObj.optString("error_description");
                            this.log.warn("Report " + reportID + " failed due to (error:" + errorId + "): " + errorMsg);
                        }
                        catch (SitecatalystException e) {
                            this.log.error("Call to Sitecatalyst failed", (Throwable)e);
                        }
                        catch (JSONException e) {
                            this.log.error("Parsing JSON response failed", (Throwable)e);
                        }
                        finally {
                            if (analytics.getSession().hasPendingChanges()) {
                                analytics.setProperty("cq:lastAttempt", Long.toString(System.currentTimeMillis()));
                                analytics.getSession().save();
                            }
                        }
                    }
                    long last = Long.parseLong(lastAttempt);
                    if (last + this.reportInterval >= System.currentTimeMillis()) break block30;
                    if (reportSuiteID == null) {
                        this.log.warn("cannot import data since no valid report suite ID was found");
                        return;
                    }
                    try {
                        Calendar cal = Calendar.getInstance();
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        cal.add(5, -1);
                        String date = dateFormat.format(cal.getTime());
                        String response = this.webservice.queuePageViewReport(configuration, reportSuiteID, date);
                        JSONObject jsonObj = new JSONObject(response);
                        Long reportID = jsonObj.optLong("reportID");
                        if (reportID != 0) {
                            analytics.setProperty("cq:lastAttempt", "waiting-" + reportID);
                            analytics.setProperty("cq:lastAttemptDate", date);
                            this.log.info("Report queued: " + reportID + " for " + reportSuiteID + " and " + date);
                            break block30;
                        }
                        Long errorId = jsonObj.optLong("error");
                        String errorMsg = jsonObj.optString("error_description");
                        this.log.warn(jsonObj.toString());
                        this.log.warn("queueing report failed due to (error:" + errorId + "): " + errorMsg);
                        analytics.setProperty("cq:lastAttempt", Long.toString(System.currentTimeMillis()));
                    }
                    catch (SitecatalystException e) {
                        this.log.error("Call to SiteCatalyst failed", (Throwable)e);
                        analytics.setProperty("cq:lastAttempt", Long.toString(System.currentTimeMillis()));
                    }
                    catch (JSONException e) {
                        this.log.error("Parsing JSON response failed", (Throwable)e);
                        analytics.setProperty("cq:lastAttempt", Long.toString(System.currentTimeMillis()));
                    }
                    finally {
                        if (analytics.getSession().hasPendingChanges()) {
                            analytics.getSession().save();
                        }
                    }
                }
                catch (PathNotFoundException e) {
                    this.log.error("Reading analytics data failed for " + target.getPath(), (Throwable)e);
                }
                catch (RepositoryException e) {
                    this.log.error("Reading analytics data failed", (Throwable)e);
                }
            }
        }
    }

    private void setStatsData(String basePath, String date, String name, String count, ResourceResolver resolver, StatisticsService statService) {
        long views;
        ValueMap statsConfig;
        String statsPath = basePath;
        name = !name.equals("home") ? "/" + name.replace(":", "/") : "";
        statsPath = statsPath + name + "/.stats/";
        Resource dayStats = resolver.getResource(statsPath = statsPath + date.replace("-", "/"));
        if (dayStats != null && (views = ((Long)(statsConfig = (ValueMap)dayStats.adaptTo(ValueMap.class)).get("views", Long.class)).longValue()) == Long.parseLong(count)) {
            return;
        }
        ImpressionsEntry view = new ImpressionsEntry(basePath, name, date, Long.parseLong(count));
        try {
            statService.addEntry((Entry)view);
        }
        catch (RepositoryException e) {
            this.log.error("adding stats entry failed", (Throwable)e);
        }
    }

    private boolean isImporterDisabledFromConfig(Configuration config) {
        boolean disableAuthor = (Boolean)config.getInherited("disableImportPageImpressionsAuthor", (Object)false);
        boolean disablePublish = (Boolean)config.getInherited("disableImportPageImpressionsPublish", (Object)false);
        Set runmodes = this.settingsService.getRunModes();
        if (disableAuthor && runmodes.contains("author")) {
            return true;
        }
        if (disablePublish && runmodes.contains("publish")) {
            return true;
        }
        return false;
    }

    protected void activate(ComponentContext componentContext) {
        Dictionary config = componentContext.getProperties();
        this.reportInterval = OsgiUtil.toLong(config.get("cq.analytics.sitecatalyst.importer.inverval"), (long)43200000);
        this.enabled = OsgiUtil.toBoolean(config.get("cq.analytics.sitecatalyst.importer.enabled"), (boolean)false);
    }

    public void handleTopologyEvent(TopologyEvent event) {
        if (event.getType() == TopologyEvent.Type.TOPOLOGY_CHANGED || event.getType() == TopologyEvent.Type.PROPERTIES_CHANGED || event.getType() == TopologyEvent.Type.TOPOLOGY_INIT) {
            this.isLeader = event.getNewView().getLocalInstance().isLeader();
        } else if (event.getType() == TopologyEvent.Type.TOPOLOGY_CHANGING) {
            this.isLeader = false;
        }
    }

    protected void bindCfgManager(ConfigurationManager cfg) {
        throw new UnsupportedOperationException();
    }

    protected void unbindCfgManager(ConfigurationManager cfg) {
        throw new UnsupportedOperationException();
    }

    protected void bindSettingsService(SlingSettingsService slingSettingsService) {
        this.settingsService = slingSettingsService;
    }

    protected void unbindSettingsService(SlingSettingsService slingSettingsService) {
        if (this.settingsService == slingSettingsService) {
            this.settingsService = null;
        }
    }

    protected void bindWebservice(SitecatalystWebservice sitecatalystWebservice) {
        this.webservice = sitecatalystWebservice;
    }

    protected void unbindWebservice(SitecatalystWebservice sitecatalystWebservice) {
        if (this.webservice == sitecatalystWebservice) {
            this.webservice = null;
        }
    }

    protected void bindStatService(StatisticsService statisticsService) {
        this.statService = statisticsService;
    }

    protected void unbindStatService(StatisticsService statisticsService) {
        if (this.statService == statisticsService) {
            this.statService = null;
        }
    }

    protected void bindCfgManagerFactory(ConfigurationManagerFactory configurationManagerFactory) {
        this.cfgManagerFactory = configurationManagerFactory;
    }

    protected void unbindCfgManagerFactory(ConfigurationManagerFactory configurationManagerFactory) {
        if (this.cfgManagerFactory == configurationManagerFactory) {
            this.cfgManagerFactory = null;
        }
    }
}