EmailServiceHandlerServlet.java 21.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.i18n.I18n
 *  com.day.cq.mcm.api.newsletter.NewsLetter
 *  com.day.cq.mcm.api.newsletter.NewsletterEmailService
 *  com.day.cq.mcm.core.NewsletterHelper
 *  com.day.cq.replication.Replicator
 *  com.day.cq.wcm.foundation.forms.FormsHelper
 *  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.jcr.Session
 *  javax.servlet.ServletException
 *  javax.servlet.http.HttpServletRequest
 *  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.apache.sling.commons.json.io.JSONWriter
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.mcm.emailprovider.servlets;

import com.day.cq.i18n.I18n;
import com.day.cq.mcm.api.newsletter.NewsLetter;
import com.day.cq.mcm.api.newsletter.NewsletterEmailService;
import com.day.cq.mcm.core.NewsletterHelper;
import com.day.cq.mcm.emailprovider.EmailService;
import com.day.cq.mcm.emailprovider.EmailServiceException;
import com.day.cq.mcm.emailprovider.service.EmailServiceProvider;
import com.day.cq.mcm.emailprovider.types.Email;
import com.day.cq.mcm.emailprovider.types.EmailServiceActions;
import com.day.cq.mcm.emailprovider.util.EmailHelper;
import com.day.cq.replication.Replicator;
import com.day.cq.wcm.foundation.forms.FormsHelper;
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.io.Writer;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
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.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.apache.sling.commons.json.io.JSONWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
@Service
@Properties(value={@org.apache.felix.scr.annotations.Property(name="sling.servlet.extensions", value={"json"}, propertyPrivate=1), @org.apache.felix.scr.annotations.Property(name="sling.servlet.selectors", value={"emailservice"}, propertyPrivate=1), @org.apache.felix.scr.annotations.Property(name="sling.servlet.resourceTypes", value={"sling/servlet/default"}), @org.apache.felix.scr.annotations.Property(name="sling.servlet.methods", value={"POST", "GET"}, propertyPrivate=1)})
public class EmailServiceHandlerServlet
extends SlingAllMethodsServlet {
    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 Logger log = LoggerFactory.getLogger(EmailServiceHandlerServlet.class);
    private static final String OPERATION_ADDSUBSCRIBER = "addToList";
    private static final String OPERATION_DELETESUBSCRIBER = "deleteFromList";
    private static final String OPERATION_AUTORESPONDEREMAIL = "sendAutoResponderMail";
    private static final String PARAM_PATH = "cfgpath";
    private static final String PARAM_OPERATION = "operation";
    private static final int STATUS_NO_LETTER = -10;
    private static final int STATUS_CQ_PUBLISH_OUTDATED = 9;
    private static final int STATUS_NO_REPLICATOR = -12;
    private static final int STATUS_REPLICATION_EXCEPTION = -13;
    private static final String KEY_STATUS_MESSAGE = "testStatusText";
    private static final String KEY_STATUS = "testStatus";
    @Reference
    private EmailServiceProvider emailServiceProvider;
    @Reference
    private ConfigurationManagerFactory configurationManagerFactory;
    @Reference
    private NewsletterEmailService newsletterService;
    @Reference
    private Replicator repl;

    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 IOException {
        String operation = request.getParameter("operation");
        if (operation == null) {
            operation = this.getActionType(request);
        }
        EmailServiceActions op = null;
        try {
            Object serviceResponse;
            op = this.getEmailServiceAction(operation);
            if (op == null) {
                response.sendError(400, I18n.get((HttpServletRequest)request, (String)"Requested Operation not supported: {0}", (String)null, (Object[])new Object[]{operation}));
            }
            ConfigurationManager cfgMgr = this.configurationManagerFactory.getConfigurationManager(request.getResourceResolver());
            if (op == EmailServiceActions.PUBLISH_EMAIL || op == EmailServiceActions.UPDATE_EMAIL) {
                this.handlePublishEmail(request, response, op, cfgMgr);
                return;
            }
            Map<String, Object> requestParams = this.getRequestParams(op, request);
            Configuration config = this.getConfiguration(request, response, cfgMgr);
            if (config == null && op != EmailServiceActions.CONNECT && op != EmailServiceActions.GET_ACCOUNTS) {
                response.sendError(400, I18n.get((HttpServletRequest)request, (String)"EmailService configuration not found or missing"));
            }
            EmailService service = null;
            service = config == null ? this.getEmailService(request, cfgMgr) : this.emailServiceProvider.getEmailService(config);
            if (service == null) {
                response.sendError(503, I18n.get((HttpServletRequest)request, (String)"Requested EmailService not available"));
            }
            if ((serviceResponse = service.execute(op, requestParams, config)) != null) {
                this.writeJSONResponse(serviceResponse, response.getWriter());
            }
            if (op == EmailServiceActions.ADD_SUBSCRIBER || op == EmailServiceActions.DELETE_SUBSCRIBER || op == EmailServiceActions.SEND_AUTO_RESPONDER) {
                EmailHelper.redirectUrl(false, request, response);
            }
        }
        catch (EmailServiceException e) {
            log.error(e.getMessage());
            if (op == EmailServiceActions.ADD_SUBSCRIBER || op == EmailServiceActions.DELETE_SUBSCRIBER || op == EmailServiceActions.SEND_AUTO_RESPONDER) {
                this.redirectOnFormError(request, response, I18n.get((HttpServletRequest)request, (String)"Could not complete request. Please try again later."));
            }
            response.sendError(400, "");
        }
    }

    private JSONArray getJSONFromList(List<Object> list) {
        JSONArray jsonArray = new JSONArray();
        try {
            for (Object object : list) {
                if (object instanceof List) {
                    jsonArray.put((Object)this.getJSONFromList((List)object));
                    continue;
                }
                if (object instanceof Map) {
                    jsonArray.put((Object)this.getJSONFromMap((Map)object));
                    continue;
                }
                jsonArray.put((Object)object.toString());
            }
        }
        catch (Exception e) {
            log.error(e.getMessage());
        }
        return jsonArray;
    }

    private void writeJSONResponse(Object serviceResponse, PrintWriter writer) {
        try {
            if (serviceResponse instanceof List) {
                JSONArray jsonArray = this.getJSONFromList((List)serviceResponse);
                writer.write(jsonArray.toString());
            } else if (serviceResponse instanceof Map) {
                JSONObject jsonObject = this.getJSONFromMap((Map)serviceResponse);
                writer.write(jsonObject.toString());
            } else {
                JSONArray wrapObject = new JSONArray().put((Object)serviceResponse.toString());
                writer.write(wrapObject.toString());
            }
        }
        catch (Exception e) {
            log.error(e.getMessage());
        }
        writer.flush();
    }

    private JSONObject getJSONFromMap(Map<String, Object> map) {
        JSONObject jsonObject = new JSONObject();
        try {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                if (value instanceof Map) {
                    value = this.getJSONFromMap((Map)value);
                } else if (value instanceof List) {
                    value = this.getJSONFromList((List)value);
                }
                jsonObject.put(key, value);
            }
        }
        catch (Exception e) {
            log.error(e.getMessage());
        }
        return jsonObject;
    }

    private Map<String, Object> getRequestParams(EmailServiceActions op, SlingHttpServletRequest request) {
        HashMap<String, Object> requestParams = new HashMap<String, Object>();
        Enumeration paramsNames = request.getParameterNames();
        while (paramsNames.hasMoreElements()) {
            String key = (String)paramsNames.nextElement();
            requestParams.put(key, request.getParameter(key));
        }
        if (op == EmailServiceActions.ADD_SUBSCRIBER || op == EmailServiceActions.DELETE_SUBSCRIBER || op == EmailServiceActions.SEND_AUTO_RESPONDER) {
            ValueMap values = ResourceUtil.getValueMap((Resource)request.getResource());
            requestParams.putAll((Map<String, Object>)values);
            Iterator formFieldsIter = FormsHelper.getFormElements((Resource)request.getResource());
            ArrayList<String> fieldNames = new ArrayList<String>();
            while (formFieldsIter.hasNext()) {
                Resource fieldResource = (Resource)formFieldsIter.next();
                ValueMap valueMap = ResourceUtil.getValueMap((Resource)fieldResource);
                String name = (String)valueMap.get("name", String.class);
                if (name == null || request.getParameter(name) == null) continue;
                fieldNames.add(name);
            }
            requestParams.put("formFields", fieldNames);
        }
        return requestParams;
    }

    private EmailServiceActions getEmailServiceAction(String operation) {
        for (EmailServiceActions action : EmailServiceActions.values()) {
            if (!action.toString().equals(operation)) continue;
            return action;
        }
        return null;
    }

    private void redirectOnFormError(SlingHttpServletRequest request, SlingHttpServletResponse response, String error) throws IOException {
        log.error(error);
        Node formStart = (Node)request.getResource().adaptTo(Node.class);
        try {
            formStart.setProperty("MCMFormError", error);
            formStart.getSession().save();
        }
        catch (Exception e) {
            log.error(e.getMessage(), (Throwable)e);
        }
        EmailHelper.redirectUrl(true, request, response);
    }

    private Configuration getConfiguration(SlingHttpServletRequest request, SlingHttpServletResponse response, ConfigurationManager cfgMgr) throws IOException {
        Configuration config = null;
        String path = request.getParameter("cfgpath");
        if (path == null) {
            ValueMap values = ResourceUtil.getValueMap((Resource)request.getResource());
            path = (String)values.get("cfgpath", String.class);
        }
        if (path != null) {
            config = cfgMgr.getConfiguration(path);
        }
        return config;
    }

    /*
     * 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();
        }
    }

    private EmailService getEmailService(SlingHttpServletRequest request, ConfigurationManager cfgMgr) throws EmailServiceException {
        EmailService emailService = null;
        Configuration config = null;
        String path = request.getParameter("cfgpath");
        if (path != null) {
            config = cfgMgr.getConfiguration(path);
        }
        String providerName = null;
        if (config != null) {
            emailService = this.emailServiceProvider.getEmailService(config);
        } else {
            providerName = request.getParameter("providerName");
            emailService = this.emailServiceProvider.getEmailService(providerName);
        }
        if (emailService == null) {
            throw new EmailServiceException("Unable to locate any EmailService for this request, Path: " + path + ", Name: " + providerName);
        }
        return emailService;
    }

    private String getActionType(SlingHttpServletRequest request) {
        String addSubscriber = "addSubscriber";
        String autoResponder = "autoResponder";
        String deleteSubscriber = "deleteSubscriber";
        ValueMap values = ResourceUtil.getValueMap((Resource)request.getResource());
        String actionType = (String)values.get("actionType", String.class);
        if (actionType.indexOf("addSubscriber") != -1) {
            return "addToList";
        }
        if (actionType.indexOf("deleteSubscriber") != -1) {
            return "deleteFromList";
        }
        if (actionType.indexOf("autoResponder") != -1) {
            return "sendAutoResponderMail";
        }
        return "";
    }

    private void handlePublishEmail(SlingHttpServletRequest request, SlingHttpServletResponse response, EmailServiceActions op, ConfigurationManager cfgMgr) throws IOException {
        try {
            Configuration config = this.getConfiguration(request, response, cfgMgr);
            EmailService emailService = null;
            PrintWriter out = response.getWriter();
            JSONWriter json = new JSONWriter((Writer)out);
            json.object();
            if (config == null) {
                json.key("testStatus").value(500);
                json.key("testStatusText").value((Object)I18n.get((HttpServletRequest)request, (String)"Email Service configuration not found"));
                json.endObject();
                return;
            }
            emailService = this.emailServiceProvider.getEmailService(config);
            if (this.newsletterService == null || emailService == null) {
                response.sendError(503);
                return;
            }
            String path = request.getParameter("newsletter");
            if (path == null) {
                response.sendError(400);
                return;
            }
            NewsLetter letter = null;
            try {
                letter = NewsletterHelper.fromRequest((SlingHttpServletRequest)request, (NewsletterEmailService)this.newsletterService);
            }
            catch (RepositoryException e1) {
                log.error("Error while accesing repository: ", (Object)e1.getMessage());
                json.key("testStatus").value(2);
                json.key("testStatusText").value((Object)I18n.get((HttpServletRequest)request, (String)"Error while accesing repository."));
            }
            if (letter == null) {
                json.key("testStatus").value(-10);
                json.key("testStatusText").value((Object)I18n.get((HttpServletRequest)request, (String)"Letter could not be built"));
            } else if (!NewsletterHelper.isPublishUptodate((NewsLetter)letter, (ResourceResolver)request.getResourceResolver())) {
                json.key("testStatus").value(9);
            } else {
                int code = 0;
                String msg = null;
                try {
                    String name = request.getParameter("name");
                    Email email = EmailHelper.getEmail(name, letter);
                    Resource emailResource = request.getResourceResolver().resolve(path);
                    HashMap<String, Object> requestParams = new HashMap<String, Object>(request.getParameterMap());
                    requestParams.put("subject", email.getSubject());
                    requestParams.put("content", email.getContent());
                    requestParams.put("isHtml", email.isHtml());
                    requestParams.put("name", email.getName());
                    requestParams.put("resource", (Object)emailResource);
                    if (ResourceUtil.isNonExistingResource((Resource)emailResource)) {
                        throw new Exception(I18n.get((HttpServletRequest)request, (String)"Email Resource does not exist"));
                    }
                    if (op == EmailServiceActions.PUBLISH_EMAIL) {
                        emailService.execute(EmailServiceActions.PUBLISH_EMAIL, requestParams, config);
                        msg = I18n.get((HttpServletRequest)request, (String)"{0} successfully published to Email Service provider.", (String)null, (Object[])new Object[]{name});
                    } else if (op == EmailServiceActions.UPDATE_EMAIL) {
                        emailService.execute(EmailServiceActions.UPDATE_EMAIL, requestParams, config);
                        msg = I18n.get((HttpServletRequest)request, (String)"{0} successfully updated to Email Service Provider.", (String)null, (Object[])new Object[]{name});
                    }
                }
                catch (EmailServiceException e) {
                    log.error(e.getMessage());
                    code = 500;
                    msg = I18n.get((HttpServletRequest)request, (String)"Could not publish. Make sure Email Settings are appropriate.");
                }
                catch (Exception e) {
                    code = 500;
                    msg = I18n.get((HttpServletRequest)request, (String)"Could not publish. Make sure Email Settings are appropriate.");
                    log.error("Email Service Publish: error on publish:", (Throwable)e);
                }
                json.key("testStatus").value((long)code);
                json.key("testStatusText").value((Object)msg);
            }
            json.endObject();
        }
        catch (JSONException e) {
            log.error(e.getMessage());
        }
    }

    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;
        }
    }

    protected void bindNewsletterService(NewsletterEmailService newsletterEmailService) {
        this.newsletterService = newsletterEmailService;
    }

    protected void unbindNewsletterService(NewsletterEmailService newsletterEmailService) {
        if (this.newsletterService == newsletterEmailService) {
            this.newsletterService = null;
        }
    }

    protected void bindRepl(Replicator replicator) {
        this.repl = replicator;
    }

    protected void unbindRepl(Replicator replicator) {
        if (this.repl == replicator) {
            this.repl = null;
        }
    }
}