Search.java 19.5 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 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.search.Predicate
 *  com.day.cq.search.PredicateGroup
 *  com.day.cq.search.SimpleSearch
 *  com.day.cq.search.Trends
 *  com.day.cq.search.facets.Facet
 *  com.day.cq.search.result.Hit
 *  com.day.cq.search.result.ResultPage
 *  com.day.cq.search.result.SearchResult
 *  com.day.cq.wcm.api.components.Component
 *  com.day.cq.wcm.commons.WCMUtils
 *  javax.jcr.Node
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.Value
 *  javax.jcr.Workspace
 *  javax.jcr.query.Query
 *  javax.jcr.query.QueryManager
 *  javax.jcr.query.QueryResult
 *  javax.jcr.query.Row
 *  javax.jcr.query.RowIterator
 *  org.apache.commons.lang.StringUtils
 *  org.apache.jackrabbit.commons.query.GQL
 *  org.apache.jackrabbit.commons.query.GQL$ParserCallback
 *  org.apache.sling.api.SlingHttpServletRequest
 *  org.apache.sling.api.request.RequestParameter
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ValueMap
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.wcm.foundation;

import com.day.cq.search.Predicate;
import com.day.cq.search.PredicateGroup;
import com.day.cq.search.SimpleSearch;
import com.day.cq.search.Trends;
import com.day.cq.search.facets.Facet;
import com.day.cq.search.result.ResultPage;
import com.day.cq.search.result.SearchResult;
import com.day.cq.wcm.api.components.Component;
import com.day.cq.wcm.commons.WCMUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.Workspace;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import javax.jcr.query.Row;
import javax.jcr.query.RowIterator;
import org.apache.commons.lang.StringUtils;
import org.apache.jackrabbit.commons.query.GQL;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.RequestParameter;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class Search {
    private final Logger log = LoggerFactory.getLogger(Search.class);
    private static final String QUERY_PARAM_NAME = "q";
    private static final String START_PARAM_NAME = "start";
    private static final String LANGUAGE_FACET_PARAM_NAME = "language";
    private static final String CHARSET_PARAM_NAME = "_charset_";
    private static final String TAG_FACET_PARAM_NAME = "tag";
    private static final String MIME_TYPE_FACET_PARAM_NAME = "mimeType";
    private static final String FROM_FACET_PARAM_NAME = "from";
    private static final String TO_FACET_PARAM_NAME = "to";
    private static final String NODE_TYPE_PARAM_NAME = "nodeType";
    private static final String HTML_EXT = "html";
    private static final String SPELLCHECK_QUERY = "/jcr:root[rep:spellcheck('${query}')]/(rep:spellcheck())";
    private List<String> defaultNodeTypes = new ArrayList<String>(Arrays.asList("cq:Page", "dam:Asset"));
    private final SlingHttpServletRequest request;
    private final SimpleSearch search;
    private final Resource resource;
    private Result result;
    private List<Page> resultPages;
    private String query;
    private boolean tagPredicateSet;

    public Search(SlingHttpServletRequest request) {
        this.request = request;
        this.resource = request.getResource();
        this.search = (SimpleSearch)this.resource.adaptTo(SimpleSearch.class);
        String charset = "ISO-8859-1";
        if (request.getParameter("_charset_") != null) {
            charset = request.getParameter("_charset_");
        }
        if (request.getParameter("q") != null) {
            try {
                this.setQuery(new String(request.getParameter("q").getBytes(charset), "UTF-8"));
            }
            catch (UnsupportedEncodingException e) {
                // empty catch block
            }
        }
        if (request.getParameter("start") != null) {
            try {
                this.search.setStart(Long.parseLong(request.getParameter("start")));
            }
            catch (NumberFormatException e) {
                // empty catch block
            }
        }
        Predicate languagePredicate = new Predicate("languages", "language");
        languagePredicate.set("language", request.getParameter("language"));
        this.search.addPredicate(languagePredicate);
        Predicate tagPredicate = new Predicate("tags", "tagid");
        tagPredicate.set("property", "jcr:content/cq:tags");
        tagPredicate.set("tagid", request.getParameter("tag"));
        this.search.addPredicate(tagPredicate);
        this.tagPredicateSet = tagPredicate.get("tagid") != null;
        Predicate mimeTypePredicate = new Predicate("mimeTypes", "property");
        mimeTypePredicate.set("property", "jcr:content/jcr:mimeType");
        mimeTypePredicate.set("value", request.getParameter("mimeType"));
        this.search.addPredicate(mimeTypePredicate);
        Predicate lastModPredicate = new Predicate("lastModified", "daterange");
        lastModPredicate.set("property", "jcr:content/cq:lastModified");
        lastModPredicate.set("lowerBound", request.getParameter("from"));
        lastModPredicate.set("upperBound", request.getParameter("to"));
        this.search.addPredicate(lastModPredicate);
        Predicate orderByScore = new Predicate("orderByScore", "orderby");
        orderByScore.set("orderby", "@jcr:score");
        orderByScore.set("sort", "desc");
        this.search.addPredicate(orderByScore);
        this.addNodeTypesPredicate();
    }

    public Trends getTrends() {
        return this.search.getTrends();
    }

    public Result getResult() throws RepositoryException {
        if (this.result == null && (this.search.getQuery().length() > 0 || this.tagPredicateSet) && this.search.getResult() != null) {
            this.result = new Result(this.search.getResult());
        }
        return this.result;
    }

    public List<String> getRelatedQueries() throws RepositoryException {
        return this.search.getRelatedQueries();
    }

    public String getQuery() {
        return this.query != null ? this.query : "";
    }

    public void setQuery(String query) {
        this.query = query;
        if (query != null && query.length() > 2 && query.startsWith("\"") && query.endsWith("\"") && !query.substring(1, query.length() - 1).contains("\"")) {
            this.search.setQuery(query);
            return;
        }
        try {
            final StringBuilder sb = new StringBuilder();
            GQL.parse((String)query, (Session)((Session)this.request.getResourceResolver().adaptTo(Session.class)), (GQL.ParserCallback)new GQL.ParserCallback(){

                public void term(String property, String value, boolean optional) throws RepositoryException {
                    sb.append(" ");
                    if (optional) {
                        sb.append("OR ");
                    }
                    if (property.length() > 0) {
                        sb.append(property).append(":");
                    }
                    sb.append(value);
                }
            });
            this.search.setQuery(sb.toString().trim());
        }
        catch (RepositoryException e) {
            this.search.setQuery("");
        }
    }

    @Deprecated
    public String getExcerptPropertyNames() {
        return "";
    }

    @Deprecated
    public void setExcerptPropertyNames(String properties) {
    }

    public long getHitsPerPage() {
        return this.search.getHitsPerPage();
    }

    public void setHitsPerPage(long num) {
        this.search.setHitsPerPage(num);
    }

    public String getSearchIn() {
        return this.search.getSearchIn();
    }

    public void setSearchIn(String searchIn) {
        this.search.setSearchIn(searchIn);
    }

    public String getSearchProperties() {
        return this.search.getSearchProperties();
    }

    public void setSearchProperties(String properties) {
        this.search.setSearchProperties(properties);
    }

    private static String encodeURL(String url) {
        try {
            return URLEncoder.encode(url, "UTF-8");
        }
        catch (UnsupportedEncodingException e) {
            return url;
        }
    }

    private String getIconPath(String extension) {
        Component c = WCMUtils.getComponent((Resource)this.resource);
        if (c == null) {
            return null;
        }
        Resource icon = c.getLocalResource("resources/" + extension + ".gif");
        if (icon == null) {
            icon = c.getLocalResource("resources/default.gif");
        }
        return icon == null ? null : icon.getPath();
    }

    private void addNodeTypesPredicate() {
        RequestParameter[] nodeTypeParams = this.request.getRequestParameters("nodeType");
        if (nodeTypeParams != null && nodeTypeParams.length > 0) {
            ArrayList<String> nodeTypes = new ArrayList<String>();
            for (RequestParameter parameter : nodeTypeParams) {
                String type = parameter.getString();
                nodeTypes.add(type);
            }
            this.addNodeTypesPredicate(nodeTypes);
        } else {
            this.addNodeTypesPredicate(this.defaultNodeTypes);
        }
    }

    private void addNodeTypesPredicate(List<String> types) {
        PredicateGroup nodeTypesPredicate = new PredicateGroup("nodeTypes");
        for (String type : types) {
            if (!StringUtils.isNotEmpty((String)type)) continue;
            Predicate predicate = new Predicate("type", "type");
            predicate.set("type", type);
            nodeTypesPredicate.add(predicate);
        }
        nodeTypesPredicate.setAllRequired(false);
        this.search.addPredicate((Predicate)nodeTypesPredicate);
        this.log.info("Searching with the type(s): {}", (Object)Arrays.toString(types.toArray()));
    }

    public final class Page {
        private final ResultPage rp;

        private Page(ResultPage rp) {
            this.rp = rp;
        }

        public boolean isCurrentPage() {
            return this.rp.isCurrentPage();
        }

        public long getIndex() {
            return this.rp.getIndex();
        }

        public String getURL() {
            String to;
            String from;
            String mimeType;
            String tag;
            StringBuffer url = new StringBuffer();
            url.append(Search.this.request.getRequestURI());
            url.append("?").append("q");
            url.append("=").append(Search.encodeURL(Search.this.search.getQuery()));
            url.append("&").append("start");
            url.append("=").append(this.rp.getStart());
            String lang = Search.this.request.getParameter("language");
            if (lang != null) {
                url.append("&").append("language");
                url.append("=").append(lang);
            }
            if ((tag = Search.this.request.getParameter("tag")) != null) {
                url.append("&").append("tag");
                url.append("=").append(tag);
            }
            if ((mimeType = Search.this.request.getParameter("mimeType")) != null) {
                url.append("&").append("mimeType");
                url.append("=").append(mimeType);
            }
            if ((from = Search.this.request.getParameter("from")) != null) {
                url.append("&").append("from");
                url.append("=").append(from);
            }
            if ((to = Search.this.request.getParameter("to")) != null) {
                url.append("&").append("to");
                url.append("=").append(to);
            }
            return url.toString();
        }
    }

    public final class Hit {
        private final com.day.cq.search.result.Hit hit;

        private Hit(com.day.cq.search.result.Hit hit) {
            this.hit = hit;
        }

        public String getTitle() throws RepositoryException {
            String excerpt = (String)this.hit.getExcerpts().get("jcr:title");
            if (excerpt != null) {
                return excerpt;
            }
            return this.getPageOrAsset().getName();
        }

        public String getExcerpt() throws RepositoryException {
            return this.hit.getExcerpt();
        }

        public String getURL() throws RepositoryException {
            Node n = this.getPageOrAsset();
            String url = Search.this.request.getContextPath() + n.getPath();
            if (this.isPage(n)) {
                url = url + ".html";
            }
            return url;
        }

        public String getSimilarURL() throws RepositoryException {
            StringBuffer url = new StringBuffer();
            url.append(Search.this.request.getRequestURI());
            url.append("?").append("q");
            url.append("=").append(Search.encodeURL("related:"));
            url.append(Search.encodeURL(this.hit.getPath()));
            return url.toString();
        }

        public String getIcon() throws RepositoryException {
            String url = this.getURL();
            int idx = url.lastIndexOf(46);
            if (idx == -1) {
                return "";
            }
            String ext = url.substring(idx + 1);
            if (ext.equals("html")) {
                return "";
            }
            String path = Search.this.getIconPath(ext);
            if (path == null) {
                return "";
            }
            StringBuffer sb = new StringBuffer();
            sb.append("<img src='");
            sb.append(Search.this.request.getContextPath());
            sb.append(path).append("'/>");
            return sb.toString();
        }

        public String getExtension() throws RepositoryException {
            String url = this.getURL();
            int idx = url.lastIndexOf(46);
            return idx >= 0 ? url.substring(idx + 1) : "";
        }

        public Map getProperties() throws RepositoryException {
            return this.hit.getProperties();
        }

        private boolean isPageOrAsset(Node n) throws RepositoryException {
            return this.isPage(n) || n.isNodeType("dam:Asset");
        }

        private boolean isPage(Node n) throws RepositoryException {
            return n.isNodeType("cq:Page") || n.isNodeType("cq:PseudoPage");
        }

        private Node getPageOrAsset() throws RepositoryException {
            Node n = this.hit.getNode();
            while (!this.isPageOrAsset(n) && n.getName().length() > 0) {
                n = n.getParent();
            }
            return n;
        }
    }

    public final class Result {
        private final SearchResult result;
        private final List<Hit> hits;
        private String spellSuggestion;

        private Result(SearchResult result) {
            this.result = result;
            this.hits = new ArrayList<Hit>();
            for (com.day.cq.search.result.Hit h : result.getHits()) {
                this.hits.add(new Hit(h));
            }
        }

        public List<Page> getResultPages() throws RepositoryException {
            if (Search.this.resultPages == null) {
                Search.this.resultPages = new ArrayList();
                for (ResultPage rp : this.result.getResultPages()) {
                    Search.this.resultPages.add(new Page(rp));
                }
            }
            return Search.this.resultPages;
        }

        public Page getPreviousPage() throws RepositoryException {
            ResultPage previous = this.result.getPreviousPage();
            if (previous != null) {
                return new Page(previous);
            }
            return null;
        }

        public Page getNextPage() throws RepositoryException {
            ResultPage next = this.result.getNextPage();
            if (next != null) {
                return new Page(next);
            }
            return null;
        }

        public String getTrackerScript() {
            StringBuffer sb = new StringBuffer();
            String contextPath = Search.this.request.getContextPath();
            sb.append("<script type='text/javascript'>");
            if (!Search.this.search.getQuery().startsWith("related:")) {
                sb.append("$.post(");
                sb.append("'/bin/statistics/tracker/query',");
                sb.append("{q:'").append(Search.encodeURL(Search.this.search.getQuery())).append("',");
                sb.append("nr:'").append(this.getTotalMatches()).append("',");
                sb.append("et:'").append(this.getExecutionTimeMillis()).append("',");
                sb.append("ct:'").append(System.currentTimeMillis()).append("'});\n");
            }
            sb.append("function trackSelectedResult(obj, position, query) {\n");
            sb.append("  var regExp = /^((\\w+):\\/\\/\\/?)?((\\w+):?(\\w+)?@)?([^\\/\\?:]+):?(\\d+)?(\\/?[^\\?#;\\|]+)?([;\\|])?([^\\?#]+)?\\??([^#]+)?#?(\\w*)/;\n");
            sb.append("  var uri = regExp.exec(obj.href);\n");
            sb.append(" var path= uri[8].substring(" + contextPath.length() + ", uri[8].lastIndexOf('.'));\n");
            sb.append("$.post(");
            sb.append("'/bin/statistics/tracker/result',\n");
            sb.append("{\np:path").append(",\n");
            sb.append("po:position").append(",\n");
            sb.append("q:'").append(Search.encodeURL(Search.this.search.getQuery().toLowerCase())).append("',\n");
            sb.append("rand:Math.random()\n}\n);\n");
            sb.append("}");
            sb.append("</script>");
            return sb.toString();
        }

        public String getSpellcheck() {
            if (this.spellSuggestion == null) {
                try {
                    Value v;
                    Session session = (Session)Search.this.request.getResourceResolver().adaptTo(Session.class);
                    RowIterator rows = session.getWorkspace().getQueryManager().createQuery("/jcr:root[rep:spellcheck('${query}')]/(rep:spellcheck())".replaceAll("\\$\\{query\\}", Matcher.quoteReplacement(Search.this.getQuery())), "xpath").execute().getRows();
                    String suggestion = null;
                    if (rows.hasNext() && (v = rows.nextRow().getValue("rep:spellcheck()")) != null) {
                        suggestion = v.getString();
                    }
                    if (suggestion == null) {
                        return null;
                    }
                    Search.this.search.setQuery(suggestion);
                    this.spellSuggestion = Search.this.search.getResult().getTotalMatches() > 0 ? suggestion : "";
                }
                catch (RepositoryException e) {
                    this.spellSuggestion = "";
                }
            }
            if (this.spellSuggestion.length() == 0) {
                return null;
            }
            return this.spellSuggestion;
        }

        public long getStartIndex() {
            return this.result.getStartIndex();
        }

        public long getTotalMatches() {
            return this.result.getTotalMatches();
        }

        public String getExecutionTime() {
            return this.result.getExecutionTime();
        }

        public long getExecutionTimeMillis() {
            return this.result.getExecutionTimeMillis();
        }

        public Map<String, Facet> getFacets() throws RepositoryException {
            return this.result.getFacets();
        }

        public List<Hit> getHits() {
            return this.hits;
        }
    }

}