ProductCollectionServlet.java 16.1 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.ui.components.HtmlResponse
 *  com.adobe.granite.xss.XSSAPI
 *  com.day.cq.commons.jcr.JcrUtil
 *  com.day.cq.i18n.I18n
 *  javax.servlet.ServletException
 *  javax.servlet.http.HttpServletRequest
 *  javax.servlet.http.HttpServletResponse
 *  org.apache.commons.lang.StringUtils
 *  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.PersistenceException
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceUtil
 *  org.apache.sling.api.servlets.SlingAllMethodsServlet
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.cq.commerce.impl.collection;

import com.adobe.cq.commerce.api.CommerceException;
import com.adobe.cq.commerce.api.collection.ProductCollection;
import com.adobe.cq.commerce.api.collection.ProductCollectionManager;
import com.adobe.granite.ui.components.HtmlResponse;
import com.adobe.granite.xss.XSSAPI;
import com.day.cq.commons.jcr.JcrUtil;
import com.day.cq.i18n.I18n;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
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.PersistenceException;
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.servlets.SlingAllMethodsServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(metatype=1, label="Day CQ Commerce Product Collection Servlet", description="Manages Product Collections")
@Service
@Properties(value={@Property(name="sling.servlet.resourceTypes", value={"sling/servlet/default"}), @Property(name="sling.servlet.methods", value={"GET", "POST"}), @Property(name="sling.servlet.selectors", value={"productcollection"})})
public class ProductCollectionServlet
extends SlingAllMethodsServlet {
    private final Logger log = LoggerFactory.getLogger(ProductCollectionServlet.class);
    private static final String REQUEST_PARAM_OPERATION = ":operation";
    private static final String REQUEST_PARAM_COLLECTION_PARENT_PATH = "collectionParentPath";
    private static final String REQUEST_PARAM_COLLECTION_PATH = "collectionPath";
    private static final String REQUEST_PARAM_COLLECTION_TITLE = "collectionTitle";
    private static final String REQUEST_PARAM_COLLECTION_DESC = "collectionDescription";
    private static final String REQUEST_PARAM_COLLECTION_TYPE = "collectionType";
    private static final String REQUEST_PARAM_REFERENCE_PATHS = "referencePaths";
    private static final String REQUEST_PARAM_BASE_PATH = "basePath";
    private static final String REQUEST_PARAM_MATCH_TAGS = "matchTags";
    private static final String REQUEST_PARAM_QUERY_TEXT = "search";
    private static final String REQUEST_PARAM_QUERY_TYPE = "searchType";
    private static final String CREATE_COLLECTION_OPERATION = "createCollection";
    private static final String UPDATE_COLLECTION_OPERATION = "updateCollection";
    private static final String UPDATE_COLLECTION_PROPS_OPERATION = "updateCollectionProperties";
    private static final String REMOVE_COLLECTION_OPERATION = "removeCollection";
    private static final String ADD_REFERENCE_OPERATION = "addReferences";
    private static final String REMOVE_REFERENCE_OPERATION = "removeReferences";
    @Reference
    private XSSAPI xssApi;

    protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
        XSSAPI xssAPI = this.xssApi.getRequestSpecificAPI(request);
        I18n i18n = new I18n((HttpServletRequest)request);
        Resource res = request.getResource();
        String redirectUrl = request.getContextPath() + res.getPath();
        String parentLocation = request.getContextPath() + res.getParent().getPath();
        HtmlResponse htmlRes = new HtmlResponse(xssAPI, i18n, request.getLocale());
        ResourceResolver resolver = request.getResourceResolver();
        ProductCollectionManager productCollectionManager = (ProductCollectionManager)resolver.adaptTo(ProductCollectionManager.class);
        String operation = request.getParameter(":operation");
        String collectionParentPath = request.getParameter("collectionParentPath");
        String collectionPath = request.getParameter("collectionPath");
        if (StringUtils.isEmpty((String)collectionParentPath)) {
            collectionParentPath = request.getResource().getPath();
        }
        if (StringUtils.isEmpty((String)collectionPath)) {
            collectionPath = request.getResource().getPath();
        }
        String collectionTitle = request.getParameter("collectionTitle");
        String collectionDescription = request.getParameter("collectionDescription");
        String collectionType = request.getParameter("collectionType");
        String basePath = request.getParameter("basePath");
        String[] matchTags = request.getParameterValues("matchTags");
        String search = request.getParameter("search");
        String searchType = request.getParameter("searchType");
        String[] productPaths = request.getParameterValues("referencePaths");
        HashMap<String, Object> collectionProperties = new HashMap<String, Object>();
        if (StringUtils.isNotEmpty((String)collectionTitle)) {
            collectionProperties.put("jcr:title", collectionTitle);
        }
        if (StringUtils.isNotEmpty((String)collectionDescription)) {
            collectionProperties.put("jcr:description", collectionDescription);
        }
        if (StringUtils.isNotEmpty((String)collectionType)) {
            collectionProperties.put("commerce.collection.type", collectionType);
        }
        if (StringUtils.isNotEmpty((String)basePath)) {
            collectionProperties.put("basePath", basePath);
        }
        if (matchTags != null && matchTags.length > 0) {
            collectionProperties.put("matchTags", matchTags);
        }
        if (StringUtils.isNotEmpty((String)search)) {
            collectionProperties.put("search", search);
        }
        if (StringUtils.isNotEmpty((String)searchType)) {
            collectionProperties.put("searchType", searchType);
        }
        ProductCollection productCollection = productCollectionManager.getCollection(collectionPath);
        if (StringUtils.isEmpty((String)operation)) {
            return;
        }
        if ("createCollection".equals(operation)) {
            try {
                String status;
                String name = this.createUniqueChildName(resolver, collectionParentPath, collectionTitle);
                ProductCollection newProductCollection = productCollectionManager.createCollection(collectionParentPath, name, collectionProperties);
                this.addToCollection(newProductCollection, productPaths);
                String statusTitle = status = i18n.get("Created");
                String statusDesc = i18n.get("<div id=\"Message\">Created {0}</div>", "response description", new Object[]{newProductCollection.getPath()});
                this.setResponseObject(htmlRes, 201, status, statusTitle, statusDesc, collectionParentPath, newProductCollection.getPath(), request.getContextPath() + newProductCollection.getPath());
                htmlRes.onCreated(newProductCollection.getPath());
                htmlRes.setCreateRequest(true);
            }
            catch (Exception e) {
                String errorMsg = "Error while creating the new collection.";
                this.log.error(errorMsg, (Throwable)e);
                String status = errorMsg;
                String statusTitle = errorMsg;
                String statusDesc = i18n.get("<div id=\"Message\">" + errorMsg + "</div>");
                this.setResponseObject(htmlRes, 500, status, statusTitle, statusDesc, parentLocation, res.getPath(), redirectUrl);
            }
        } else if ("updateCollection".equals(operation)) {
            try {
                String status;
                productCollectionManager.updateCollection(productCollection, collectionProperties);
                Iterator<String> it = productCollection.getDirectReferences();
                while (it.hasNext()) {
                    String reference = it.next();
                    productCollection.remove(reference);
                }
                this.addToCollection(productCollection, productPaths);
                String statusTitle = status = i18n.get("Updated collection");
                String statusDesc = i18n.get("<div id=\"Message\">Updated {0}</div>", "response description", new Object[]{productCollection.getPath()});
                this.setResponseObject(htmlRes, 200, status, statusTitle, statusDesc, parentLocation, res.getPath(), redirectUrl);
            }
            catch (Exception e) {
                String errorMsg;
                this.log.error("Could not update the collection {}.", (Object)collectionPath, (Object)e);
                String status = errorMsg = "Error while updating the collection.";
                String statusTitle = i18n.get("<div id=\"Message\">" + errorMsg + "</div>");
                String statusDesc = errorMsg;
                this.setResponseObject(htmlRes, 500, status, statusTitle, statusDesc, parentLocation, res.getPath(), redirectUrl);
            }
        } else if ("updateCollectionProperties".equals(operation)) {
            try {
                String status;
                productCollectionManager.updateCollection(productCollection, collectionProperties);
                String statusTitle = status = i18n.get("Updated collection properties");
                String statusDesc = i18n.get("<div id=\"Message\">Updated properties for collection {0}</div>", "response description", new Object[]{productCollection.getPath()});
                this.setResponseObject(htmlRes, 200, status, statusTitle, statusDesc, parentLocation, res.getPath(), redirectUrl);
            }
            catch (Exception e) {
                String errorMsg;
                this.log.error("Could not update properties for the collection {}.", (Object)collectionPath, (Object)e);
                String status = errorMsg = "Error while updating the collection properties.";
                String statusTitle = i18n.get("<div id=\"Message\">" + errorMsg + "</div>");
                String statusDesc = errorMsg;
                this.setResponseObject(htmlRes, 500, status, statusTitle, statusDesc, parentLocation, res.getPath(), redirectUrl);
            }
        } else if ("removeCollection".equals(operation)) {
            try {
                String status;
                productCollectionManager.deleteCollection(productCollection);
                String statusTitle = status = i18n.get("Removed collection");
                String statusDesc = i18n.get("<div id=\"Message\">Removed {0}</div>", "response description", new Object[]{productCollection.getPath()});
                this.setResponseObject(htmlRes, 200, status, statusTitle, statusDesc, parentLocation, res.getPath(), redirectUrl);
            }
            catch (Exception e) {
                String errorMsg;
                this.log.error("Could not remove the collection {}", (Object)collectionPath, (Object)e);
                String status = errorMsg = "Could not remove the collection.";
                String statusTitle = i18n.get("<div id=\"Message\">" + errorMsg + "</div>");
                String statusDesc = errorMsg;
                this.setResponseObject(htmlRes, 500, status, statusTitle, statusDesc, parentLocation, res.getPath(), redirectUrl);
            }
        } else if ("addReferences".equals(operation)) {
            try {
                String status;
                this.addToCollection(productCollection, productPaths);
                String statusTitle = status = i18n.get("Added members to collection");
                String statusDesc = i18n.get("<div id=\"Message\">Added members to collection {0}</div>", "response description", new Object[]{productCollection.getPath()});
                this.setResponseObject(htmlRes, 200, status, statusTitle, statusDesc, parentLocation, res.getPath(), redirectUrl);
            }
            catch (Exception e) {
                String errorMsg;
                this.log.error("Error while adding members to the collection {}", (Object)collectionPath, (Object)e);
                String status = errorMsg = "Error while adding members to the collection.";
                String statusTitle = i18n.get("<div id=\"Message\">" + errorMsg + "</div>");
                String statusDesc = errorMsg;
                this.setResponseObject(htmlRes, 500, status, statusTitle, statusDesc, parentLocation, res.getPath(), redirectUrl);
            }
        } else if ("removeReferences".equals(operation)) {
            try {
                String status;
                this.removeFromCollection(productCollection, productPaths);
                String statusTitle = status = i18n.get("Removed members from collection");
                String statusDesc = i18n.get("<div id=\"Message\">Removed members from collection {0}</div>", "response description", new Object[]{productCollection.getPath()});
                this.setResponseObject(htmlRes, 200, status, statusTitle, statusDesc, parentLocation, res.getPath(), redirectUrl);
            }
            catch (Exception e) {
                String errorMsg;
                this.log.error("Error while removing members from the collection {}", (Object)collectionPath, (Object)e);
                String status = errorMsg = "Error while removing members from the collection.";
                String statusTitle = i18n.get("<div id=\"Message\">" + errorMsg + "</div>");
                String statusDesc = errorMsg;
                this.setResponseObject(htmlRes, 500, status, statusTitle, statusDesc, parentLocation, res.getPath(), redirectUrl);
            }
        }
        htmlRes.send((HttpServletResponse)response, true);
    }

    private void addToCollection(ProductCollection coll, String[] paths) throws CommerceException {
        if (paths != null && paths.length > 0) {
            for (String path : paths) {
                coll.add(path);
            }
        }
    }

    private void removeFromCollection(ProductCollection coll, String[] paths) throws CommerceException {
        if (paths != null && paths.length > 0) {
            for (String path : paths) {
                coll.remove(path);
            }
        }
    }

    private void setResponseObject(HtmlResponse response, int statusCode, String status, String title, String desc, String parentLocation, String path, String location) {
        response.setStatus(statusCode, status);
        response.setTitle(title);
        response.setDescription(desc);
        response.setParentLocation(parentLocation);
        response.setLocation(location);
        response.setPath(path);
    }

    private String createUniqueChildName(ResourceResolver resolver, String parentPath, String nameHint) throws PersistenceException {
        String jcrNameHint = JcrUtil.createValidName((String)nameHint);
        Resource parent = resolver.getResource(parentPath);
        return ResourceUtil.createUniqueChildName((Resource)parent, (String)jcrNameHint);
    }

    protected void bindXssApi(XSSAPI xSSAPI) {
        this.xssApi = xSSAPI;
    }

    protected void unbindXssApi(XSSAPI xSSAPI) {
        if (this.xssApi == xSSAPI) {
            this.xssApi = null;
        }
    }
}