alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/*
 * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/search/company/CompanySearchQuery.java,v 1.4 2005/01/28 08:11:03 minhnn Exp $
 * $Author: minhnn $
 * $Revision: 1.4 $
 * $Date: 2005/01/28 08:11:03 $
 *
 * ====================================================================
 *
 * Copyright (C) 2002-2005 by MyVietnam.net
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * All copyright notices regarding mvnForum MUST remain intact
 * in the scripts and in the outputted HTML.
 * The "powered by" text/logo with a link back to
 * http://www.mvnForum.com and http://www.MyVietnam.net in the
 * footer of the pages MUST remain visible when the pages
 * are viewed on the internet or intranet.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Support can be obtained from support forums at:
 * http://www.mvnForum.com/mvnforum/index
 *
 * Correspondence and Marketing Questions can be sent to:
 * info@MyVietnam.net
 *
 * @author: Minh Nguyen  minhnn@MyVietnam.net
 * @author: Dejan Krsmanovic dejan_krsmanovic@yahoo.com
 */
package com.mvnforum.search.company;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;

import com.mvnforum.MVNForumConfig;
import com.mvnforum.db.CompanyBean;
import com.mvnforum.db.DAOFactory;
import net.myvietnam.mvncore.exception.DatabaseException;
import net.myvietnam.mvncore.exception.ObjectNotFoundException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.DateField;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.*;

/**
 * This class is used for specifying query that should be searched for. Query
 * can contain keywords and further it can be filtered by specifying member
 * name of the company, address as well as date interval for searching.
 *
 * searchString contains one or more keywords. Each keyword can use wildcards.
 * ? for single character and * for multiple characters.
 * For specifying boolean operators AND and OR operators can be used.....
 *
 * For all available options consult Lucene documentation http://jakarta.apache.org/lucene
 *
 * @author Dejan Krsmanovic dejan_krsmanovic@yahoo.com
 */
public class CompanySearchQuery
{
    public static final int SEARCH_ANY_DATE = 0;

    public static final int SEARCH_NEWER    = 1;
    public static final int SEARCH_OLDER    = 2;

    private static Log log = LogFactory.getLog(CompanySearchQuery.class);

    private int companyID = -1;
    private String companyNameKey = null;
    private String companyAddressKey = null;
    private Timestamp companyDateKey = null;
    private Timestamp fromCompanyDateKey = null;
    private Timestamp toCompanyDateKey = null;

    private String searchCompanyIndexDir = null;
    private int hitCount = 0;
    private Collection searchResult = null;

    public CompanySearchQuery() {
        searchCompanyIndexDir = MVNForumConfig.getSearchCompanyIndexDir();
    }

    /**
     * Set name of the author that should be searched for
     * @param companyId
     */
    public void setCompanyId(int companyId) {
        this.companyID = companyId;
    }

    /**
     * Set string that should be searched for.
     * @param companyNameKey
     */
    public void setCompanyAddressKey(String companyAddressKey) {
        this.companyAddressKey = companyAddressKey;
    }

    /**
     * Set string that should be searched for.
     * @param companyNameKey
     */
    public void setCompanyNameKey(String companyNameKey) {
        this.companyNameKey = companyNameKey;
    }

    public void setCompanyDateKey(Timestamp companyDateKey) {
        this.companyDateKey = companyDateKey;
    }

    public void setFromCompanyDateKey(Timestamp fromCompanyDateKey) {
        this.fromCompanyDateKey = fromCompanyDateKey;
    }

    public void setToCompanyDateKey(Timestamp toCompanyDateKey) {
        this.toCompanyDateKey = toCompanyDateKey;
    }

    protected IndexSearcher getSearcher() throws IOException {
        try {
            IndexSearcher searcher = new IndexSearcher(searchCompanyIndexDir);
            return searcher;
        } catch (IOException ex) {
            // we throw new IOException because the original exception
            // contain sensitive directory information
            log.error("Cannot access the lucene search index for query. Please check if you have configed mvnForumHome properly. You can also go to Admin Zone to rebuild the Lucene index files.", ex);
            throw new IOException("Cannot access the lucene search index. Please report this error to web site Administrator (check mvnForumHome or rebuild Lucene index).");
        }
    }

    public void searchDocuments(int offset, int rowsToReturn)
        throws IOException, DatabaseException, ObjectNotFoundException {
        //Build the query
        //Analyzer analyzer = CompanyIndexer.getAnalyzer();
        BooleanQuery query = new BooleanQuery();//query.
        try {
            Query companyNameQuery = getCompanyNameQuery();
            if (companyNameQuery != null) {
                query.add(companyNameQuery, true, false);
                log.debug("companyNameQuery = " + companyNameQuery);
            }
            Query companyAddressQuery = getCompanyAddressQuery();
            if (companyAddressQuery != null) {
                query.add(companyAddressQuery, true, false);
                log.debug("companyAddressQuery = " + companyAddressQuery);
            }

            /*if (companyDateQuery != null) {
                query.add(companyDateQuery, true, false);
                log.debug("companyDateQuery = " + companyDateQuery);
            }*/
        } catch (ParseException pe) {
            log.error("Cannot parse the search query", pe);
        }
        log.debug("[OK ] booleanQuery = " + query);

        DateFilter dateFilter = null;
        if (fromCompanyDateKey != null && toCompanyDateKey != null) {
            dateFilter = new DateFilter(CompanyIndexer.FIELD_CREATION_DATE, fromCompanyDateKey, toCompanyDateKey );
        } else if (fromCompanyDateKey != null) {
            dateFilter = DateFilter.After(CompanyIndexer.FIELD_CREATION_DATE, fromCompanyDateKey);
        } else if (toCompanyDateKey != null) {
            dateFilter = DateFilter.Before(CompanyIndexer.FIELD_CREATION_DATE, toCompanyDateKey );
        }

        //Now search the documents
        IndexSearcher searcher = null;
        try {
            searcher = getSearcher();

            //If dateFilter set then use it
            Hits companyHits = null;
            //dateFilter = null;
            if (dateFilter != null) {
                companyHits = searcher.search(query, dateFilter);
            } else {
                companyHits = searcher.search(query);
            }
            hitCount = companyHits.length();
            log.debug("[ HIT COUNT ]"  + hitCount);
            searchResult = getCompanies(companyHits, offset, rowsToReturn);
        } catch (IOException ex) {
            throw ex;
        } finally {
            try {
                if (searcher != null) {
                    searcher.close();
                }
            } catch (Exception ex) {}
        }
    }

    public int getHitCount() {
        return hitCount;
    }

    public Collection getCompanyResult() {
        return searchResult;
    }

    private Collection getCompanies(Hits companyHits, int offset, int rowsToReturn)
        throws IOException, ObjectNotFoundException, DatabaseException {

        if (offset < 0) throw new IllegalArgumentException("The offset < 0 is not allowed.");
        if (rowsToReturn <= 0) throw new IllegalArgumentException("The rowsToReturn <= 0 is not allowed.");

        //int hitCount = getHitCount();
        ArrayList retValue = new ArrayList(hitCount);

        for (int i = offset; (i < offset + rowsToReturn) && (i < hitCount); i++) {
            Document companyDocument = companyHits.doc(i);
            int currentCompanyID = Integer.parseInt(companyDocument.get(CompanyIndexer.FIELD_COMPANY_ID));
            CompanyBean companyBean = DAOFactory.getCompanyDAO().getCompany(currentCompanyID);
            retValue.add(companyBean);
        }
        return retValue;
    }

    private Query getCompanyNameQuery() throws ParseException {
        if (companyNameKey == null) {
            return null;
        }
        Analyzer analyzer = CompanyIndexer.getAnalyzer();
        Query companyNameQuery = QueryParser.parse(companyNameKey,
                                                   CompanyIndexer.FIELD_COMPANY_NAME,
                                                   analyzer);
        return companyNameQuery;
    }

    private Query getCompanyAddressQuery() throws ParseException {
        if (companyAddressKey == null || companyAddressKey.equals("")) {
            return null;
        }
        Analyzer analyzer = CompanyIndexer.getAnalyzer();
        Query companyAddressQuery = QueryParser.parse(companyAddressKey,
                                                   CompanyIndexer.FIELD_COMPANY_ADDRESS,
                                                   analyzer);
        return companyAddressQuery;
    }
    /*
    private Query getCompanyDateQuery() throws ParseException {
        if (companyDateKey == null || companyDateKey.equals("") || companyDateKey.equals("dd/MM/yyyy")) {
            return null;
        }
        Analyzer analyzer = CompanyIndexer.getAnalyzer();
        Query companyDateQuery = QueryParser.parse(DateField.dateToString(companyDateKey),
                                                   CompanyIndexer.FIELD_CREATION_DATE,
                                                   analyzer);
        return companyDateQuery;
    }
    */
}
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.