ProductFeedUpdateServlet.java 9.99 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.commons.Externalizer
 *  com.day.cq.wcm.webservicesupport.Configuration
 *  com.day.cq.wcm.webservicesupport.ConfigurationManager
 *  com.day.cq.wcm.webservicesupport.ConfigurationManagerFactory
 *  javax.servlet.ServletException
 *  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.SlingHttpServletResponse
 *  org.apache.sling.api.resource.PersistableValueMap
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.servlets.SlingAllMethodsServlet
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.cq.targetrecommendations.impl.servlet;

import com.adobe.cq.targetrecommendations.api.TargetRecommendationsAPIClient;
import com.adobe.cq.targetrecommendations.api.TargetRecommendationsException;
import com.adobe.cq.targetrecommendations.api.model.ProductFeed;
import com.adobe.cq.targetrecommendations.impl.model.ProductFeedImpl;
import com.day.cq.commons.Externalizer;
import com.day.cq.wcm.webservicesupport.Configuration;
import com.day.cq.wcm.webservicesupport.ConfigurationManager;
import com.day.cq.wcm.webservicesupport.ConfigurationManagerFactory;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
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.SlingHttpServletResponse;
import org.apache.sling.api.resource.PersistableValueMap;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(label="Adobe AEM Target Recommendations Product Feed Configuration Servlet", description="Handles initialization and/or update of the Target Recommendations product feed configuration from AEM")
@Service
@Properties(value={@Property(name="sling.servlet.resourceTypes", value={"cq/analytics/components/testandtargetpage"}), @Property(name="sling.servlet.selectors", value={"recommendationsFeedUpdate"}), @Property(name="sling.servlet.extensions", value={"json"}), @Property(name="sling.servlet.methods", value={"POST"})})
public class ProductFeedUpdateServlet
extends SlingAllMethodsServlet {
    public static final String AEM_FEED_NAME = "AEM Product Feed";
    private static final String FEED_URL_SUFFIX = "/jcr:content.productfeed.recs.full.xml";
    private static final Logger LOG = LoggerFactory.getLogger(ProductFeedUpdateServlet.class);
    @Reference
    private ConfigurationManagerFactory configManagerFactory;
    @Reference
    private TargetRecommendationsAPIClient recsApiClient;

    protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
        Resource ttConfigResource = request.getResource();
        if (ttConfigResource == null) {
            LOG.error("No resource found on request!");
            return;
        }
        try {
            Configuration ttCloudConfig = this.configManagerFactory.getConfigurationManager(request.getResourceResolver()).getConfiguration(ttConfigResource.getParent().getPath());
            Resource recommendationsSettingsResource = ttConfigResource.getChild("recommendations");
            if (recommendationsSettingsResource == null) {
                LOG.debug("No Target Recommendations product feed settings node found!");
                return;
            }
            boolean recsEnabled = (Boolean)ttCloudConfig.get("recommendationsEnabled", (Object)false);
            if (!recsEnabled) {
                LOG.debug("The {} TnT configuration does not have Target Recommendations capabilities! Will not synchronize product feed settings to Recommendations!", new Object[]{ttConfigResource.getPath()});
                return;
            }
            PersistableValueMap configProps = (PersistableValueMap)recommendationsSettingsResource.adaptTo(PersistableValueMap.class);
            String feedUrl = "";
            URI feedURI = null;
            String rootPage = (String)configProps.get("rootPage", (Object)"");
            boolean overrideExternalizer = (Boolean)configProps.get("overrideExternalizer", (Object)false);
            String serverHost = (String)configProps.get("serverHost", (Object)"");
            String domainPortStr = "";
            if (!overrideExternalizer || "".equals(serverHost)) {
                ResourceResolver resolver = request.getResourceResolver();
                Externalizer externalizer = (Externalizer)resolver.adaptTo(Externalizer.class);
                if (externalizer != null) {
                    feedUrl = externalizer.externalLink(resolver, "local", rootPage + "/jcr:content.productfeed.recs.full.xml");
                    feedURI = new URI(feedUrl);
                }
            } else {
                feedUrl = serverHost + rootPage + "/jcr:content.productfeed.recs.full.xml";
                feedURI = new URI(feedUrl);
            }
            if (feedURI != null) {
                domainPortStr = feedURI.getHost();
                if (feedURI.getPort() > 0) {
                    domainPortStr = domainPortStr + ":" + feedURI.getPort();
                }
            }
            String updateFrequency = (String)configProps.get("frequency", (Object)"");
            int feedId = (Integer)configProps.get("recsFeedId", (Object)-1);
            boolean feedEnabled = (Boolean)configProps.get("enableFeed", (Object)false);
            ProductFeed aemFeed = this.findAEMPRoductFeed(ttCloudConfig, feedId, domainPortStr);
            ProductFeed.FeedSchedule feedUpdateFreq = null;
            try {
                feedUpdateFreq = ProductFeed.FeedSchedule.valueOf(updateFrequency.toUpperCase());
            }
            catch (Exception e) {
                feedUpdateFreq = ProductFeed.FeedSchedule.WEEKLY;
            }
            feedUpdateFreq = feedEnabled ? feedUpdateFreq : ProductFeed.FeedSchedule.NEVER;
            HashMap<String, String> connectionProperties = new HashMap<String, String>();
            connectionProperties.put("type", "url");
            connectionProperties.put("URL", feedUrl);
            HashMap<String, String> attributeMapping = new HashMap<String, String>();
            attributeMapping.put("id", "id");
            attributeMapping.put("product_type", "category");
            attributeMapping.put("title", "name");
            attributeMapping.put("description", "message");
            attributeMapping.put("price", "value");
            attributeMapping.put("image_link", "thumbnailUrl");
            attributeMapping.put("link", "pageUrl");
            aemFeed = aemFeed == null ? new ProductFeedImpl(-1, this.getAEMFeedName(domainPortStr), ProductFeed.FeedType.GOOGLE_PRODUCT, feedUpdateFreq, -1, attributeMapping, connectionProperties) : new ProductFeedImpl(aemFeed.getId(), this.getAEMFeedName(domainPortStr), aemFeed.getType(), feedUpdateFreq, aemFeed.getEnvironmentId(), attributeMapping, connectionProperties);
            aemFeed = this.recsApiClient.saveFeed(aemFeed, ttCloudConfig);
            boolean saveConfig = false;
            if (feedId != aemFeed.getId()) {
                configProps.put((Object)"recsFeedId", (Object)aemFeed.getId());
                saveConfig = true;
            }
            if (!feedUrl.equals(configProps.get("url", (Object)""))) {
                configProps.put((Object)"url", (Object)feedUrl);
                saveConfig = true;
            }
            if (saveConfig) {
                configProps.save();
            }
        }
        catch (Exception e) {
            LOG.error("Could not update recommendations product feed config for T&T configuration" + ttConfigResource.getPath(), (Throwable)e);
        }
    }

    private ProductFeed findAEMPRoductFeed(Configuration ttConfig, int feedId, String domainPortStr) throws TargetRecommendationsException {
        ProductFeed foundFeed = null;
        if (feedId > 0) {
            try {
                foundFeed = this.recsApiClient.getFeed(feedId, ttConfig);
            }
            catch (Exception e) {
                LOG.warn("Error getting feed with id=" + feedId, (Throwable)e);
            }
        }
        String searchFeedName = this.getAEMFeedName(domainPortStr);
        if (foundFeed == null) {
            List<ProductFeed> allFeeds = this.recsApiClient.getFeeds(ttConfig);
            for (ProductFeed feed : allFeeds) {
                if (!searchFeedName.equalsIgnoreCase(feed.getName())) continue;
                foundFeed = feed;
                break;
            }
        }
        return foundFeed;
    }

    private String getAEMFeedName(String domainPortStr) {
        return "AEM Product Feed [" + domainPortStr + "]";
    }

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

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

    protected void bindRecsApiClient(TargetRecommendationsAPIClient targetRecommendationsAPIClient) {
        this.recsApiClient = targetRecommendationsAPIClient;
    }

    protected void unbindRecsApiClient(TargetRecommendationsAPIClient targetRecommendationsAPIClient) {
        if (this.recsApiClient == targetRecommendationsAPIClient) {
            this.recsApiClient = null;
        }
    }
}