Package org.alastairmailer

Source Code of org.alastairmailer.FiletypeHandler

package org.alastairmailer;

import java.awt.Component;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;

import net.sf.jabref.plugin.PluginCore;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.java.plugin.Plugin;
import org.java.plugin.PluginLifecycleException;
import org.java.plugin.registry.Extension;
import org.java.plugin.registry.ExtensionPoint;
import org.java.plugin.registry.PluginDescriptor;

/*
* Copyright 2010 Alastair George Mailer

   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.
*/


/**
*
* The FiletypeHandler class defines a superclass for all classes
* looking to handle a particular set of filetypes for the Lucene
* plugin.
*
* @author agm
*
*/
public abstract class FiletypeHandler extends Plugin implements FilenameFilter {

  private static Vector<FiletypeHandler> handlers = new Vector<FiletypeHandler>();
 
  private static final Logger logger = Logger.getLogger(FiletypeHandler.class.getCanonicalName());
 
  static {
    logger.setLevel(Level.FINE);
  }
 
  private static final String CORE_PLUGIN_ID = "org.alastairmailer.luceneplugin";

  private static final String EXTENSION_ID = "FiletypeHandler";
 
  @SuppressWarnings("unchecked")
  public static void loadHandlers() {
    ExtensionPoint fhExt = PluginCore.getManager().getRegistry().getExtensionPoint(CORE_PLUGIN_ID, EXTENSION_ID);
    for (Extension e : fhExt.getConnectedExtensions()) {
      String pluginClassName = "";
      try {
       
        PluginDescriptor extensionDescriptor = e.getDeclaringPluginDescriptor();
        pluginClassName = e.getParameter("class").valueAsString();
        ClassLoader classLoader = PluginCore.getManager().getPluginClassLoader(extensionDescriptor);
        PluginCore.getManager().activatePlugin(extensionDescriptor.getId());
        Class<FiletypeHandler>pluginClass = (Class<FiletypeHandler>) classLoader.loadClass(pluginClassName);
        FiletypeHandler pluginInstance = pluginClass.newInstance();
        FiletypeHandler.register(pluginInstance);
        pluginInstance.desc = e;
        String fhName = e.getParameter("name").valueAsString();
        logger.info("Loaded filetype handler: " + fhName);
      } catch (PluginLifecycleException e1) {
        logger.severe("Unable to activate plugin " + e.getId());
        logger.severe("Exception: " + e1.toString());
      } catch (ClassNotFoundException e1) {
        logger.severe("Unable to locate class " + pluginClassName + " for plugin " + e.getId());
        logger.severe("Exception: " + e1.toString());
      } catch (InstantiationException e1) {
        logger.severe("Unable to instantiate class " + pluginClassName + " for plugin " + e.getId());
        logger.severe("Exception: " + e1.toString());
      } catch (IllegalAccessException e1) {
        logger.severe("Unable to instantiate class " + pluginClassName + " for plugin " + e.getId());
        logger.severe("Exception: " + e1.toString());
      }
    }
  }
 
  public static void register(FiletypeHandler fh) {
    handlers.add(fh);
  }

        public static List<FiletypeHandler> getRegisteredHandlers() {
            return Collections.unmodifiableList(handlers);
        }

  /**
   * Returns a FiletypeHandler subclass which can handle the given file.
   * This is determined by finding the first handler in this.handlers
   * whose accept method returns true for the file. If no handler is
   * present which can handle the file, getHandler returns null.
   *
   * @param file File object to find a handler for.
   * @return A FiletypeHandler to handle the file or null if none exists.
   */
  public static FiletypeHandler getHandler(File file) {

    FiletypeHandler h = null;
    Iterator<FiletypeHandler> i = handlers.iterator();
    while (i.hasNext() && h == null) {
      FiletypeHandler handler = i.next();
      if (handler.accept(file.getParentFile(), file.getName())) {
        h = handler;
      }
    }
   
    return h;
  }
 
  /**
   * This method allows a handler to define a custom TableCellRenderer
   * for its particular filetype, to allow customisation of the
   * results table. The default renderer here simply returns an
   * icon to represent the filetype.
   *
   * @return A TableCellRenderer to render table rows corresponding to this file type.
   *
   */
  public static TableCellRenderer getRenderer() {

    return new TableCellRenderer() {
      public Component getTableCellRendererComponent(JTable table, Object value,
          boolean isSelected, boolean hasFocus, int row, int column) {
        FiletypeHandler fh = getHandler((File)value);
        JLabel l;
        if (fh != null) {
          l = new JLabel(fh.getIcon());
          l.setOpaque(true);
          if (isSelected) { l.setBackground(table.getSelectionBackground()); }
          else { l.setBackground(table.getBackground()); }
        } else {
          // This shouldn't happen, as only files with FiletypeHandlers are indexed
          l = new JLabel();
        }
        return l;
      }
    };
  }
 
  protected Extension desc;
 
  /* (non-Javadoc)
   * @see java.io.FilenameFilter#accept(java.io.File, java.lang.String)
   */
  public abstract boolean accept(File dir, String name);
 
  /**
   * Method to construct a Lucene Document object to represent the
   * given file.
   *
   * @param f File to build a Document for.
   * @return A Lucene Document object representing f.
   * @throws IOException If there is an error accessing f.
   */
  protected abstract Document getDocument(File f) throws IOException;
 
  /**
   * This method wraps the protected method implemented by subclasses
   * of FiletypeHandler and assigns a modification date sensitive
   * unique ID field ("uid") to allow updates and deletions of the
   * document from an index.
   *
   * @param f File to get a Document object for.
   * @return A Lucene Document representing f with a unique ID field.
   * @throws IOException If there is an error accessing f.
   */
  public Document getLuceneDocument(File fileDir, String rel_path) throws IOException {
                File f = new File(fileDir, rel_path);
    FiletypeHandler fh = getHandler(f);
    Document d = fh.getDocument(f);
//    d.add(new Field("uid", fh.getUID(f), Field.Store.YES, Field.Index.NOT_ANALYZED));
                d.add(new Field("rel_path", rel_path, Field.Store.YES, Field.Index.NOT_ANALYZED));
                d.add(new Field("mod", "" + f.lastModified(), Field.Store.YES, Field.Index.NOT_ANALYZED));
    return d;
  }
 
  /**
   * Method for generating unique IDs on a per filetype basis.
   *
   * @param f File to get a UID for
   * @return A String representation of the UID of f.
   */
  public abstract String getUID(File f);

  /**
   * A method to return an icon representing this filetype.
   *
   * @return An icon representing this filetype.
   */
  public abstract Icon getIcon();
 
  /**
   * Once a user has selected an entry in the results table, the
   * plugin needs to generate a view of the search matches within
   * the file. This method should return a Component (probably a
   * JPanel with other nested Components) which provides this view
   * for any given file of this filetype.
   *
   * @return A Component capable of displaying any file of the given
   * filetype.
   *
   * @see showContext()
   */
  public abstract Component getContextComponent();
 
  /**
   * Method to update the context component to display a file
   * with the context of the given search query made clear (e.g.
   * highlighted)
   * 
   * @param f File to display
   * @param searchQ Search query to highlight context of
   */
  public abstract void showContext(File f, String searchQ);
 
  /**
   * This method is called when the plugin has determined that the
   * user may wish to view the given file with the given terms. It
   * gives FiletypeHandlers the option to begin loading the given
   * files into memory in the background, to enable smooth viewing
   * when decoding a file may be processor intensive (e.g. decoding
   * a PDF). This method should complete quickly as it runs on the
   * event dispatch thread (e.g. run decoding threads in the background!)
   *
   * @param f File to cache
   * @param terms Context to highlight in cache
   */
  public void cache(File f, String[] terms) {
    logger.info("Caching " + f.toString());
  }
 
  /**
   * This indicates to FiletypeHandlers that the given file is no
   * longer likely to be viewed by the user, so any cached resources
   * associated with it can be released.
   *
   * @param f File to decache
   */
  public void decache(File f) {
    logger.info("Decaching " + f.toString());
  }
 
  /**
   * A FiletypeHandler context element may place components in this JPanel, such
   * as command buttons etc.
   *
   * @return A JPanel on which command buttons etc. for the context element may be placed.
   *
   */
  public abstract JPanel getButtonBar();

    public String getPluginName() {
      return desc.getParameter("name").valueAsString() + " (" + desc.getParameter("class").valueAsString() +")";
     
    }

    public String getPluginAbout() {
      return desc.getParameter("description").valueAsString();
    }
       
}
TOP

Related Classes of org.alastairmailer.FiletypeHandler

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.