TargetRecommendationsServlet.java 12.2 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.wcm.api.PageManagerFactory
 *  com.day.cq.wcm.webservicesupport.Configuration
 *  com.day.cq.wcm.webservicesupport.ConfigurationManager
 *  com.day.cq.wcm.webservicesupport.ConfigurationManagerFactory
 *  javax.servlet.ServletException
 *  javax.servlet.ServletInputStream
 *  org.apache.commons.io.IOUtils
 *  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.request.RequestPathInfo
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.servlets.SlingAllMethodsServlet
 *  org.apache.sling.commons.json.JSONArray
 *  org.apache.sling.commons.json.JSONObject
 *  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.RecommendationAlgorithm;
import com.adobe.cq.targetrecommendations.api.model.RecommendationMbox;
import com.adobe.cq.targetrecommendations.api.model.RecommendationTemplate;
import com.adobe.cq.targetrecommendations.api.model.RecommendationsEntity;
import com.adobe.cq.targetrecommendations.api.model.TargetRecommendation;
import com.adobe.cq.targetrecommendations.impl.util.TargetRecommendationsJSONUtil;
import com.day.cq.wcm.api.PageManagerFactory;
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.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import org.apache.commons.io.IOUtils;
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.request.RequestPathInfo;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(label="Adobe AEM Target Recommendations Command Servlet", description="Offers REST support for interacting with the Target Recommendations API Client")
@Service
@Properties(value={@Property(name="sling.servlet.resourceTypes", value={"cq/analytics/components/testandtargetpage"}), @Property(name="sling.servlet.selectors", value={"recommendation", "algorithm", "template", "mbox"}), @Property(name="sling.servlet.extensions", value={"json"}), @Property(name="sling.servlet.methods", value={"GET", "POST", "DELETE", "PUT"})})
public class TargetRecommendationsServlet
extends SlingAllMethodsServlet {
    public static final String SELECTOR_RECOMMENDATION = "recommendation";
    public static final String SELECTOR_ALGORITHM = "algorithm";
    public static final String SELECTOR_TEMPLATE = "template";
    public static final String SELECTOR_MBOX = "mbox";
    public static final String PARAM_ENTITY_ID = "entityId";
    private static final Logger LOG = LoggerFactory.getLogger(TargetRecommendationsServlet.class);
    @Reference
    private ConfigurationManagerFactory configManagerFactory;
    @Reference
    private PageManagerFactory pageManagerFactory;
    @Reference
    private TargetRecommendationsAPIClient recsApiClient;

    protected void doDelete(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
        block5 : {
            String[] selectors = request.getRequestPathInfo().getSelectors();
            Resource currentResource = request.getResource();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            try {
                if (currentResource == null) break block5;
                Configuration ttConfig = this.configManagerFactory.getConfigurationManager(request.getResourceResolver()).getConfiguration(currentResource.getParent().getPath());
                int entityId = 0;
                try {
                    entityId = Integer.parseInt(request.getParameter("entityId"));
                }
                catch (Exception var7_8) {
                    // empty catch block
                }
                if (entityId > 0) {
                    this.deleteEntity(selectors[0], entityId, ttConfig);
                }
            }
            catch (Exception e) {
                LOG.error("Error creating recommendations entities!", (Throwable)e);
                throw new ServletException((Throwable)e);
            }
        }
    }

    protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
        String[] selectors = request.getRequestPathInfo().getSelectors();
        Resource currentResource = request.getResource();
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        try {
            if (currentResource != null) {
                Configuration ttConfig = this.configManagerFactory.getConfigurationManager(request.getResourceResolver()).getConfiguration(currentResource.getParent().getPath());
                ServletInputStream bodyIs = request.getInputStream();
                StringWriter writer = new StringWriter();
                IOUtils.copy((InputStream)bodyIs, (Writer)writer, (String)"UTF-8");
                RecommendationsEntity persistedEntity = this.persistEntity(selectors[0], ttConfig, writer.toString());
                JSONObject responseJson = new JSONObject(persistedEntity.toJson());
                responseJson.write((Writer)response.getWriter());
            }
        }
        catch (Exception e) {
            LOG.error("Error creating recommendations entities!", (Throwable)e);
            throw new ServletException((Throwable)e);
        }
    }

    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
        block5 : {
            String[] selectors = request.getRequestPathInfo().getSelectors();
            Resource currentResource = request.getResource();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            try {
                if (currentResource == null) break block5;
                Configuration ttConfig = this.configManagerFactory.getConfigurationManager(request.getResourceResolver()).getConfiguration(currentResource.getParent().getPath());
                int entityId = 0;
                try {
                    entityId = Integer.parseInt(request.getParameter("entityId"));
                }
                catch (Exception var7_8) {
                    // empty catch block
                }
                List<RecommendationsEntity> responseEntities = this.getEntities(selectors[0], entityId, ttConfig);
                JSONArray responseJson = new JSONArray();
                for (RecommendationsEntity entity : responseEntities) {
                    responseJson.put((Object)new JSONObject(entity.toJson()));
                }
                responseJson.write((Writer)response.getWriter());
            }
            catch (Exception e) {
                LOG.error("Error building the JSON response!", (Throwable)e);
                throw new ServletException((Throwable)e);
            }
        }
    }

    private RecommendationsEntity persistEntity(String selector, Configuration ttConfig, String rawJson) throws Exception {
        RecommendationsEntity entity = null;
        if ("template".equalsIgnoreCase(selector)) {
            RecommendationTemplate template = TargetRecommendationsJSONUtil.parseTemplate(rawJson);
            entity = this.recsApiClient.saveTemplate(template, ttConfig);
        } else if ("algorithm".equalsIgnoreCase(selector)) {
            RecommendationAlgorithm algorithm = TargetRecommendationsJSONUtil.parseAlgorithm(rawJson);
            entity = this.recsApiClient.saveAlgorithm(algorithm, ttConfig);
        } else if ("recommendation".equalsIgnoreCase(selector)) {
            TargetRecommendation recommendation = TargetRecommendationsJSONUtil.parseRecommendation(rawJson);
            entity = this.recsApiClient.saveRecommendation(recommendation, ttConfig);
        } else {
            throw new IllegalArgumentException("Unknown entity type!");
        }
        return entity;
    }

    private void deleteEntity(String selector, int entityId, Configuration ttConfig) throws TargetRecommendationsException {
        if ("template".equalsIgnoreCase(selector)) {
            this.recsApiClient.deleteTemplate(entityId, ttConfig);
        } else if ("algorithm".equalsIgnoreCase(selector)) {
            this.recsApiClient.deleteAlgorithm(entityId, ttConfig);
        } else if ("recommendation".equalsIgnoreCase(selector)) {
            this.recsApiClient.deleteRecommendation(entityId, ttConfig);
        }
    }

    private List<RecommendationsEntity> getEntities(String selector, int entityId, Configuration ttConfig) throws TargetRecommendationsException {
        ArrayList<RecommendationsEntity> responseEntities = new ArrayList<RecommendationsEntity>();
        if ("template".equalsIgnoreCase(selector)) {
            if (entityId > 0) {
                responseEntities.add(this.recsApiClient.getTemplate(entityId, ttConfig));
            } else {
                responseEntities.addAll(this.recsApiClient.getTemplates(ttConfig));
            }
        } else if ("algorithm".equalsIgnoreCase(selector)) {
            if (entityId > 0) {
                responseEntities.add(this.recsApiClient.getAlgorithm(entityId, ttConfig));
            } else {
                responseEntities.addAll(this.recsApiClient.getAlgorithms(ttConfig));
            }
        } else if ("recommendation".equalsIgnoreCase(selector)) {
            if (entityId > 0) {
                responseEntities.add(this.recsApiClient.getRecommendation(entityId, ttConfig));
            } else {
                responseEntities.addAll(this.recsApiClient.getRecommendations(ttConfig));
            }
        } else if ("mbox".equalsIgnoreCase(selector)) {
            responseEntities.addAll(this.recsApiClient.getMBoxes(ttConfig));
        }
        return responseEntities;
    }

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

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

    protected void bindPageManagerFactory(PageManagerFactory pageManagerFactory) {
        this.pageManagerFactory = pageManagerFactory;
    }

    protected void unbindPageManagerFactory(PageManagerFactory pageManagerFactory) {
        if (this.pageManagerFactory == pageManagerFactory) {
            this.pageManagerFactory = null;
        }
    }

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

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