/*
 * $Header: /home/cvspublic/jakarta-slide/src/stores/org/apache/slide/index/SampleTxtContainsIndexer.java,v 1.3 2004/07/11 10:12:50 unico Exp $
 * $Revision: 1.3 $
 * $Date: 2004/07/11 10:12:50 $
 *
 * ====================================================================
 *
 * Copyright 1999-2004 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.apache.slide.index;
import java.io.CharArrayReader;
import java.io.IOException;
import java.util.Hashtable;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.IndexWriter;
import org.apache.slide.common.XAServiceBase;
import org.apache.slide.common.NamespaceAccessToken;
import org.apache.slide.common.ServiceAccessException;
import org.apache.slide.common.ServiceConnectionFailedException;
import org.apache.slide.common.ServiceDisconnectionFailedException;
import org.apache.slide.common.ServiceInitializationFailedException;
import org.apache.slide.common.ServiceParameterErrorException;
import org.apache.slide.common.ServiceParameterMissingException;
import org.apache.slide.common.ServiceResetFailedException;
import org.apache.slide.common.Uri;
import org.apache.slide.content.NodeRevisionContent;
import org.apache.slide.content.NodeRevisionDescriptor;
import org.apache.slide.content.NodeRevisionNumber;
import org.apache.slide.search.IndexException;
import org.apache.slide.search.basic.IBasicExpressionFactory;
import org.apache.slide.store.IndexStore;


/**
 * Take this as a starting point for your own Indexer implementation.
 *
 * @version $Revision: 1.3 $
 */
public class SampleTxtContainsIndexer extends XAServiceBase implements IndexStore
{
    private static final String INDEX_PATH = "indexpath";
    
    private String indexpath;
    
    /**
     * Create Index, if not yet done.
     *
     * @param    token               a  NamespaceAccessToken
     *
     * @throws   ServiceInitializationFailedException
     *
     */
    public void initialize(NamespaceAccessToken token)
        throws ServiceInitializationFailedException
    {
        indexpath = token.getNamespaceConfig().getParameter (INDEX_PATH);
        IndexWriter indexWriter = null;
        try
        {
            indexWriter = new IndexWriter(indexpath, new StandardAnalyzer(), false);
        }
        // will fail, if not yet exists
        catch (IOException e)
        {
            try
            {
                // create index
                indexWriter = new IndexWriter(indexpath, new StandardAnalyzer(), true);
            }
            catch (IOException ex)
            {
                throw new ServiceInitializationFailedException (this, ex);
            }
        }
        
        try
        {
            indexWriter.close();
        }
        catch (IOException e)
        {
            throw new ServiceInitializationFailedException (this, e);
        }
    }
    
    /**
     * Method getFactory
     *
     * @return   an IBasicExpressionFactory
     *
     */
    public IBasicExpressionFactory getBasicExpressionFactory()
    {
        return new BasicExpressionFactoryTxtContainsSample (indexpath);
    }
    
    private boolean started = false;
    
    
    /**
     * Index an object content.
     *
     * @param uri Uri
     * @exception IndexException Error accessing the Data Source
     */
    synchronized public void createIndex (Uri uri,
                                          NodeRevisionDescriptor revisionDescriptor,
                                          NodeRevisionContent revisionContent)
        throws IndexException
    {
        try
        {
            LuceneIndexer indexer = new LuceneIndexer (indexpath);
            indexer.index (uri.toString(),
                           new CharArrayReader (revisionContent.getContent()));
        }
        catch (Exception e)
        {
            throw new IndexException (e);
        }
        //index(revisionContent, uri);
    }
    
    /**
     * Method updateIndex
     *
     * @param    uri                 an Uri
     * @param    revisionDescriptor  a  NodeRevisionDescriptor
     * @param    revisionContent     a  NodeRevisionContent
     *
     * @throws   IndexException
     *
     */
    synchronized public void updateIndex(Uri uri,
                                         NodeRevisionDescriptor revisionDescriptor,
                                         NodeRevisionContent revisionContent)
        throws IndexException
    {
        try
        {
            LuceneIndexer indexer = new LuceneIndexer (indexpath);
            indexer.removeIndex (uri.toString());
            indexer.index (uri.toString(),
                           new CharArrayReader (revisionContent.getContent()));
        }
        catch (Exception e)
        {
            throw new IndexException (e);
        }
    }
        
    /**
     * Drop an object revision from the index.
     *
     * @param uri Uri
     * @exception ServiceAccessException Error accessing the Data Source
     */
    synchronized public void dropIndex(Uri uri, NodeRevisionNumber number)
        throws IndexException
    {
        try
        {
            LuceneIndexer indexer = new LuceneIndexer (indexpath);
            indexer.removeIndex (uri.toString());
        }
        catch (Exception e)
        {
            throw new IndexException (e);
        }
    }
        
    /**
     * Connects to the underlying data source (if any is needed).
     *
     * @exception ServiceConnectionFailedException Connection failed
     */
    public void connect() throws ServiceConnectionFailedException
    {
        System.out.println("SampleIndexer: connect");
        started = true;
    }
    
    /**
     * This function tells whether or not the service is connected.
     *
     * @return boolean true if we are connected
     * @exception ServiceAccessException Service access error
     */
    public boolean isConnected() throws ServiceAccessException
    {
        // System.out.println("isConnected");
        return started;
    }
    
    /**
     * Initializes the service with a set of parameters. Those could be :
     * <li>User name, login info
     * <li>Host name on which to connect
     * <li>Remote port
     * <li>JDBC driver whoich is to be used :-)
     * <li>Anything else ...
     *
     * @param parameters Hashtable containing the parameters' names
     * and associated values
     * @exception ServiceParameterErrorException Incorrect service parameter
     * @exception ServiceParameterMissingException Service parameter missing
     */
    public void setParameters (Hashtable parameters) throws ServiceParameterErrorException, ServiceParameterMissingException
    {
        indexpath = (String)parameters.get (INDEX_PATH);
        if (indexpath == null || indexpath.length() == 0)
            throw new ServiceParameterMissingException (this, INDEX_PATH);
    }
    
    /**
     * Disconnects from the underlying data source.
     *
     * @exception ServiceDisconnectionFailedException Disconnection failed
     */
    public void disconnect() throws ServiceDisconnectionFailedException
    {
        System.out.println("SampleIndexer: disconnect");
        started = false;
    }
    
    /**
     * Deletes service underlying data source, if possible (and meaningful).
     *
     * @exception ServiceResetFailedException Reset failed
     */
    public void reset() throws ServiceResetFailedException
    {
        System.out.println("SampleIndexer: reset");
    }
}

