ViewHandler.java 8.45 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.commons.feed.StringResponseWrapper
 *  com.day.cq.tagging.Tag
 *  com.day.cq.tagging.TagManager
 *  javax.jcr.Session
 *  javax.servlet.RequestDispatcher
 *  javax.servlet.ServletException
 *  javax.servlet.ServletRequest
 *  javax.servlet.ServletResponse
 *  org.apache.commons.collections.Predicate
 *  org.apache.sling.api.SlingHttpServletRequest
 *  org.apache.sling.api.SlingHttpServletResponse
 *  org.apache.sling.api.request.RequestDispatcherOptions
 *  org.apache.sling.api.request.RequestPathInfo
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  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.wcm.core.contentfinder;

import com.day.cq.commons.feed.StringResponseWrapper;
import com.day.cq.tagging.Tag;
import com.day.cq.tagging.TagManager;
import com.day.cq.wcm.core.contentfinder.ContentFinderListInfoProviderHelper;
import com.day.cq.wcm.core.contentfinder.Hit;
import com.day.cq.wcm.core.contentfinder.ViewQuery;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import javax.jcr.Session;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.commons.collections.Predicate;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.request.RequestDispatcherOptions;
import org.apache.sling.api.request.RequestPathInfo;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
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;

public abstract class ViewHandler
extends ContentFinderListInfoProviderHelper {
    private static final long serialVersionUID = 5964360462202342062L;
    private static final Logger LOG = LoggerFactory.getLogger(ViewHandler.class);
    public static final String QUERY = "query";
    public static final String TYPE = "type";
    public static final String LIMIT = "limit";
    public static final int DEFAULT_LIMIT = 20;
    public static final String ITEM_RESOURCE_TYPE = "itemResourceType";

    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response, Predicate predicate) throws ServletException, IOException {
        JSONArray hits = new JSONArray();
        JSONObject result = new JSONObject();
        RequestPathInfo pathInfo = request.getRequestPathInfo();
        Collection<Hit> results = this.executeSearch(request);
        if ("json".equals(pathInfo.getExtension())) {
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            try {
                hits = this.getHitsArray(results, request, null);
                result.put("hits", (Object)hits);
            }
            catch (Exception e) {
                throw new ServletException((Throwable)e);
            }
            finally {
                response.getWriter().write(result.toString());
            }
        }
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        try {
            response.getWriter().write(this.generateHtmlOutput(results, request, response));
        }
        catch (Exception e) {
            throw new ServletException((Throwable)e);
        }
    }

    protected Collection<Hit> executeSearch(SlingHttpServletRequest request) throws ServletException {
        Collection<Hit> results = null;
        String queryString = request.getParameter("query");
        if (queryString == null || queryString.length() == 0) {
            queryString = "";
        }
        queryString = queryString.trim();
        try {
            ResourceResolver resolver = request.getResourceResolver();
            Session session = (Session)resolver.adaptTo(Session.class);
            ViewQuery q = this.createQuery(request, session, queryString);
            results = q.execute();
        }
        catch (Exception e) {
            throw new ServletException((Throwable)e);
        }
        return results;
    }

    protected abstract ViewQuery createQuery(SlingHttpServletRequest var1, Session var2, String var3) throws Exception;

    protected JSONArray getHitsArray(Iterable<Hit> hits, SlingHttpServletRequest request, Resource resource) throws JSONException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONArray hitsArray = new JSONArray();
        for (Hit hit : hits) {
            JSONObject jsonHit = new JSONObject();
            Iterator<String> keys = hit.getKeys();
            while (keys.hasNext()) {
                String key = keys.next();
                Object val = hit.get(key);
                if (val instanceof Calendar) {
                    Date date = ((Calendar)val).getTime();
                    jsonHit.put(key, (Object)format.format(date));
                    continue;
                }
                jsonHit.put(key, val);
            }
            String path = null;
            try {
                ResourceResolver rr;
                boolean shouldResetResource = false;
                if (resource == null && (path = (String)jsonHit.get("path")) != null && (resource = (rr = request.getResourceResolver()).getResource(path)) != null) {
                    shouldResetResource = true;
                }
                if (resource != null) {
                    this.pingCallbacksWithItem(request, jsonHit, resource);
                    if (shouldResetResource) {
                        resource = null;
                    }
                }
            }
            catch (JSONException e) {
                LOG.warn("Could not find a path element in the JSON object; not calling ListInfoProviders");
            }
            hitsArray.put((Object)jsonHit);
        }
        return hitsArray;
    }

    protected String generateHtmlOutput(Collection<Hit> hits, SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
        if (request.getParameter("itemResourceType") == null) {
            return hits.toString();
        }
        StringResponseWrapper hitResponse = new StringResponseWrapper(response);
        RequestDispatcherOptions requestDispatcherOptions = new RequestDispatcherOptions(null);
        requestDispatcherOptions.setForceResourceType(request.getParameter("itemResourceType"));
        for (Hit hit : hits) {
            Resource resource;
            String path = (String)hit.get("path");
            if (path == null || (resource = request.getResourceResolver().getResource(path)) == null) continue;
            request.setAttribute(Resource.class.getCanonicalName(), (Object)resource);
            RequestDispatcher dispatcher = request.getRequestDispatcher(resource.getPath(), requestDispatcherOptions);
            dispatcher.include((ServletRequest)request, (ServletResponse)hitResponse);
            request.removeAttribute(Resource.class.getCanonicalName());
        }
        return hitResponse.getString();
    }

    protected StringBuilder getTagTitleGQLSearchExpression(String title, String tagPropertyPath, TagManager tagMgr, Locale locale) {
        StringBuilder titleQuery = new StringBuilder();
        Tag[] tags = tagMgr.findTagsByTitle(title, locale);
        boolean flag = false;
        for (Tag tag : tags) {
            if (flag) {
                titleQuery.append("OR ");
            } else {
                flag = true;
            }
            titleQuery.append(tag.getGQLSearchExpression(tagPropertyPath));
            titleQuery.append(" ");
        }
        return titleQuery;
    }

    protected static String preserveWildcards(String queryString) {
        if (queryString != null) {
            queryString = queryString.replace("*", "%");
        }
        return queryString;
    }

    protected static String revertWildcards(String queryString) {
        if (queryString != null) {
            queryString = queryString.replace("%", "*");
        }
        return queryString;
    }
}