OmniSearchSuggestionServlet.java 10.3 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.i18n.I18n
 *  javax.jcr.Node
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.servlet.Servlet
 *  javax.servlet.ServletException
 *  javax.servlet.http.HttpServletRequest
 *  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.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.servlets.SlingSafeMethodsServlet
 *  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.adobe.granite.omnisearch.impl.servlets;

import com.adobe.granite.omnisearch.api.core.OmniSearchService;
import com.adobe.granite.omnisearch.api.suggestion.PredicateSuggestion;
import com.adobe.granite.omnisearch.api.suggestion.SuggestionResult;
import com.adobe.granite.omnisearch.spi.core.OmniSearchHandler;
import com.day.cq.i18n.I18n;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
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.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
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;

@Component(immediate=1, metatype=0)
@Service(value={Servlet.class})
@Properties(value={@Property(name="sling.servlet.resourceTypes", value={"/libs/granite/omnisearch/components/suggest"})})
public class OmniSearchSuggestionServlet
extends SlingSafeMethodsServlet {
    private static final Logger log = LoggerFactory.getLogger(OmniSearchSuggestionServlet.class);
    private static final String FULLTEXT = "fulltext";
    private static ConcurrentHashMap<String, OmniSearchHandler> handlerConcurrentHashMap = new ConcurrentHashMap();
    @Reference
    private OmniSearchService omniSearchService;

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

    private Writer getJsonOutputWriter(SlingHttpServletResponse response) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        return out;
    }

    private void handleSuggestionQuery(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
        Map predicateParameters = request.getParameterMap();
        String searchTerm = null;
        String location = this.getLocation(predicateParameters);
        if (predicateParameters.containsKey("fulltext")) {
            String[] valueArray = (String[])predicateParameters.get("fulltext");
            String string = searchTerm = valueArray.length == 0 ? null : valueArray[0];
        }
        if (searchTerm == null) {
            log.warn("No query term has been provided. No suggestion require");
            return;
        }
        ResourceResolver resourceResolver = request.getResourceResolver();
        Map<String, SuggestionResult> suggestionResults = this.omniSearchService.getSuggestions(resourceResolver, new I18n((HttpServletRequest)request), searchTerm, location);
        if (suggestionResults == null) {
            log.debug("no suggestion obtained for search term {} and location {}", (Object)searchTerm, (Object)location);
            return;
        }
        JSONObject result = new JSONObject();
        JSONArray suggestionJsonList = new JSONArray();
        HashSet<String> suggestionsSet = new HashSet<String>();
        ArrayList<JSONObject> availableModules = new ArrayList<JSONObject>();
        ArrayList<JSONObject> predicateSuggestionJsonList = new ArrayList<JSONObject>();
        HashSet<String> spellCheckSuggestionJsonList = new HashSet<String>();
        Writer out = this.getJsonOutputWriter(response);
        try {
            for (String key : suggestionResults.keySet()) {
                List<String> spellcheckSuggestions;
                List<PredicateSuggestion> predicateSuggestions;
                List<String> suggestions;
                SuggestionResult currSuggestionResult = suggestionResults.get(key);
                Resource moduleConfigRes = this.omniSearchService.getModuleConfiguration(resourceResolver, key);
                if (moduleConfigRes != null) {
                    Node contentNode = (Node)moduleConfigRes.adaptTo(Node.class);
                    JSONObject moduleDetails = new JSONObject();
                    if (contentNode.hasProperty("jcr:title")) {
                        moduleDetails.put("name", (Object)contentNode.getProperty("jcr:title").getString());
                        String contentNodePath = contentNode.getPath();
                        if (contentNodePath != null && contentNodePath.startsWith("/")) {
                            contentNodePath = request.getContextPath() + contentNodePath;
                        }
                        moduleDetails.put("contentNodePath", (Object)contentNodePath);
                        moduleDetails.put("id", (Object)key);
                        availableModules.add(moduleDetails);
                    }
                }
                if ((predicateSuggestions = currSuggestionResult.getPredicateSuggestions()) != null && !predicateSuggestions.isEmpty()) {
                    for (PredicateSuggestion predicateSuggestion : predicateSuggestions) {
                        Map<String, String> queryParameters;
                        JSONObject predicateDetails = new JSONObject();
                        predicateDetails.put("type", (Object)predicateSuggestion.getType());
                        predicateDetails.put("value", (Object)predicateSuggestion.getOptionTitle());
                        String typePath = predicateSuggestion.getTypePath();
                        String titlePath = predicateSuggestion.getOptionPath();
                        if (typePath != null && titlePath != null) {
                            predicateDetails.put("typePath", (Object)typePath);
                            predicateDetails.put("valuePath", (Object)titlePath);
                        }
                        if ((queryParameters = predicateSuggestion.getQueryParameters()) != null) {
                            JSONObject queryParametersJSON = new JSONObject();
                            for (String parameterKey : queryParameters.keySet()) {
                                queryParametersJSON.put(parameterKey, (Object)queryParameters.get(parameterKey));
                            }
                            predicateDetails.put("queryParameters", (Object)queryParametersJSON);
                        }
                        predicateSuggestionJsonList.add(predicateDetails);
                    }
                }
                if ((spellcheckSuggestions = currSuggestionResult.getSpellcheckSuggestions()) != null && !spellcheckSuggestions.isEmpty()) {
                    spellCheckSuggestionJsonList.addAll(spellcheckSuggestions);
                }
                if ((suggestions = currSuggestionResult.getSuggestions()) == null || suggestions.isEmpty()) continue;
                for (String suggestion : suggestions) {
                    suggestionsSet.add(StringUtils.capitalize((String)suggestion.toLowerCase()));
                }
            }
            if (!availableModules.isEmpty()) {
                result.put("availableModules", availableModules);
            }
            if (!predicateSuggestionJsonList.isEmpty()) {
                result.put("predicateSuggestions", predicateSuggestionJsonList);
            }
            if (!spellCheckSuggestionJsonList.isEmpty()) {
                result.put("spellcheckSuggestion", spellCheckSuggestionJsonList);
            }
            if (!suggestionsSet.isEmpty()) {
                for (String suggestion : suggestionsSet) {
                    JSONObject suggestionObj = new JSONObject();
                    suggestionObj.put("suggestion", (Object)suggestion);
                    suggestionJsonList.put((Object)suggestionObj);
                }
                result.put("suggestions", (Object)suggestionJsonList);
            }
        }
        catch (RepositoryException e) {
            log.error("Error while creating Json Response for Suggestion", (Throwable)e);
        }
        catch (JSONException e) {
            log.error("Error while creating Json Response for Suggestion", (Throwable)e);
        }
        out.write(result.toString());
    }

    private String getLocation(Map<String, String[]> predicateParameters) {
        String location = null;
        if (predicateParameters.containsKey("location")) {
            String[] valueArray = predicateParameters.get("location");
            location = valueArray.length == 0 ? null : valueArray[0];
        }
        return location;
    }

    protected void bindOmniSearchService(OmniSearchService omniSearchService) {
        this.omniSearchService = omniSearchService;
    }

    protected void unbindOmniSearchService(OmniSearchService omniSearchService) {
        if (this.omniSearchService == omniSearchService) {
            this.omniSearchService = null;
        }
    }
}