001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.kernel.search;
016    
017    import com.liferay.portal.kernel.util.ArrayUtil;
018    
019    import java.util.List;
020    import java.util.Map;
021    
022    /**
023     * @author Michael C. Han
024     */
025    public class AlternateKeywordQueryHitsProcessor implements HitsProcessor {
026    
027            @Override
028            public boolean process(SearchContext searchContext, Hits hits)
029                    throws SearchException {
030    
031                    if (hits.getLength() > 0) {
032                            return true;
033                    }
034    
035                    Map<String, List<String>> spellCheckResults =
036                            hits.getSpellCheckResults();
037    
038                    if (spellCheckResults == null) {
039                            return true;
040                    }
041    
042                    String spellCheckedKeywords = hits.getCollatedSpellCheckResult();
043    
044                    searchContext.overrideKeywords(spellCheckedKeywords);
045    
046                    String[] querySuggestions = SearchEngineUtil.suggestKeywordQueries(
047                            searchContext, 5);
048    
049                    if (ArrayUtil.isNotEmpty(querySuggestions)) {
050                            searchContext.setKeywords(querySuggestions[0]);
051                    }
052    
053                    QueryConfig queryConfig = searchContext.getQueryConfig();
054    
055                    queryConfig.setHitsProcessingEnabled(false);
056    
057                    Indexer indexer = FacetedSearcher.getInstance();
058    
059                    Hits alternateResults = indexer.search(searchContext);
060    
061                    hits.copy(alternateResults);
062    
063                    return true;
064            }
065    
066    }