SmartListManagementServlet.java 19.6 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.i18n.I18n
 *  javax.servlet.ServletException
 *  javax.servlet.http.HttpServletRequest
 *  org.apache.commons.collections.CollectionUtils
 *  org.apache.commons.lang.StringUtils
 *  org.apache.commons.lang.math.NumberUtils
 *  org.apache.felix.scr.annotations.sling.SlingServlet
 *  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.ValueMap
 *  org.apache.sling.api.servlets.SlingAllMethodsServlet
 *  org.apache.sling.api.wrappers.ValueMapDecorator
 *  org.apache.sling.auth.core.AuthUtil
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.cq.commerce.impl.smartlist;

import com.adobe.cq.commerce.api.CommerceException;
import com.adobe.cq.commerce.api.CommerceService;
import com.adobe.cq.commerce.api.CommerceSession;
import com.adobe.cq.commerce.api.Product;
import com.adobe.cq.commerce.api.smartlist.SmartList;
import com.adobe.cq.commerce.api.smartlist.SmartListEntry;
import com.adobe.cq.commerce.api.smartlist.SmartListManager;
import com.adobe.cq.commerce.impl.smartlist.SmartListEntryImpl;
import com.day.cq.i18n.I18n;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.felix.scr.annotations.sling.SlingServlet;
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.ValueMap;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.api.wrappers.ValueMapDecorator;
import org.apache.sling.auth.core.AuthUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SlingServlet(resourceTypes={"sling/servlet/default"}, selectors={"commerce.smartlist.management"}, methods={"POST"}, extensions={"html"}, label="Adobe CQ Commerce Smart List Management Servlet", description="Manages customers smart lists")
public class SmartListManagementServlet
extends SlingAllMethodsServlet {
    private static final Logger LOGGER = LoggerFactory.getLogger(SmartListManagementServlet.class);
    private static final String REQUEST_PARAM_OPERATION = ":operation";
    private static final String REQUEST_PARAM_REDIRECT = "redirect";
    private static final String REQUEST_PARAM_TITLE = "title";
    private static final String REQUEST_PARAM_DESCRIPTION = "description";
    private static final String REQUEST_PARAM_DEFAULT = "default";
    private static final String REQUEST_PARAM_DELETE = "delete";
    private static final String REQUEST_PARAM_PRIVACY = "privacy";
    private static final String REQUEST_PARAM_SMARTLIST_PATH = "smartlist-path";
    private static final String REQUEST_PARAM_PRODUCT_PATH = "product-path";
    private static final String REQUEST_PARAM_QUANTITY = "quantity";
    private static final String CREATE_SMARTLIST_OPERATION = "createSmartList";
    private static final String MANAGE_SMARTLISTS_OPERATION = "manageSmartLists";
    private static final String EDIT_SMARTLIST_OPERATION = "editSmartList";
    private static final String ADD_TO_SMARTLIST_OPERATION = "addToSmartList";
    private static final String SHARE_SMARTLIST_OPERATION = "shareSmartList";
    private static final String MOVE_SMARTLISTENTRY_OPERATION = "moveSmartListEntry";
    private static final String COPY_SMARTLISTENTRY_OPERATION = "copySmartListEntry";
    private static final String DELETE_SMARTLISTENTRY_OPERATION = "deleteSmartListEntry";
    private static final String MODIFY_SMARTLISTENTRY_OPERATION = "modifyQuantitySmartListEntry";
    private static final String ADD_TO_CART_OPERATION = "addToCart";

    protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
        String operation = request.getParameter(":operation");
        String redirectUrl = request.getParameter("redirect");
        I18n i18n = new I18n((HttpServletRequest)request);
        boolean success = true;
        CommerceService commerceService = (CommerceService)request.getResource().adaptTo(CommerceService.class);
        try {
            SmartList smartList;
            SmartList smartList2;
            String smartListPath;
            CommerceSession session = commerceService.login(request, response);
            SmartListManager smartListManager = session.getSmartListManager();
            if (smartListManager == null) {
                throw new CommerceException("SmartListManager is null, can not do anything here");
            }
            Map reqParamMap = request.getParameterMap();
            if ("addToSmartList".equals(operation)) {
                String productPath = request.getParameter("product-path");
                Resource productResource = request.getResourceResolver().getResource(productPath);
                Product product = (Product)productResource.adaptTo(Product.class);
                if (product != null) {
                    smartList2 = null;
                    boolean addNewSmartList = StringUtils.equals((String)request.getParameter("smartlist-select"), (String)"new");
                    if (!addNewSmartList && reqParamMap.containsKey("smartlist-path")) {
                        String smartListName = request.getParameter("smartlist-path");
                        smartList2 = smartListManager.getSmartList(smartListName);
                    } else if (addNewSmartList && reqParamMap.containsKey("title")) {
                        String listTitle = StringUtils.defaultIfEmpty((String)request.getParameter("title"), (String)i18n.get("My Smart List"));
                        boolean defaultList = StringUtils.equals((String)request.getParameter("default"), (String)"on");
                        smartList2 = this.createSmartList(smartListManager, listTitle, defaultList);
                    } else {
                        List<SmartList> smartLists = smartListManager.getSmartLists(null);
                        if (CollectionUtils.isNotEmpty(smartLists)) {
                            smartList2 = smartLists.get(0);
                        } else {
                            LOGGER.debug("User has no smart list, create a new default list before adding the product");
                            smartList2 = this.createSmartList(smartListManager, i18n.get("My Smart List"), true);
                        }
                    }
                    LOGGER.debug("Add product {} to smart list {}", (Object)product.getPath(), (Object)smartList2.getPath());
                    smartList2.add(productPath);
                    redirectUrl = redirectUrl + "?smartList=" + smartList2.getPath();
                }
            }
            if ("addToCart".equals(operation)) {
                if (reqParamMap.containsKey("smartlist-path")) {
                    boolean deleteSmartListEntry;
                    ArrayList<SmartListEntry> cartSmartListEntries;
                    deleteSmartListEntry = StringUtils.equals((String)request.getParameter("delete"), (String)"on");
                    cartSmartListEntries = new ArrayList<SmartListEntry>(1);
                    String smartListPath2 = request.getParameter("smartlist-path");
                    smartList2 = smartListManager.getSmartList(smartListPath2);
                    Iterator<SmartListEntry> smartListEntries = smartList2.getSmartListEntries();
                    if (reqParamMap.containsKey("product-path")) {
                        while (smartListEntries.hasNext()) {
                            SmartListEntry next = smartListEntries.next();
                            if (!StringUtils.equals((String)next.getProduct().getPath(), (String)request.getParameter("product-path"))) continue;
                            cartSmartListEntries.add(next);
                            break;
                        }
                    } else {
                        CollectionUtils.addAll(cartSmartListEntries, smartListEntries);
                    }
                    for (SmartListEntry cartSmartListEntry : cartSmartListEntries) {
                        session.addCartEntry(cartSmartListEntry.getProduct(), cartSmartListEntry.getQuantity());
                        if (!deleteSmartListEntry) continue;
                        smartList2.remove(cartSmartListEntry.getProduct().getPath());
                    }
                } else {
                    LOGGER.warn("can not add smart list entries to cart, parameters missing");
                    success = false;
                }
            }
            if ("createSmartList".equals(operation)) {
                String listTitle = StringUtils.defaultIfEmpty((String)request.getParameter("title"), (String)i18n.get("My Smart List"));
                boolean defaultList = StringUtils.equals((String)request.getParameter("default"), (String)"on");
                if (StringUtils.isNotEmpty((String)listTitle)) {
                    smartList = this.createSmartList(smartListManager, listTitle, defaultList);
                    redirectUrl = redirectUrl + "?smartList=" + smartList.getPath();
                } else {
                    LOGGER.warn("can not create new smart list, listTitle is empty");
                    success = false;
                }
            }
            if ("manageSmartLists".equals(operation)) {
                String defaultList;
                String[] listsMarkedPrivate;
                String[] listsToBeDeleted = request.getParameterValues("delete");
                if (listsToBeDeleted != null) {
                    for (String listName : listsToBeDeleted) {
                        smartListManager.deleteSmartList(listName);
                        LOGGER.debug("smart-list {} has been deleted", (Object)listName);
                    }
                }
                if (StringUtils.isNotEmpty((String)(defaultList = request.getParameter("default")))) {
                    smartList = smartListManager.getSmartList(defaultList);
                    if (smartList != null && !smartList.isDefault()) {
                        smartListManager.makeSmartListDefault(defaultList);
                        LOGGER.debug("smart-list {} has been marked as default", (Object)defaultList);
                    } else {
                        LOGGER.warn("can not make smart list {} default", (Object)defaultList);
                    }
                }
                if ((listsMarkedPrivate = request.getParameterValues("privacy")) != null) {
                    for (String smartListPath3 : listsMarkedPrivate) {
                        LOGGER.debug("set privacy of smart-list {} to personal", (Object)smartListPath3);
                        smartListManager.shareSmartList(smartListPath3, null);
                    }
                }
            }
            if ("editSmartList".equals(operation)) {
                if (reqParamMap.containsKey("smartlist-path")) {
                    smartListPath = request.getParameter("smartlist-path");
                    HashMap<String, Object> updateProperties = new HashMap<String, Object>();
                    if (reqParamMap.containsKey("title")) {
                        String listTitle = StringUtils.defaultIfEmpty((String)request.getParameter("title"), (String)i18n.get("My Smart List"));
                        updateProperties.put("jcr:title", listTitle);
                    }
                    if (reqParamMap.containsKey("description") && StringUtils.isNotEmpty((String)request.getParameter("description"))) {
                        updateProperties.put("jcr:description", request.getParameter("description"));
                    }
                    if (updateProperties.size() > 0) {
                        smartListManager.updateSmartList(smartListPath, updateProperties);
                    }
                } else {
                    LOGGER.warn("can not edit smart list, smart list path missing");
                    success = false;
                }
            }
            if ("deleteSmartListEntry".equals(operation) || "modifyQuantitySmartListEntry".equals(operation)) {
                if (reqParamMap.containsKey("smartlist-path") && reqParamMap.containsKey("product-path")) {
                    smartListPath = request.getParameter("smartlist-path");
                    String productPath = request.getParameter("product-path");
                    smartList = smartListManager.getSmartList(smartListPath);
                    if (smartList != null) {
                        if ("deleteSmartListEntry".equals(operation)) {
                            smartList.remove(productPath);
                            LOGGER.debug("removed product {} from smart list {}", (Object)productPath, (Object)smartListPath);
                        } else if ("modifyQuantitySmartListEntry".equals(operation)) {
                            HashMap<String, Object> updateProperties = new HashMap<String, Object>();
                            updateProperties.put("quantity", NumberUtils.toInt((String)request.getParameter("quantity"), (int)1));
                            smartList.update(productPath, updateProperties);
                            LOGGER.debug("product {} updated on smart list {}", (Object)productPath, (Object)smartListPath);
                        }
                    } else {
                        LOGGER.warn("can not delete or update smart list entry, smart list {} does not exist", (Object)smartListPath);
                        success = false;
                    }
                } else {
                    LOGGER.warn("can not delete or update smart list entry, parameters missing");
                    success = false;
                }
            }
            if ("moveSmartListEntry".equals(operation) || "copySmartListEntry".equals(operation)) {
                if (reqParamMap.containsKey("smartlist-path") && reqParamMap.containsKey("product-path") && reqParamMap.containsKey("smartlist-path-target")) {
                    String sourceSmartListPath = request.getParameter("smartlist-path");
                    String targetSmartListPath = request.getParameter("smartlist-path-target");
                    SmartList sourceSmartList = smartListManager.getSmartList(sourceSmartListPath);
                    SmartList targetSmartList = smartListManager.getSmartList(targetSmartListPath);
                    if (sourceSmartList != null && targetSmartList != null) {
                        String productPath = request.getParameter("product-path");
                        Resource productResource = request.getResourceResolver().getResource(productPath);
                        if (productResource != null) {
                            Product product = (Product)productResource.adaptTo(Product.class);
                            if (product != null && sourceSmartList.contains(product)) {
                                SmartListEntry sle = null;
                                Iterator<SmartListEntry> smartListEntries = sourceSmartList.getSmartListEntries();
                                while (smartListEntries.hasNext()) {
                                    SmartListEntry next = smartListEntries.next();
                                    if (!StringUtils.equals((String)next.getProduct().getPath(), (String)product.getPath())) continue;
                                    sle = next;
                                    break;
                                }
                                if (sle != null) {
                                    SmartListEntryImpl newSle = new SmartListEntryImpl(sle.getProduct(), this.cleanSmartListEntryProperties(sle.getProperties()));
                                    targetSmartList.add(newSle);
                                    if ("moveSmartListEntry".equals(operation)) {
                                        sourceSmartList.remove(sle.getProduct().getPath());
                                    }
                                } else {
                                    targetSmartList.add(product.getPath());
                                    if ("moveSmartListEntry".equals(operation)) {
                                        sourceSmartList.remove(product.getPath());
                                    }
                                }
                            }
                            redirectUrl = redirectUrl + "?smartList=" + targetSmartListPath;
                        } else {
                            LOGGER.warn("can not move smart list entries, product {} does not exist", (Object)productPath);
                            success = false;
                        }
                    } else {
                        LOGGER.warn("can not move smart list entries, source smart list {} or target smart list does not exist", (Object)sourceSmartListPath, (Object)targetSmartListPath);
                        success = false;
                    }
                } else {
                    LOGGER.warn("can not move smart list entries, smart list path missing");
                    success = false;
                }
            }
            if ("shareSmartList".equals(operation)) {
                if (reqParamMap.containsKey("smartlist-path") && reqParamMap.containsKey("smartlist-share-privacy")) {
                    smartListPath = request.getParameter("smartlist-path");
                    SmartList.Privacy sharePricay = SmartList.Privacy.valueOf(request.getParameter("smartlist-share-privacy"));
                    if (SmartList.Privacy.PERSONAL.equals((Object)sharePricay)) {
                        smartListManager.shareSmartList(smartListPath, null);
                    } else {
                        HashMap<String, Object> properties = new HashMap<String, Object>();
                        properties.put("smartlist_privacy_s", sharePricay.name());
                        smartListManager.shareSmartList(smartListPath, properties);
                    }
                } else {
                    LOGGER.warn("can not shart smart list entries, smart list path missing");
                    success = false;
                }
            }
        }
        catch (CommerceException e) {
            LOGGER.error("Error during smart list operations", (Throwable)e);
            success = false;
        }
        if (AuthUtil.isRedirectValid((HttpServletRequest)request, (String)redirectUrl) && success) {
            response.sendRedirect(redirectUrl);
        } else {
            response.sendError(403);
        }
    }

    private SmartList createSmartList(SmartListManager smartListManager, String title, boolean defaultList) throws CommerceException {
        HashMap<String, Object> properties = new HashMap<String, Object>();
        properties.put("jcr:title", title);
        SmartList smartList = smartListManager.createSmartList(title, properties);
        if (smartList != null) {
            if (defaultList) {
                smartListManager.makeSmartListDefault(smartList.getPath());
            }
            LOGGER.debug("created new smart list {}", (Object)smartList.getPath());
        }
        return smartList;
    }

    private ValueMap cleanSmartListEntryProperties(Map<String, Object> properties) {
        ValueMapDecorator newProperties = new ValueMapDecorator(properties);
        newProperties.remove((Object)"social:parentid");
        newProperties.remove((Object)"social:key");
        newProperties.remove((Object)"id");
        newProperties.remove((Object)"added");
        return newProperties;
    }
}