ExactTargetSpecificActionsServlet.java 12 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.mcm.emailprovider.EmailService
 *  com.day.cq.mcm.emailprovider.service.EmailServiceProvider
 *  com.day.cq.mcm.exacttarget.client.DataExtension
 *  com.day.cq.mcm.exacttarget.client.FilterPart
 *  com.day.cq.mcm.exacttarget.client.SimpleFilterPart
 *  com.day.cq.mcm.exacttarget.client.SimpleOperators
 *  com.day.cq.wcm.webservicesupport.Configuration
 *  com.day.cq.wcm.webservicesupport.ConfigurationManager
 *  com.day.cq.wcm.webservicesupport.ConfigurationManagerFactory
 *  javax.jcr.Node
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  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.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceUtil
 *  org.apache.sling.api.resource.ValueMap
 *  org.apache.sling.api.servlets.SlingAllMethodsServlet
 *  org.apache.sling.commons.json.JSONArray
 *  org.apache.sling.commons.json.JSONException
 *  org.apache.sling.commons.json.JSONObject
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.mcm.exacttarget.servlets;

import com.day.cq.mcm.emailprovider.EmailService;
import com.day.cq.mcm.emailprovider.service.EmailServiceProvider;
import com.day.cq.mcm.exacttarget.ExactTargetException;
import com.day.cq.mcm.exacttarget.ExactTargetService;
import com.day.cq.mcm.exacttarget.client.DataExtension;
import com.day.cq.mcm.exacttarget.client.FilterPart;
import com.day.cq.mcm.exacttarget.client.SimpleFilterPart;
import com.day.cq.mcm.exacttarget.client.SimpleOperators;
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.PrintWriter;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
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.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/*
 * This class specifies class file version 49.0 but uses Java 6 signatures.  Assumed Java 6.
 */
@Component
@Service
@Properties(value={@Property(name="sling.servlet.extensions", value={"json"}, propertyPrivate=1), @Property(name="sling.servlet.selectors", value={"exacttarget"}, propertyPrivate=1), @Property(name="sling.servlet.resourceTypes", value={"sling/servlet/default"}), @Property(name="sling.servlet.methods", value={"POST", "GET"}, propertyPrivate=1)})
public class ExactTargetSpecificActionsServlet
extends SlingAllMethodsServlet {
    private static final String CONFIGURATION_PATH = "cfgpath";
    private static final String PARAM_ERROR = "error";
    private static final String ENCODING_UTF_8 = "utf-8";
    private static final String CONTENT_TYPE_JSON = "application/json";
    private static final String PARAM_NEWSLETTER = "newsletter";
    private static final Logger log = LoggerFactory.getLogger(ExactTargetSpecificActionsServlet.class);
    private static final String PARAM_OPERATION = "operation";
    private static final String OPERATION_VIEW_PUBLISHED_EMAIL = "viewPublishedEmail";
    @Reference
    private EmailServiceProvider emailServiceProvider;
    @Reference
    private ConfigurationManagerFactory configurationManagerFactory;

    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        String errorMsg = "";
        try {
            this.handleRequest(request, response);
        }
        catch (Exception e) {
            log.error(e.getMessage(), (Throwable)e);
            errorMsg = e.getCause() instanceof UnknownHostException ? "Could not connect to " + e.getCause().getMessage() : "An exception occured.<br>" + e.getMessage();
            PrintWriter out = response.getWriter();
            this.writeResponse(out, "error", errorMsg);
        }
    }

    private void handleRequest(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ExactTargetException, IOException {
        String operation = request.getParameter("operation");
        if ("viewPublishedEmail".equals(operation)) {
            this.handleViewPublishedEmail(request, response);
        } else if ("getSendableDataExtensions".equals(operation)) {
            this.handleGetSendableDataExtensions(request, response);
        } else {
            throw new ExactTargetException("requested operation " + operation + " is not supported");
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void handleGetSendableDataExtensions(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException, ExactTargetException {
        PrintWriter out = response.getWriter();
        try {
            EmailService service;
            Configuration config = this.getConfiguration(request, response, false);
            if (config != null && (service = this.emailServiceProvider.getEmailService(config)) instanceof ExactTargetService) {
                String[] properties = new String[]{"Name", "CustomerKey"};
                SimpleFilterPart filter = new SimpleFilterPart();
                filter.setProperty("IsSendable");
                filter.setSimpleOperator(SimpleOperators.equals);
                filter.setValue(new String[]{"true"});
                List<DataExtension> dExts = ((ExactTargetService)service).retrieveDataExtension(config, properties, (FilterPart)filter);
                JSONArray jsonArray = new JSONArray();
                for (DataExtension dExt : dExts) {
                    try {
                        JSONObject jObj = new JSONObject();
                        jObj.put("text", (Object)dExt.getName());
                        jObj.put("value", (Object)dExt.getCustomerKey());
                        jsonArray.put((Object)jObj);
                    }
                    catch (JSONException e) {
                        log.error(e.getMessage());
                    }
                }
                out.write(jsonArray.toString());
            }
        }
        finally {
            out.flush();
        }
    }

    private void handleViewPublishedEmail(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException, ExactTargetException {
        String newsletter = request.getParameter("newsletter");
        if (newsletter == null) {
            this.writeResponse(response.getWriter(), "error", "Missing request parameters");
            return;
        }
        Configuration config = this.getConfiguration(request, response, false);
        if (config != null) {
            EmailService service = this.emailServiceProvider.getEmailService(config);
            if (service instanceof ExactTargetService) {
                Resource resource = request.getResourceResolver().resolve(newsletter);
                Node node = (Node)resource.adaptTo(Node.class);
                String entityId = null;
                try {
                    int val = (int)node.getProperty("entityID").getDouble();
                    entityId = Integer.toString(val);
                }
                catch (RepositoryException e) {
                    log.error("Error accessing node property: " + e.getMessage());
                    this.writeResponse(response.getWriter(), "error", e.getMessage());
                    return;
                }
                Map<String, String> urlToken = ((ExactTargetService)service).viewPublishedNewsletter(config, entityId);
                this.writeResponse(response.getWriter(), urlToken);
            } else {
                this.writeResponse(response.getWriter(), "error", "Email Service configuration provided does not match the requested one");
            }
        } else {
            this.writeResponse(response.getWriter(), "error", "ExactTarget Configuration Missing or not provided");
        }
    }

    private Configuration getConfiguration(SlingHttpServletRequest request, SlingHttpServletResponse response, boolean formSubmission) throws IOException {
        String path;
        Configuration config = null;
        if (!formSubmission) {
            path = request.getParameter("cfgpath");
        } else {
            ValueMap values = ResourceUtil.getValueMap((Resource)request.getResource());
            path = (String)values.get("cfgpath", String.class);
        }
        if (path != null) {
            ConfigurationManager cfgMgr = this.configurationManagerFactory.getConfigurationManager(request.getResourceResolver());
            config = cfgMgr.getConfiguration(path);
        }
        if (config == null && !formSubmission) {
            this.writeResponse(response.getWriter(), "error", "Configuration '" + path + "' not found");
        }
        return config;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void writeResponse(PrintWriter out, Map<String, String> keyValuePair) {
        JSONObject json = new JSONObject();
        try {
            for (Map.Entry<String, String> entry : keyValuePair.entrySet()) {
                json.put(entry.getKey(), (Object)entry.getValue());
            }
            out.write(json.toString());
        }
        catch (JSONException e) {
            log.error(e.getMessage(), (Throwable)e);
        }
        finally {
            out.flush();
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void writeResponse(PrintWriter out, String propertyname, String msg) {
        JSONObject returnValue = new JSONObject();
        try {
            returnValue.put(propertyname, (Object)msg);
            out.write(returnValue.toString());
        }
        catch (JSONException e) {
            log.error(e.getMessage(), (Throwable)e);
        }
        finally {
            out.flush();
        }
    }

    protected void bindEmailServiceProvider(EmailServiceProvider emailServiceProvider) {
        this.emailServiceProvider = emailServiceProvider;
    }

    protected void unbindEmailServiceProvider(EmailServiceProvider emailServiceProvider) {
        if (this.emailServiceProvider == emailServiceProvider) {
            this.emailServiceProvider = null;
        }
    }

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

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