ReportingServicesSettingsProvider.java 13.5 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.crypto.CryptoException
 *  com.adobe.granite.crypto.CryptoSupport
 *  com.day.cq.analytics.sitecatalyst.AnalyticsPageNameContext
 *  com.day.cq.analytics.sitecatalyst.AnalyticsPageNameResolver
 *  com.day.cq.analytics.sitecatalyst.Framework
 *  com.day.cq.analytics.sitecatalyst.SitecatalystUtil
 *  com.day.cq.wcm.webservicesupport.Configuration
 *  com.day.cq.wcm.webservicesupport.ConfigurationManager
 *  com.day.cq.wcm.webservicesupport.ConfigurationManagerFactory
 *  org.apache.commons.lang.StringUtils
 *  org.apache.felix.scr.annotations.Activate
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.http.Header
 *  org.apache.http.HttpEntity
 *  org.apache.http.HttpResponse
 *  org.apache.http.NameValuePair
 *  org.apache.http.StatusLine
 *  org.apache.http.client.HttpClient
 *  org.apache.http.client.entity.EntityBuilder
 *  org.apache.http.client.methods.CloseableHttpResponse
 *  org.apache.http.client.methods.HttpPost
 *  org.apache.http.client.methods.HttpUriRequest
 *  org.apache.http.client.utils.HttpClientUtils
 *  org.apache.http.impl.client.CloseableHttpClient
 *  org.apache.http.impl.client.HttpClientBuilder
 *  org.apache.http.message.BasicNameValuePair
 *  org.apache.http.osgi.services.HttpClientBuilderFactory
 *  org.apache.http.util.EntityUtils
 *  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.JSONObject
 *  org.apache.sling.commons.osgi.PropertiesUtil
 *  org.osgi.service.component.ComponentContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.cq.contentinsight.impl;

import com.adobe.cq.contentinsight.ProviderSettingsProvider;
import com.adobe.cq.contentinsight.impl.ConfigurationUtil;
import com.adobe.granite.crypto.CryptoException;
import com.adobe.granite.crypto.CryptoSupport;
import com.day.cq.analytics.sitecatalyst.AnalyticsPageNameContext;
import com.day.cq.analytics.sitecatalyst.AnalyticsPageNameResolver;
import com.day.cq.analytics.sitecatalyst.Framework;
import com.day.cq.analytics.sitecatalyst.SitecatalystUtil;
import com.day.cq.wcm.webservicesupport.Configuration;
import com.day.cq.wcm.webservicesupport.ConfigurationManager;
import com.day.cq.wcm.webservicesupport.ConfigurationManagerFactory;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.osgi.services.HttpClientBuilderFactory;
import org.apache.http.util.EntityUtils;
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.JSONObject;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(metatype=1, label="Reporting Services settings provider", description="Provides configured settings and generates authentication token for Reporting Services.")
@Service
public class ReportingServicesSettingsProvider
implements ProviderSettingsProvider {
    private final Logger log;
    private static final String DEFAULT_URL = "https://services1.omniture.com/p/rs/0.5";
    private static final String DEFAULT_PROXY_URL = "/libs/cq/contentinsight/content/proxy.reportingservices.json";
    @Property(name="reportingservices.url", label="URL", description="Reporting Service's base URL", value={"https://services1.omniture.com/p/rs/0.5"})
    private String url;
    @Property(name="reportingservices.proxy.url", label="IE 9 Proxy URL", description="URL of proxy for IE 9 support", propertyPrivate=1, value={"/libs/cq/contentinsight/content/proxy.reportingservices.json"})
    private String proxyUrl;
    @Reference
    private ConfigurationManagerFactory configurationManagerFactory;
    @Reference
    private CryptoSupport cryptoSupport;
    @Reference
    private AnalyticsPageNameResolver pageNameResolver;
    @Reference
    private HttpClientBuilderFactory clientBuilderFactory;

    public ReportingServicesSettingsProvider() {
        this.log = LoggerFactory.getLogger(this.getClass());
    }

    @Override
    public String getName() {
        return "reportingservices";
    }

    @Override
    public ValueMap getSettings(Resource resource) {
        boolean active = false;
        HashMap<String, Object> settings = new HashMap<String, Object>();
        ConfigurationManager mgr = this.configurationManagerFactory.getConfigurationManager(resource.getResourceResolver());
        Configuration configuration = ConfigurationUtil.findConfiguration(mgr, resource, "sitecatalyst");
        if (configuration == null) {
            configuration = mgr.getConfiguration(resource.getPath());
        }
        if (configuration != null) {
            String reportSuite = SitecatalystUtil.getPublishPreferredReportSuite((Configuration)configuration);
            if (reportSuite != null) {
                settings.put("collection", "dms/" + reportSuite);
            }
            AnalyticsPageNameContext context = new AnalyticsPageNameContext(configuration, (Framework)configuration.getContentResource().adaptTo(Framework.class), resource.getResourceResolver(), resource, null, resource.getPath());
            settings.put("pageName", this.pageNameResolver.getPageName(context));
            String segment = (String)configuration.getInherited("segment", (Object)"");
            if (!StringUtils.isBlank((String)segment)) {
                settings.put("segment", segment);
            }
            String company = (String)configuration.getInherited("company", (Object)"");
            String username = (String)configuration.getInherited("username", (Object)"");
            String password = (String)configuration.getInherited("password", (Object)"");
            String sharedSecret = (String)configuration.getInherited("secret", (Object)"");
            String server = (String)configuration.getInherited("server", (Object)"");
            if (!StringUtils.isBlank((String)sharedSecret)) {
                if (this.cryptoSupport.isProtected(sharedSecret)) {
                    try {
                        sharedSecret = this.cryptoSupport.unprotect(sharedSecret);
                    }
                    catch (CryptoException e) {
                        this.log.error("Failed to decrypt the Analytics user's shared secret " + sharedSecret);
                    }
                    settings.put("sharedsecret", sharedSecret);
                    settings.put("username", username + ":" + company);
                    if (!StringUtils.isBlank((String)server)) {
                        settings.put("url", this.generateRsUrlForSharedSecret(server));
                        active = true;
                    } else {
                        this.log.error("Could not obtain the analytics server URL from the Analytics cloud config.");
                    }
                }
            } else {
                try {
                    Map<String, String> auth;
                    if (this.cryptoSupport.isProtected(password)) {
                        password = this.cryptoSupport.unprotect(password);
                    }
                    if (!(auth = this.getAuthenticationDetails(this.url, company, username, password)).isEmpty()) {
                        settings.putAll(auth);
                        active = true;
                    } else {
                        this.log.error("Authentication with Reporting Services failed");
                    }
                    settings.put("defaultLink", configuration.getInherited("serviceAdminUrl", (Object)""));
                }
                catch (Exception e) {
                    this.log.error("Requesting Reporting Services' authentication token failed: ", (Throwable)e);
                }
            }
        }
        settings.put("proxyUrl", resource.getResourceResolver().map(this.proxyUrl));
        settings.put("active", active);
        return new ValueMapDecorator(settings);
    }

    private String generateRsUrlForSharedSecret(String analyticsUrl) {
        String omnitureAPIUrl = analyticsUrl.substring(0, StringUtils.ordinalIndexOf((String)analyticsUrl, (String)"/", (int)3));
        return omnitureAPIUrl + "/rs/0.5/";
    }

    @Override
    public boolean isActive(Resource resource) {
        ConfigurationManager mgr = this.configurationManagerFactory.getConfigurationManager(resource.getResourceResolver());
        Configuration configuration = ConfigurationUtil.findConfiguration(mgr, resource, "sitecatalyst");
        return configuration != null;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private Map<String, String> getAuthenticationDetails(String url, String company, String username, String password) throws Exception {
        CloseableHttpClient httpClient = this.clientBuilderFactory.newBuilder().build();
        HashMap<String, String> details = new HashMap<String, String>();
        try {
            HttpPost post = new HttpPost(url + "/AuthToken/");
            EntityBuilder entityBuilder = EntityBuilder.create();
            entityBuilder.setParameters(new NameValuePair[]{new BasicNameValuePair("username", company + "/" + username), new BasicNameValuePair("password", password)});
            post.setEntity(entityBuilder.build());
            CloseableHttpResponse httpResponse = null;
            try {
                Header location;
                httpResponse = httpClient.execute((HttpUriRequest)post);
                int status = httpResponse.getStatusLine().getStatusCode();
                if (status == 200) {
                    JSONObject json = new JSONObject(EntityUtils.toString((HttpEntity)httpResponse.getEntity()));
                    details.put("headerName", "x-adobe-rs-auth");
                    details.put("headerValue", company + "/" + username + ":" + json.getString("token"));
                } else if (status == 302 && (location = httpResponse.getFirstHeader("Location")) != null) {
                    Map<String, String> map = this.getAuthenticationDetails(location.getValue().replaceAll("/AuthToken/", ""), company, username, password);
                    return map;
                }
            }
            finally {
                HttpClientUtils.closeQuietly((HttpResponse)httpResponse);
            }
            details.put("url", url);
        }
        finally {
            HttpClientUtils.closeQuietly((HttpClient)httpClient);
        }
        return details;
    }

    @Activate
    protected void activate(ComponentContext ctx) {
        this.url = PropertiesUtil.toString(ctx.getProperties().get("reportingservices.url"), (String)"https://services1.omniture.com/p/rs/0.5");
        this.proxyUrl = PropertiesUtil.toString(ctx.getProperties().get("reportingservices.proxy.url"), (String)"/libs/cq/contentinsight/content/proxy.reportingservices.json");
    }

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

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

    protected void bindCryptoSupport(CryptoSupport cryptoSupport) {
        this.cryptoSupport = cryptoSupport;
    }

    protected void unbindCryptoSupport(CryptoSupport cryptoSupport) {
        if (this.cryptoSupport == cryptoSupport) {
            this.cryptoSupport = null;
        }
    }

    protected void bindPageNameResolver(AnalyticsPageNameResolver analyticsPageNameResolver) {
        this.pageNameResolver = analyticsPageNameResolver;
    }

    protected void unbindPageNameResolver(AnalyticsPageNameResolver analyticsPageNameResolver) {
        if (this.pageNameResolver == analyticsPageNameResolver) {
            this.pageNameResolver = null;
        }
    }

    protected void bindClientBuilderFactory(HttpClientBuilderFactory httpClientBuilderFactory) {
        this.clientBuilderFactory = httpClientBuilderFactory;
    }

    protected void unbindClientBuilderFactory(HttpClientBuilderFactory httpClientBuilderFactory) {
        if (this.clientBuilderFactory == httpClientBuilderFactory) {
            this.clientBuilderFactory = null;
        }
    }
}