cmssearch.java

来自「找了很久才找到到源代码」· Java 代码 · 共 740 行 · 第 1/2 页

JAVA
740
字号
/*
 * File   : $Source: /usr/local/cvs/opencms/src/org/opencms/search/CmsSearch.java,v $
 * Date   : $Date: 2007-08-13 16:29:59 $
 * Version: $Revision: 1.43 $
 *
 * This library is part of OpenCms -
 * the Open Source Content Management System
 *
 * Copyright (c) 2002 - 2007 Alkacon Software GmbH (http://www.alkacon.com)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * For further information about Alkacon Software GmbH, please see the
 * company website: http://www.alkacon.com
 *
 * For further information about OpenCms, please see the
 * project website: http://www.opencms.org
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package org.opencms.search;

import org.opencms.file.CmsObject;
import org.opencms.i18n.CmsEncoder;
import org.opencms.main.CmsException;
import org.opencms.main.CmsIllegalArgumentException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsStringUtil;

import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.logging.Log;
import org.apache.lucene.search.Sort;

/**
 * Helper class to access the search facility within a jsp.<p>
 * 
 * Typically, the following fields are available for searching:
 * <ul>
 * <li>title - the title of a resource</li>
 * <li>keywords - the keywords of a resource</li>
 * <li>description - the description of a resource</li>
 * <li>content - the aggregated content of a resource</li>
 * <li>created - the creation date of a resource</li>
 * <li>lastmodified - the date of the last modification of a resource</li>
 * <li>path - the path to display the resource</li>
 * <li>channel - the channel of a resource</li>
 * <li>contentdefinition - the name of the content definition class of a resource</li>
 * </ul>
 * 
 * @author Carsten Weinholz 
 * @author Thomas Weckert  
 * 
 * @version $Revision: 1.43 $ 
 * 
 * @since 6.0.0 
 */
public class CmsSearch {

    /** The log object for this class. */
    private static final Log LOG = CmsLog.getLog(CmsSearch.class);

    /** The result categories of a search. */
    protected Map m_categoriesFound;

    /** The cms object. */
    protected transient CmsObject m_cms;

    /** The latest exception. */
    protected Exception m_lastException;

    /** The URL which leads to the next result page. */
    protected String m_nextUrl;

    /** The number of pages for the result list. */
    protected int m_pageCount;

    /** The restriction for the search parameters, used for "search in seach result". */
    protected CmsSearchParameters m_parameterRestriction;

    /** The search parameters used for searching, build out of the given individual parameter values. */
    protected CmsSearchParameters m_parameters;

    /** The URL which leads to the previous result page. */
    protected String m_prevUrl;

    /** The current search result. */
    protected List m_result;

    /** The search parameter String. */
    protected String m_searchParameters;

    /** The total number of search results matching the query. */
    protected int m_searchResultCount;

    /**
     * Default constructor, used to instanciate the search facility as a bean.<p>
     */
    public CmsSearch() {

        super();

        m_parameters = new CmsSearchParameters();
        m_parameters.setSearchRoots("");
        m_parameters.setSearchPage(1);
        m_searchResultCount = 0;
        m_parameters.setSort(CmsSearchParameters.SORT_DEFAULT);
        m_parameters.setFields(Arrays.asList(CmsSearchIndex.DOC_META_FIELDS));
    }

    /**
     * Returns <code>true</code> if a category overview should be shown as part of the result.<p>
     *
     * <b>Please note:</b> The calculation of the category count slows down the search time by an order
     * of magnitude. Make sure that you only use this feature if it's really required! 
     * Be especially careful if your search result list can become large (> 1000 documents), since in this case
     * overall system performance will certainly be impacted considerably when calculating the categories.<p> 
     *
     * @return <code>true</code> if a category overview should be shown as part of the result
     */
    public boolean getCalculateCategories() {

        return m_parameters.getCalculateCategories();
    }

    /**
     * Returns the search categories.<p>
     *
     * @return the search categories
     */
    public String[] getCategories() {

        List l = m_parameters.getCategories();
        return (String[])l.toArray(new String[l.size()]);
    }

    /**
     * Returns the maximum number of pages which should be shown.<p> 
     * 
     * @return the maximum number of pages which should be shown
     */
    public int getDisplayPages() {

        return m_parameters.getDisplayPages();
    }

    /**
     * Gets the current fields list.<p>
     * 
     * @return the fields to search
     */
    public String getFields() {

        if (m_parameters.getFields() == null) {
            return "";
        }
        StringBuffer result = new StringBuffer();
        Iterator it = m_parameters.getFields().iterator();
        while (it.hasNext()) {
            result.append(it.next());
            result.append(" ");
        }
        return result.toString();
    }

    /**
     * Gets the name of the current search index.<p>
     * 
     * @return the name of the index
     */
    public String getIndex() {

        return m_parameters.getSearchIndex().getName();
    }

    /**
     * Gets the last exception after a search operation.<p>
     * 
     * @return the exception occured in a search operation or null
     */
    public Exception getLastException() {

        return m_lastException;
    }

    /**
     * Gets the number of matches displayed on each page.<p>
     * 
     * @return matches per result page
     */
    public int getMatchesPerPage() {

        return m_parameters.getMatchesPerPage();
    }

    /**
     * Gets the URL for the link to the next result page.<p>
     * 
     * @return the URL to the next result page
     */
    public String getNextUrl() {

        return m_nextUrl;
    }

    /**
     * Creates a sorted map of URLs to link to other search result pages.<p>
     * 
     * The key values are Integers representing the page number, the entry 
     * holds the corresponding link.<p>
     *  
     * @return a map with String URLs
     */
    public Map getPageLinks() {

        Map links = new TreeMap();
        if (m_pageCount <= 1) {
            return links;
        }
        int startIndex, endIndex;
        String link = m_cms.getRequestContext().getUri() + getSearchParameters() + "&searchPage=";
        if (getDisplayPages() < 1) {
            // number of displayed pages not limited, build a map with all available page links 
            startIndex = 1;
            endIndex = m_pageCount;
        } else {
            // limited number of displayed pages, calculate page range
            int currentPage = getSearchPage();
            int countBeforeCurrent = getDisplayPages() / 2;
            int countAfterCurrent;
            if ((currentPage - countBeforeCurrent) < 1) {
                // set count before to number of available pages 
                countBeforeCurrent = currentPage - 1;
            }
            // set count after to number of remaining pages (- 1 for current page) 
            countAfterCurrent = getDisplayPages() - countBeforeCurrent - 1;
            // calculate start and end index
            startIndex = currentPage - countBeforeCurrent;
            endIndex = currentPage + countAfterCurrent;
            // check end index
            if (endIndex > m_pageCount) {
                int delta = endIndex - m_pageCount;
                // decrease start index with delta to get the right number of displayed pages
                startIndex -= delta;
                // check start index to avoid values < 1
                if (startIndex < 1) {
                    startIndex = 1;
                }
                endIndex = m_pageCount;
            }
        }

        // build the sorted tree map of page links
        for (int i = startIndex; i <= endIndex; i++) {
            links.put(new Integer(i), (link + i));
        }
        return links;
    }

    /**
     * Returns the search parameters used for searching, build out of the given individual parameter values.<p>
     *
     * @return the search parameters used for searching, build out of the given individual parameter values
     */
    public CmsSearchParameters getParameters() {

        if (m_parameterRestriction != null) {
            m_parameters = m_parameters.restrict(m_parameterRestriction);
        }
        return m_parameters;

    }

    /**
     * Gets the URL for the link to the previous result page.<p>
     * 
     * @return the URL to the previous result page
     */
    public String getPreviousUrl() {

        return m_prevUrl;
    }

    /**
     * Gets the current search query.<p>
     * 
     * @return the current query string or null if no query was set before
     */
    public String getQuery() {

        return m_parameters.getQuery();
    }

    /**
     * Gets the minimum search query length.<p>
     * 
     * @return the minimum search query length
     */
    public int getQueryLength() {

        return m_parameters.getQueryLength();
    }

    /**
     * Gets the current result page.<p>
     * 
     * @return the current result page
     */
    public int getSearchPage() {

        return m_parameters.getSearchPage();
    }

    /**
     * Creates a String with the necessary search parameters for page links.<p>
     * 
     * @return String with search parameters
     * 
     * @deprecated use {@link CmsSearchParameters#toQueryString()} instead
     * 
     * @see #getParameters()
     */
    public String getSearchParameters() {

        return m_parameters.toQueryString();
    }

    /**
     * Returns the search result for the current query, as a list of <code>{@link CmsSearchResult}</code> objects.<p>
     * 
     * @return the search result (may be empty) or null if no index or query was set before
     */
    public List getSearchResult() {

        if ((m_cms != null)
            && (m_result == null)
            && (m_parameters.getIndex() != null)
            && CmsStringUtil.isNotEmpty(m_parameters.getQuery())) {

            if ((getQueryLength() > 0) && (m_parameters.getQuery().trim().length() < getQueryLength())) {

                m_lastException = new CmsSearchException(Messages.get().container(
                    Messages.ERR_QUERY_TOO_SHORT_1,
                    new Integer(getQueryLength())));

                return m_result;
            }

            try {

                CmsSearchResultList result = m_parameters.getSearchIndex().search(m_cms, getParameters());

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?