OmniSearchServiceImpl.java 21.8 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.i18n.I18n
 *  com.day.cq.search.result.SearchResult
 *  javax.jcr.RepositoryException
 *  javax.jcr.Value
 *  javax.jcr.query.Query
 *  javax.jcr.query.QueryResult
 *  javax.jcr.query.Row
 *  javax.jcr.query.RowIterator
 *  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.ReferenceCardinality
 *  org.apache.felix.scr.annotations.ReferencePolicy
 *  org.apache.felix.scr.annotations.References
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ValueMap
 *  org.apache.sling.commons.osgi.PropertiesUtil
 *  org.osgi.framework.BundleContext
 *  org.osgi.framework.InvalidSyntaxException
 *  org.osgi.framework.ServiceReference
 *  org.osgi.service.component.ComponentContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.granite.omnisearch.impl.core;

import com.adobe.granite.omnisearch.api.core.OmniSearchException;
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.adobe.granite.omnisearch.spi.core.SavedSearchHandler;
import com.day.cq.i18n.I18n;
import com.day.cq.search.result.SearchResult;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.jcr.RepositoryException;
import javax.jcr.Value;
import javax.jcr.query.Query;
import javax.jcr.query.QueryResult;
import javax.jcr.query.Row;
import javax.jcr.query.RowIterator;
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.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.scr.annotations.References;
import org.apache.felix.scr.annotations.Service;
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.commons.osgi.PropertiesUtil;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(metatype=1, immediate=1)
@Service(value={OmniSearchService.class})
@Properties(value={@Property(name="omnisearch.suggestion.requiretext.min", label="Min Text Length for Suggestions", description="min length of text that is require to show suggestions", intValue={3}), @Property(name="omnisearch.suggestion.spellcheck.require", label="Include spellcheck in suggestions", description="check if spellcheck suggestions are require in suggestions of omnisearch", boolValue={0})})
@References(value={@Reference(name="omniSearchHandlerRef", referenceInterface=OmniSearchHandler.class, cardinality=ReferenceCardinality.OPTIONAL_MULTIPLE, policy=ReferencePolicy.DYNAMIC), @Reference(name="savedSearchHandlerRef", referenceInterface=SavedSearchHandler.class, cardinality=ReferenceCardinality.OPTIONAL_MULTIPLE, policy=ReferencePolicy.DYNAMIC)})
public class OmniSearchServiceImpl
implements OmniSearchService {
    private static final Logger log = LoggerFactory.getLogger(OmniSearchServiceImpl.class);
    private static final String REP_SUGGEST = "rep:suggest()";
    private static final String REP_SPELLCHECK = "rep:spellcheck()";
    private static final Set<String> paramsToIgnore = new HashSet<String>();
    private static final Set<String> paramsToIgnoreBeforeSearch;
    private static ConcurrentHashMap<String, OmniSearchHandler> searchHandlers;
    private static ConcurrentHashMap<String, SavedSearchHandler> savedSearchHandlers;
    private BundleContext bundleContext;
    private int minLengthRequire;
    private boolean spellcheckRequire;

    @Override
    public Map<String, SearchResult> getSearchResults(ResourceResolver resolver, Map<String, ?> predicateParameters, long limit, long offset) {
        LinkedHashMap<String, SearchResult> result = new LinkedHashMap<String, SearchResult>();
        String location = null;
        location = this.getLocation(predicateParameters);
        ListIterator<OmniSearchHandler> handlers = this.getSuggestionHandlersList(location, resolver);
        while (handlers.hasNext()) {
            OmniSearchHandler omniSearchHandler = handlers.next();
            if (omniSearchHandler.getModuleConfig(resolver) == null) continue;
            HashMap modifiablePredicateParameters = new HashMap(predicateParameters);
            result.put(omniSearchHandler.getID(), omniSearchHandler.getResults(resolver, this.removeParamsToIgnore(modifiablePredicateParameters, paramsToIgnoreBeforeSearch), limit, offset));
        }
        return result;
    }

    @Override
    public Map<String, SuggestionResult> getSuggestions(ResourceResolver resolver, I18n i18n, String searchTerm, String location) {
        LinkedHashMap<String, SuggestionResult> result = new LinkedHashMap<String, SuggestionResult>();
        if (searchTerm == null || searchTerm.length() < this.minLengthRequire) {
            log.warn("Either No query term has been provided Or query term is too small. No suggestion require");
            return null;
        }
        log.debug("location is {}", (Object)location);
        ListIterator<OmniSearchHandler> listHandlers = this.getSuggestionHandlersList(location, resolver);
        try {
            while (listHandlers.hasNext()) {
                Resource moduleConfig;
                OmniSearchHandler omniSearchHandler = listHandlers.next();
                if (log.isDebugEnabled()) {
                    log.debug("using omnisearch handler {}", (Object)omniSearchHandler.getID());
                }
                if ((moduleConfig = omniSearchHandler.getModuleConfig(resolver)) == null) continue;
                ArrayList<String> suggestions = new ArrayList<String>();
                Query suggestionQuery = omniSearchHandler.getSuggestionQuery(resolver, searchTerm);
                if (suggestionQuery != null) {
                    RowIterator suggestionIterator = suggestionQuery.execute().getRows();
                    while (suggestionIterator.hasNext()) {
                        suggestions.add(suggestionIterator.nextRow().getValue("rep:suggest()").getString());
                    }
                }
                ArrayList<String> spellcheckSuggestions = null;
                if (this.spellcheckRequire) {
                    spellcheckSuggestions = new ArrayList<String>();
                    Query spellCheckQuery = omniSearchHandler.getSpellCheckQuery(resolver, searchTerm);
                    if (spellCheckQuery != null) {
                        RowIterator spellcheckIterator = spellCheckQuery.execute().getRows();
                        while (spellcheckIterator.hasNext()) {
                            spellcheckSuggestions.add(spellcheckIterator.nextRow().getValue("rep:spellcheck()").getString());
                        }
                    }
                }
                if (location == null) {
                    List<PredicateSuggestion> locationPredicateSuggestions = this.getLocationSuggestions(moduleConfig, i18n, searchTerm, omniSearchHandler.getID());
                    result.put(omniSearchHandler.getID(), new SuggestionResult(suggestions, spellcheckSuggestions, locationPredicateSuggestions));
                    continue;
                }
                List<PredicateSuggestion> predicateSuggestions = null;
                predicateSuggestions = omniSearchHandler.getPredicateSuggestions(resolver, i18n, searchTerm);
                result.put(omniSearchHandler.getID(), new SuggestionResult(suggestions, spellcheckSuggestions, predicateSuggestions));
            }
        }
        catch (RepositoryException re) {
            log.error("Error while handling Suggestion Query", (Throwable)re);
        }
        return result;
    }

    @Override
    public Resource getModuleConfiguration(ResourceResolver resolver, String location) {
        ListIterator<OmniSearchHandler> listHandlers;
        if (location != null && (listHandlers = this.getSuggestionHandlersList(location, resolver)).hasNext()) {
            OmniSearchHandler omniSearchHandler = listHandlers.next();
            return omniSearchHandler.getModuleConfig(resolver);
        }
        log.error("location can not be null to obtain module config resource");
        return null;
    }

    @Override
    public Map<String, Resource> getModules(ResourceResolver resolver) {
        ListIterator<OmniSearchHandler> listHandlers = this.getSuggestionHandlersList(null, resolver);
        HashMap<String, Resource> resourceConfigHashMap = new HashMap<String, Resource>();
        while (listHandlers.hasNext()) {
            OmniSearchHandler omniSearchHandler = listHandlers.next();
            Resource moduleConfig = omniSearchHandler.getModuleConfig(resolver);
            if (moduleConfig == null) continue;
            resourceConfigHashMap.put(omniSearchHandler.getID(), moduleConfig);
        }
        return resourceConfigHashMap;
    }

    @Override
    public Iterator<Resource> getSavedSearches(ResourceResolver resolver, String location, long limit, long offset) throws OmniSearchException {
        SavedSearchHandler savedSearchHandler = this.getSavedSearchHandlers(location);
        if (savedSearchHandler == null) {
            return Collections.emptyList().iterator();
        }
        return savedSearchHandler.getSavedSearches(resolver, limit, offset);
    }

    @Override
    public Map<String, String> getSavedSearchParameters(ResourceResolver resolver, String location, String path) throws OmniSearchException {
        SavedSearchHandler savedSearchHandler = this.getSavedSearchHandlers(location);
        if (savedSearchHandler == null) {
            return Collections.emptyMap();
        }
        return savedSearchHandler.getSavedSearchParameters(resolver, path);
    }

    @Override
    public Resource createOrUpdateSavedSearch(ResourceResolver resolver, Map<String, Object> requestParameters) throws OmniSearchException {
        String location = this.getLocation(requestParameters);
        SavedSearchHandler savedSearchHandler = this.getSavedSearchHandlers(location);
        if (savedSearchHandler == null) {
            return null;
        }
        return savedSearchHandler.createOrUpdateSavedSearch(resolver, this.getModifiablePredicateParameters(requestParameters));
    }

    @Override
    public boolean deleteSavedSearch(ResourceResolver resolver, String location, String path) throws OmniSearchException {
        SavedSearchHandler savedSearchHandler = this.getSavedSearchHandlers(location);
        if (savedSearchHandler == null) {
            return false;
        }
        return savedSearchHandler.deleteSavedSearch(resolver, path);
    }

    private SavedSearchHandler getSavedSearchHandlers(String location) {
        if (location != null) {
            if (savedSearchHandlers.containsKey(location)) {
                return savedSearchHandlers.get(location);
            }
            log.debug("No SavedSearchHandler exists for location {}", (Object)location);
        }
        return null;
    }

    private ListIterator<OmniSearchHandler> getSuggestionHandlersList(String location, ResourceResolver resolver) {
        ArrayList<OmniSearchHandler> refs = new ArrayList<OmniSearchHandler>();
        log.debug("get handler for {}", (Object)location);
        if (location != null) {
            if (searchHandlers.containsKey(location)) {
                refs.add(searchHandlers.get(location));
            } else {
                log.error("No SuggestionHandler exist for location {}", (Object)location);
            }
        } else {
            for (OmniSearchHandler ref : searchHandlers.values()) {
                refs.add(ref);
            }
            if (resolver != null) {
                Collections.sort(refs, new OmniSearchHandlerComparator(resolver));
            }
        }
        return refs.listIterator();
    }

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

    private Map<String, String> getModifiablePredicateParameters(Map<String, ?> predicateMap) {
        HashMap<String, String> modifiableMap = new HashMap<String, String>();
        for (String key : predicateMap.keySet()) {
            String value;
            Object valueObj = predicateMap.get(key);
            if (valueObj instanceof String) {
                value = (String)valueObj;
                modifiableMap.put(key, value);
                continue;
            }
            if (!(valueObj instanceof String[])) continue;
            String[] valueArray = (String[])valueObj;
            value = valueArray.length == 0 ? null : valueArray[0];
            modifiableMap.put(key, value);
        }
        return this.removeParamsToIgnore(modifiableMap, paramsToIgnore);
    }

    private <ValueT> Map<String, ValueT> removeParamsToIgnore(Map<String, ValueT> predicateMap, Set<String> params) {
        Iterator<String> ignoreParamsIterator = params.iterator();
        while (ignoreParamsIterator.hasNext()) {
            predicateMap.remove(ignoreParamsIterator.next());
        }
        return predicateMap;
    }

    protected void bindOmniSearchHandlerRef(ServiceReference ref) {
        if (this.bundleContext != null) {
            OmniSearchHandler omniSearchHandler = (OmniSearchHandler)this.bundleContext.getService(ref);
            String handlerId = omniSearchHandler.getID();
            log.debug("Adding SuggestionHandler component with ID {}", (Object)omniSearchHandler.getID());
            searchHandlers.put(handlerId, omniSearchHandler);
        }
    }

    protected void unbindOmniSearchHandlerRef(ServiceReference ref) {
        if (this.bundleContext != null) {
            OmniSearchHandler omniSearchHandler = (OmniSearchHandler)this.bundleContext.getService(ref);
            String handlerId = omniSearchHandler.getID();
            log.debug("Removing SuggestionHandler component with ID {}", (Object)omniSearchHandler.getID());
            searchHandlers.remove(handlerId);
        }
    }

    protected void bindSavedSearchHandlerRef(ServiceReference ref) {
        if (this.bundleContext != null) {
            SavedSearchHandler savedSearchHandler = (SavedSearchHandler)this.bundleContext.getService(ref);
            String handlerId = savedSearchHandler.getID();
            log.debug("Adding SavedSearchHandler component with ID {}", (Object)savedSearchHandler.getID());
            savedSearchHandlers.put(handlerId, savedSearchHandler);
        }
    }

    protected void unbindSavedSearchHandlerRef(ServiceReference ref) {
        if (this.bundleContext != null) {
            SavedSearchHandler savedSearchHandler = (SavedSearchHandler)this.bundleContext.getService(ref);
            String handlerId = savedSearchHandler.getID();
            log.debug("Removing SavedSearchHandler component with ID {}", (Object)savedSearchHandler.getID());
            savedSearchHandlers.remove(handlerId);
        }
    }

    protected void activate(ComponentContext context) {
        this.bundleContext = context.getBundleContext();
        this.minLengthRequire = PropertiesUtil.toInteger(context.getProperties().get("omnisearch.suggestion.requiretext.min"), (int)3);
        this.spellcheckRequire = PropertiesUtil.toBoolean(context.getProperties().get("omnisearch.suggestion.spellcheck.require"), (boolean)false);
        try {
            String handlerId;
            ServiceReference[] refs = this.bundleContext.getAllServiceReferences(OmniSearchHandler.class.getName(), null);
            if (refs != null) {
                for (ServiceReference ref : refs) {
                    OmniSearchHandler omniSearchHandler = (OmniSearchHandler)this.bundleContext.getService(ref);
                    handlerId = omniSearchHandler.getID();
                    log.debug("Adding SuggestionHandler component with ID " + omniSearchHandler.getID());
                    searchHandlers.put(handlerId, omniSearchHandler);
                }
            }
            if ((refs = this.bundleContext.getAllServiceReferences(SavedSearchHandler.class.getName(), null)) != null) {
                for (ServiceReference ref : refs) {
                    SavedSearchHandler savedSearchHandler = (SavedSearchHandler)this.bundleContext.getService(ref);
                    handlerId = savedSearchHandler.getID();
                    log.debug("Adding SavedSearchHandler component with ID {}", (Object)savedSearchHandler.getID());
                    savedSearchHandlers.put(handlerId, savedSearchHandler);
                }
            }
        }
        catch (InvalidSyntaxException e) {
            log.error("Error While binding the SuggestionHandler Services", (Throwable)e);
        }
    }

    protected void deactivate(ComponentContext context) {
        searchHandlers.clear();
        savedSearchHandlers.clear();
    }

    private List<PredicateSuggestion> getLocationSuggestions(Resource configRes, I18n i18n, String searchTerm, String location) {
        ArrayList<PredicateSuggestion> locSuggestions = new ArrayList<PredicateSuggestion>();
        if (configRes != null) {
            ValueMap vm = configRes.getValueMap();
            String moduleName = (String)vm.get("jcr:title", String.class);
            if (moduleName != null) {
                searchTerm = searchTerm.replaceFirst("(?i)^location[: ]", "").trim();
                if (i18n.getVar(moduleName).toLowerCase().contains(searchTerm.toLowerCase()) || i18n.getVar(StringUtils.capitalize((String)"location")).toLowerCase().startsWith(searchTerm.toLowerCase())) {
                    HashMap<String, String> queryParameterMap = new HashMap<String, String>();
                    queryParameterMap.put("location", location);
                    PredicateSuggestion locationPredicateSuggestion = new PredicateSuggestion("location", moduleName);
                    locationPredicateSuggestion.setQueryParameters(queryParameterMap);
                    locSuggestions.add(locationPredicateSuggestion);
                }
            } else {
                log.warn("module name should not be null {} ", (Object)configRes.getName());
            }
        }
        return locSuggestions;
    }

    static {
        paramsToIgnore.add("location");
        paramsToIgnore.add(":cq_csrf_token");
        paramsToIgnoreBeforeSearch = new HashSet<String>(paramsToIgnore);
        paramsToIgnoreBeforeSearch.add("jcr:content/metadata/cq:tags@TypeHint");
        paramsToIgnoreBeforeSearch.add("jcr:content/metadata/cq:tags@Delete");
        paramsToIgnoreBeforeSearch.add("jcr:content/cq:tags@TypeHint");
        paramsToIgnoreBeforeSearch.add("jcr:content/cq:tags@Delete");
        paramsToIgnoreBeforeSearch.add("cq:tags@TypeHint");
        paramsToIgnoreBeforeSearch.add("cq:tags@Delete");
        paramsToIgnoreBeforeSearch.add("contentPath");
        paramsToIgnoreBeforeSearch.add("savedSearches");
        paramsToIgnoreBeforeSearch.add("savedSearches@Delete");
        paramsToIgnoreBeforeSearch.add("location.suggestion");
        searchHandlers = new ConcurrentHashMap();
        savedSearchHandlers = new ConcurrentHashMap();
    }

    private class OmniSearchHandlerComparator
    implements Comparator<OmniSearchHandler> {
        private final ResourceResolver resourceResolver;
        private final String LIST_ORDER = "listOrder";

        private OmniSearchHandlerComparator(ResourceResolver resolver) {
            this.LIST_ORDER = "listOrder";
            this.resourceResolver = resolver;
        }

        /*
         * WARNING - Removed try catching itself - possible behaviour change.
         */
        @Override
        public int compare(OmniSearchHandler handler1, OmniSearchHandler handler2) {
            int listOrder1 = Integer.MAX_VALUE;
            int listOrder2 = Integer.MAX_VALUE;
            try {
                Resource moduleConfig2;
                Resource moduleConfig1 = handler1.getModuleConfig(this.resourceResolver);
                if (moduleConfig1 != null) {
                    ValueMap vm1 = moduleConfig1.getValueMap();
                    listOrder1 = (Integer)vm1.get("listOrder", (Object)Integer.MAX_VALUE);
                }
                if ((moduleConfig2 = handler2.getModuleConfig(this.resourceResolver)) != null) {
                    ValueMap vm2 = moduleConfig2.getValueMap();
                    listOrder2 = (Integer)vm2.get("listOrder", (Object)Integer.MAX_VALUE);
                    return listOrder2;
                }
            }
            catch (Exception e) {
                log.error("Error while ordering OmniSearchHandlers", (Throwable)e);
            }
            finally {
                return listOrder1 - listOrder2;
            }
        }
    }

}