IndexDatabase.java revision 1028
207N/A/*
207N/A * CDDL HEADER START
207N/A *
207N/A * The contents of this file are subject to the terms of the
207N/A * Common Development and Distribution License (the "License").
207N/A * You may not use this file except in compliance with the License.
207N/A *
207N/A * See LICENSE.txt included in this distribution for the specific
207N/A * language governing permissions and limitations under the License.
207N/A *
207N/A * When distributing Covered Code, include this CDDL HEADER in each
207N/A * file and include the License file at LICENSE.txt.
207N/A * If applicable, add the following below this CDDL HEADER, with the
207N/A * fields enclosed by brackets "[]" replaced with your own identifying
207N/A * information: Portions Copyright [yyyy] [name of copyright owner]
207N/A *
207N/A * CDDL HEADER END
207N/A */
207N/A
207N/A/*
1393N/A * Copyright 2010 Sun Microsystems, Inc. All rights reserved.
207N/A * Use is subject to license terms.
1051N/A */
207N/Apackage org.opensolaris.opengrok.index;
207N/A
207N/Aimport java.io.BufferedInputStream;
207N/Aimport java.io.File;
207N/Aimport java.io.FileInputStream;
207N/Aimport java.io.FileNotFoundException;
207N/Aimport java.io.IOException;
207N/Aimport java.io.InputStream;
207N/Aimport java.util.ArrayList;
207N/Aimport java.util.Arrays;
282N/Aimport java.util.Comparator;
207N/Aimport java.util.List;
261N/Aimport java.util.concurrent.ExecutorService;
320N/Aimport java.util.logging.Level;
312N/Aimport java.util.logging.Logger;
1318N/Aimport org.apache.lucene.document.DateTools;
1318N/Aimport org.apache.lucene.document.Document;
207N/Aimport org.apache.lucene.index.IndexReader;
207N/Aimport org.apache.lucene.index.IndexWriter;
1127N/Aimport org.apache.lucene.index.Term;
1318N/Aimport org.apache.lucene.index.TermEnum;
1318N/Aimport org.apache.lucene.search.spell.LuceneDictionary;
1127N/Aimport org.apache.lucene.search.spell.SpellChecker;
1127N/Aimport org.apache.lucene.store.FSDirectory;
1127N/Aimport org.apache.lucene.store.LockFactory;
1127N/Aimport org.apache.lucene.store.NoLockFactory;
207N/Aimport org.apache.lucene.store.SimpleFSLockFactory;
207N/Aimport org.opensolaris.opengrok.analysis.AnalyzerGuru;
207N/Aimport org.opensolaris.opengrok.analysis.Ctags;
928N/Aimport org.opensolaris.opengrok.analysis.FileAnalyzer;
928N/Aimport org.opensolaris.opengrok.analysis.FileAnalyzer.Genre;
928N/Aimport org.opensolaris.opengrok.configuration.Project;
1318N/Aimport org.opensolaris.opengrok.configuration.RuntimeEnvironment;
207N/Aimport org.opensolaris.opengrok.history.HistoryException;
656N/Aimport org.opensolaris.opengrok.history.HistoryGuru;
1127N/Aimport org.opensolaris.opengrok.web.Util;
207N/A
207N/A/**
207N/A * This class is used to create / update the index databases. Currently we use
207N/A * one index database per project.
678N/A *
480N/A * @author Trond Norbye
1127N/A * @author Lubos Kosco , update for lucene 3.0.0
1318N/A */
1264N/Apublic class IndexDatabase {
207N/A
207N/A private Project project;
207N/A private FSDirectory indexDirectory;
207N/A private FSDirectory spellDirectory;
1190N/A private IndexWriter writer;
1190N/A private TermEnum uidIter;
207N/A private IgnoredNames ignoredNames;
928N/A private Filter includedNames;
207N/A private AnalyzerGuru analyzerGuru;
207N/A private File xrefDir;
207N/A private boolean interrupted;
207N/A private List<IndexChangedListener> listeners;
207N/A private File dirtyFile;
207N/A private final Object lock = new Object();
207N/A private boolean dirty;
207N/A private boolean running;
207N/A private List<String> directories;
1026N/A private static final Logger log = Logger.getLogger(IndexDatabase.class.getName());
207N/A private Ctags ctags;
207N/A private LockFactory lockfact;
207N/A
207N/A /**
253N/A * Create a new instance of the Index Database. Use this constructor if
359N/A * you don't use any projects
207N/A *
359N/A * @throws java.io.IOException if an error occurs while creating directories
274N/A */
1264N/A public IndexDatabase() throws IOException {
656N/A this(null);
928N/A }
656N/A
207N/A /**
207N/A * Create a new instance of an Index Database for a given project
207N/A * @param project the project to create the database for
1190N/A * @throws java.io.IOException if an errror occurs while creating directories
207N/A */
207N/A public IndexDatabase(Project project) throws IOException {
207N/A this.project = project;
1190N/A lockfact = new SimpleFSLockFactory();
207N/A initialize();
207N/A }
207N/A
207N/A /**
207N/A * Update the index database for all of the projects. Print progress to
207N/A * standard out.
207N/A * @param executor An executor to run the job
1190N/A * @throws IOException if an error occurs
207N/A */
928N/A public static void updateAll(ExecutorService executor) throws IOException {
207N/A updateAll(executor, null);
207N/A }
207N/A
207N/A /**
207N/A * Update the index database for all of the projects
207N/A * @param executor An executor to run the job
261N/A * @param listener where to signal the changes to the database
459N/A * @throws IOException if an error occurs
207N/A */
459N/A static void updateAll(ExecutorService executor, IndexChangedListener listener) throws IOException {
261N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
207N/A List<IndexDatabase> dbs = new ArrayList<IndexDatabase>();
207N/A
207N/A if (env.hasProjects()) {
207N/A for (Project project : env.getProjects()) {
261N/A dbs.add(new IndexDatabase(project));
207N/A }
459N/A } else {
207N/A dbs.add(new IndexDatabase());
312N/A }
207N/A
564N/A for (IndexDatabase d : dbs) {
1190N/A final IndexDatabase db = d;
207N/A if (listener != null) {
207N/A db.addIndexChangedListener(listener);
564N/A }
207N/A
207N/A executor.submit(new Runnable() {
564N/A
564N/A public void run() {
1190N/A try {
564N/A db.update();
564N/A } catch (Exception e) {
207N/A log.log(Level.FINE,"Problem updating lucene index database: ",e);
207N/A }
207N/A }
1190N/A });
261N/A }
261N/A }
1054N/A
261N/A /**
261N/A * Update the index database for a number of sub-directories
261N/A * @param executor An executor to run the job
1264N/A * @param listener where to signal the changes to the database
1264N/A * @param paths
261N/A * @throws IOException if an error occurs
261N/A */
261N/A public static void update(ExecutorService executor, IndexChangedListener listener, List<String> paths) throws IOException {
207N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
207N/A List<IndexDatabase> dbs = new ArrayList<IndexDatabase>();
207N/A
668N/A for (String path : paths) {
668N/A Project project = Project.getProject(path);
668N/A if (project == null && env.hasProjects()) {
668N/A log.warning("Could not find a project for \"" + path + "\"");
668N/A } else {
668N/A IndexDatabase db;
668N/A
668N/A try {
668N/A if (project == null) {
668N/A db = new IndexDatabase();
668N/A } else {
668N/A db = new IndexDatabase(project);
668N/A }
668N/A
1054N/A int idx = dbs.indexOf(db);
668N/A if (idx != -1) {
668N/A db = dbs.get(idx);
668N/A }
668N/A
668N/A if (db.addDirectory(path)) {
668N/A if (idx == -1) {
668N/A dbs.add(db);
668N/A }
668N/A } else {
668N/A log.warning("Directory does not exist \"" + path + "\"");
668N/A }
668N/A } catch (IOException e) {
668N/A log.log(Level.WARNING, "An error occured while updating index", e);
668N/A
668N/A }
668N/A }
668N/A
668N/A for (final IndexDatabase db : dbs) {
668N/A db.addIndexChangedListener(listener);
668N/A executor.submit(new Runnable() {
1054N/A
668N/A public void run() {
668N/A try {
668N/A db.update();
668N/A } catch (Exception e) {
668N/A log.log(Level.WARNING, "An error occured while updating index", e);
668N/A }
668N/A }
668N/A });
668N/A }
668N/A }
668N/A }
1054N/A
668N/A @SuppressWarnings("PMD.CollapsibleIfStatements")
668N/A private void initialize() throws IOException {
668N/A synchronized (this) {
1264N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
1264N/A File indexDir = new File(env.getDataRootFile(), "index");
668N/A File spellDir = new File(env.getDataRootFile(), "spellIndex");
668N/A if (project != null) {
668N/A indexDir = new File(indexDir, project.getPath());
668N/A spellDir = new File(spellDir, project.getPath());
668N/A }
668N/A
668N/A if (!indexDir.exists() && !indexDir.mkdirs()) {
460N/A // to avoid race conditions, just recheck..
580N/A if (!indexDir.exists()) {
580N/A throw new FileNotFoundException("Failed to create root directory [" + indexDir.getAbsolutePath() + "]");
580N/A }
580N/A }
580N/A
580N/A if (!spellDir.exists() && !spellDir.mkdirs()) {
580N/A if (!spellDir.exists()) {
580N/A throw new FileNotFoundException("Failed to create root directory [" + spellDir.getAbsolutePath() + "]");
580N/A }
580N/A }
580N/A
580N/A if (!env.isUsingLuceneLocking()) {
580N/A lockfact = NoLockFactory.getNoLockFactory();
580N/A }
580N/A indexDirectory = FSDirectory.open(indexDir,lockfact);
580N/A spellDirectory = FSDirectory.open(spellDir,lockfact);
207N/A ignoredNames = env.getIgnoredNames();
580N/A includedNames = env.getIncludedNames();
580N/A analyzerGuru = new AnalyzerGuru();
580N/A if (env.isGenerateHtml()) {
580N/A xrefDir = new File(env.getDataRootFile(), "xref");
580N/A }
1190N/A listeners = new ArrayList<IndexChangedListener>();
580N/A dirtyFile = new File(indexDir, "dirty");
928N/A dirty = dirtyFile.exists();
207N/A directories = new ArrayList<String>();
928N/A }
928N/A }
580N/A
1026N/A /**
580N/A * By default the indexer will traverse all directories in the project.
580N/A * If you add directories with this function update will just process
580N/A * the specified directories.
580N/A *
580N/A * @param dir The directory to scan
580N/A * @return <code>true</code> if the file is added, false oth
580N/A */
580N/A @SuppressWarnings("PMD.UseStringBufferForStringAppends")
359N/A public boolean addDirectory(String dir) {
207N/A String directory = dir;
207N/A if (directory.startsWith("\\")) {
207N/A directory = directory.replace('\\', '/');
274N/A } else if (directory.charAt(0) != '/') {
274N/A directory = "/" + directory;
274N/A }
1190N/A File file = new File(RuntimeEnvironment.getInstance().getSourceRootFile(), directory);
274N/A if (file.exists()) {
297N/A directories.add(directory);
274N/A return true;
464N/A } else {
274N/A return false;
439N/A }
439N/A }
439N/A
464N/A /**
439N/A * Update the content of this index database
297N/A * @throws IOException if an error occurs
439N/A * @throws HistoryException if an error occurs when accessing the history
460N/A */
439N/A public void update() throws IOException, HistoryException {
274N/A synchronized (lock) {
274N/A if (running) {
1185N/A throw new IOException("Indexer already running!");
274N/A }
1190N/A running = true;
274N/A interrupted = false;
207N/A }
459N/A
678N/A String ctgs = RuntimeEnvironment.getInstance().getCtags();
207N/A if (ctgs != null) {
678N/A ctags = new Ctags();
359N/A ctags.setBinary(ctgs);
359N/A }
459N/A if (ctags == null) {
359N/A log.severe("Unable to run ctags! searching definitions will not work!");
359N/A }
359N/A
359N/A try {
656N/A //TODO we might need to add writer.commit after certain phases of index generation, right now it will only happen in the end
694N/A writer = new IndexWriter(indexDirectory, AnalyzerGuru.getAnalyzer(),IndexWriter.MaxFieldLength.UNLIMITED);
694N/A writer.setMaxFieldLength(RuntimeEnvironment.getInstance().getIndexWordLimit());
656N/A
694N/A if (directories.isEmpty()) {
656N/A if (project == null) {
656N/A directories.add("");
656N/A } else {
656N/A directories.add(project.getPath());
656N/A }
1393N/A }
1393N/A
1393N/A for (String dir : directories) {
1393N/A File sourceRoot;
1393N/A if ("".equals(dir)) {
1393N/A sourceRoot = RuntimeEnvironment.getInstance().getSourceRootFile();
1393N/A } else {
207N/A sourceRoot = new File(RuntimeEnvironment.getInstance().getSourceRootFile(), dir);
816N/A }
1318N/A
1318N/A HistoryGuru.getInstance().ensureHistoryCacheExists(sourceRoot);
1318N/A
1318N/A String startuid = Util.uid(dir, "");
1318N/A IndexReader reader = IndexReader.open(indexDirectory,false); // open existing index
1318N/A try {
1318N/A uidIter = reader.terms(new Term("u", startuid)); // init uid iterator
207N/A
456N/A indexDown(sourceRoot, dir);
460N/A
460N/A while (uidIter.term() != null && uidIter.term().field().equals("u") && uidIter.term().text().startsWith(startuid)) {
460N/A removeFile();
274N/A uidIter.next();
274N/A }
207N/A } finally {
651N/A reader.close();
274N/A }
274N/A }
456N/A } finally {
274N/A if (writer != null) {
274N/A try {
274N/A writer.close();
274N/A } catch (IOException e) {
1190N/A log.log(Level.WARNING, "An error occured while closing writer", e);
651N/A }
651N/A }
1185N/A
1425N/A if (ctags != null) {
457N/A try {
457N/A ctags.close();
207N/A } catch (IOException e) {
1112N/A log.log(Level.WARNING, "An error occured while closing ctags process", e);
1108N/A }
1114N/A }
1114N/A
1114N/A synchronized (lock) {
1114N/A running = false;
1114N/A }
1114N/A }
1112N/A
1108N/A if (!isInterrupted() && isDirty()) {
1108N/A if (RuntimeEnvironment.getInstance().isOptimizeDatabase()) {
207N/A optimize();
457N/A }
457N/A createSpellingSuggestions();
457N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
457N/A File timestamp = new File(env.getDataRootFile(), "timestamp");
457N/A if (timestamp.exists()) {
457N/A if (!timestamp.setLastModified(System.currentTimeMillis())) {
274N/A log.warning("Failed to set last modified time on '" + timestamp.getAbsolutePath() + "', used for timestamping the index database.");
207N/A }
207N/A } else {
207N/A if (!timestamp.createNewFile()) {
1054N/A log.warning("Failed to create file '" + timestamp.getAbsolutePath() + "', used for timestamping the index database.");
207N/A }
207N/A }
1190N/A }
207N/A }
207N/A
656N/A /**
656N/A * Optimize all index databases
656N/A * @param executor An executor to run the job
656N/A * @throws IOException if an error occurs
656N/A */
656N/A static void optimizeAll(ExecutorService executor) throws IOException {
656N/A List<IndexDatabase> dbs = new ArrayList<IndexDatabase>();
656N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
656N/A if (env.hasProjects()) {
359N/A for (Project project : env.getProjects()) {
359N/A dbs.add(new IndexDatabase(project));
359N/A }
207N/A } else {
207N/A dbs.add(new IndexDatabase());
359N/A }
253N/A
253N/A for (IndexDatabase d : dbs) {
253N/A final IndexDatabase db = d;
207N/A if (db.isDirty()) {
667N/A executor.submit(new Runnable() {
667N/A
667N/A public void run() {
672N/A try {
1054N/A db.update();
672N/A } catch (Exception e) {
667N/A log.log(Level.FINE,"Problem updating lucene index database: ",e);
672N/A }
1054N/A }
672N/A });
667N/A }
207N/A }
207N/A }
207N/A
207N/A /**
270N/A * Optimize the index database
270N/A */
459N/A public void optimize() {
270N/A synchronized (lock) {
312N/A if (running) {
1190N/A log.warning("Optimize terminated... Someone else is updating / optimizing it!");
270N/A return ;
270N/A }
270N/A running = true;
564N/A }
270N/A IndexWriter wrt = null;
270N/A try {
564N/A if (RuntimeEnvironment.getInstance().isVerbose()) {
564N/A log.info("Optimizing the index ... ");
564N/A }
564N/A wrt = new IndexWriter(indexDirectory, null, false,IndexWriter.MaxFieldLength.UNLIMITED);
564N/A wrt.optimize();
359N/A if (RuntimeEnvironment.getInstance().isVerbose()) {
270N/A log.info("done");
270N/A }
1054N/A synchronized (lock) {
270N/A if (dirtyFile.exists() && !dirtyFile.delete()) {
270N/A log.fine("Failed to remove \"dirty-file\": " +
270N/A dirtyFile.getAbsolutePath());
1264N/A }
1264N/A dirty = false;
270N/A }
270N/A } catch (IOException e) {
270N/A log.severe("ERROR: optimizing index: " + e);
270N/A } finally {
270N/A if (wrt != null) {
270N/A try {
1190N/A wrt.close();
270N/A } catch (IOException e) {
207N/A log.log(Level.WARNING, "An error occured while closing writer", e);
207N/A }
207N/A }
359N/A synchronized (lock) {
359N/A running = false;
359N/A }
359N/A }
359N/A }
359N/A
359N/A /**
207N/A * Generate a spelling suggestion for the definitions stored in defs
1190N/A */
1190N/A public void createSpellingSuggestions() {
1318N/A IndexReader indexReader = null;
1318N/A SpellChecker checker = null;
1318N/A
1318N/A try {
1318N/A if (RuntimeEnvironment.getInstance().isVerbose()) {
1318N/A log.info("Generating spelling suggestion index ... ");
1190N/A }
359N/A indexReader = IndexReader.open(indexDirectory,false);
460N/A checker = new SpellChecker(spellDirectory);
1054N/A //TODO below seems only to index "defs" , possible bug ?
359N/A checker.indexDictionary(new LuceneDictionary(indexReader, "defs"));
359N/A if (RuntimeEnvironment.getInstance().isVerbose()) {
359N/A log.info("done");
207N/A }
1054N/A } catch (IOException e) {
207N/A log.severe("ERROR: Generating spelling: " + e);
207N/A } finally {
207N/A if (indexReader != null) {
207N/A try {
207N/A indexReader.close();
508N/A } catch (IOException e) {
207N/A log.log(Level.WARNING, "An error occured while closing reader", e);
207N/A }
359N/A }
359N/A if (spellDirectory != null) {
359N/A spellDirectory.close();
207N/A }
207N/A }
207N/A }
207N/A
207N/A private boolean isDirty() {
207N/A synchronized (lock) {
207N/A return dirty;
207N/A }
207N/A }
207N/A
1190N/A private void setDirty() {
1190N/A synchronized (lock) {
1425N/A try {
207N/A if (!dirty && !dirtyFile.createNewFile()) {
830N/A if (!dirtyFile.exists()) {
1318N/A log.log(Level.FINE,
1318N/A "Failed to create \"dirty-file\": {0}",
1318N/A dirtyFile.getAbsolutePath());
1318N/A }
1190N/A dirty = true;
207N/A }
1054N/A } catch (IOException e) {
207N/A log.log(Level.FINE,"When creating dirty file: ",e);
207N/A }
207N/A }
207N/A }
207N/A /**
508N/A * Remove a stale file (uidIter.term().text()) from the index database
207N/A * (and the xref file)
207N/A * @throws java.io.IOException if an error occurs
207N/A */
207N/A private void removeFile() throws IOException {
207N/A String path = Util.uid2url(uidIter.term().text());
207N/A
207N/A for (IndexChangedListener listener : listeners) {
207N/A listener.fileRemoved(path);
359N/A }
359N/A writer.deleteDocuments(uidIter.term());
359N/A
359N/A File xrefFile;
359N/A if (RuntimeEnvironment.getInstance().isCompressXref()) {
359N/A xrefFile = new File(xrefDir, path + ".gz");
359N/A } else {
359N/A xrefFile = new File(xrefDir, path);
359N/A }
460N/A File parent = xrefFile.getParentFile();
460N/A
888N/A if (!xrefFile.delete() && xrefFile.exists()) {
888N/A log.info("Failed to remove obsolete xref-file: " +
888N/A xrefFile.getAbsolutePath());
359N/A }
359N/A
359N/A // Remove the parent directory if it's empty
359N/A if (parent.delete()) {
359N/A log.fine("Removed empty xref dir:" + parent.getAbsolutePath());
253N/A }
253N/A
253N/A setDirty();
207N/A }
1190N/A
207N/A /**
207N/A * Add a file to the Lucene index (and generate a xref file)
207N/A * @param file The file to add
207N/A * @param path The path to the file (from source root)
207N/A * @throws java.io.IOException if an error occurs
207N/A */
207N/A private void addFile(File file, String path) throws IOException {
1054N/A final InputStream in =
207N/A new BufferedInputStream(new FileInputStream(file));
207N/A try {
207N/A FileAnalyzer fa = AnalyzerGuru.getAnalyzer(in, path);
515N/A if (log.isLoggable(Level.FINER)) {
515N/A log.finer("Adding file:"+path);}
515N/A fa.setCtags(ctags);
515N/A fa.setProject(Project.getProject(path));
515N/A
515N/A Document d;
359N/A try {
359N/A d = analyzerGuru.getDocument(file, in, path, fa);
602N/A } catch (Exception e) {
1054N/A log.log(Level.INFO,
359N/A "Skipped file ''{0}'' because the analyzer didn''t " +
359N/A "understand it.",
506N/A path);
506N/A log.log(Level.FINE, "Exception from analyzer:", e);
1054N/A return;
506N/A }
253N/A
1054N/A writer.addDocument(d, fa);
1054N/A Genre g = fa.getFactory().getGenre();
1190N/A if (xrefDir != null && (g == Genre.PLAIN || g == Genre.XREFABLE)) {
207N/A File xrefFile = new File(xrefDir, path);
207N/A // If mkdirs() returns false, the failure is most likely
207N/A // because the file already exists. But to check for the
207N/A // file first and only add it if it doesn't exists would
207N/A // only increase the file IO...
207N/A if (!xrefFile.getParentFile().mkdirs()) {
207N/A assert xrefFile.getParentFile().exists();
207N/A }
594N/A fa.writeXref(xrefDir, path);
594N/A }
594N/A setDirty();
212N/A for (IndexChangedListener listener : listeners) {
1190N/A listener.fileAdded(path, fa.getClass().getSimpleName());
1054N/A }
1054N/A } finally {
1054N/A in.close();
656N/A }
922N/A }
207N/A
889N/A /**
889N/A * Check if I should accept this file into the index database
889N/A * @param file the file to check
889N/A * @return true if the file should be included, false otherwise
889N/A */
889N/A private boolean accept(File file) {
889N/A
889N/A if (!includedNames.isEmpty() &&
889N/A // the filter should not affect directory names
889N/A (!(file.isDirectory() || includedNames.match(file))) ) {
889N/A return false;
889N/A }
889N/A if (ignoredNames.ignore(file)) {
889N/A return false;
889N/A }
889N/A
889N/A String absolutePath = file.getAbsolutePath();
889N/A
889N/A if (!file.canRead()) {
889N/A log.warning("Warning: could not read " + absolutePath);
889N/A return false;
889N/A }
506N/A
889N/A try {
889N/A String canonicalPath = file.getCanonicalPath();
889N/A if (!absolutePath.equals(canonicalPath) && !acceptSymlink(absolutePath, canonicalPath)) {
889N/A log.fine("Skipped symlink '" + absolutePath +
889N/A "' -> '" + canonicalPath + "'");
207N/A return false;
553N/A }
594N/A //below will only let go files and directories, anything else is considered special and is not added
508N/A if (!file.isFile() && !file.isDirectory()) {
207N/A log.warning("Warning: ignored special file " + absolutePath);
207N/A return false;
207N/A }
207N/A } catch (IOException exp) {
207N/A log.warning("Warning: Failed to resolve name: " + absolutePath);
207N/A log.log(Level.FINE,"Stack Trace: ",exp);
207N/A }
207N/A
1028N/A if (file.isDirectory()) {
1028N/A // always accept directories so that their files can be examined
1028N/A return true;
1028N/A }
1026N/A
1026N/A if (HistoryGuru.getInstance().hasHistory(file)) {
207N/A // versioned files should always be accepted
207N/A return true;
207N/A }
207N/A
1016N/A // this is an unversioned file, check if it should be indexed
1016N/A return !RuntimeEnvironment.getInstance().isIndexVersionedFilesOnly();
207N/A }
1054N/A
207N/A /**
207N/A * Check if I should accept the path containing a symlink
207N/A * @param absolutePath the path with a symlink to check
207N/A * @param canonicalPath the canonical path to the file
1016N/A * @return true if the file should be accepted, false otherwise
1016N/A */
1054N/A private boolean acceptSymlink(String absolutePath, String canonicalPath) throws IOException {
1016N/A for (String allowedSymlink : RuntimeEnvironment.getInstance().getAllowedSymlinks()) {
207N/A if (absolutePath.startsWith(allowedSymlink)) {
876N/A String allowedTarget = new File(allowedSymlink).getCanonicalPath();
872N/A if (canonicalPath.startsWith(allowedTarget) &&
1054N/A absolutePath.substring(allowedSymlink.length()).equals(canonicalPath.substring(allowedTarget.length()))) {
872N/A return true;
872N/A }
207N/A }
1054N/A }
1190N/A return false;
207N/A }
207N/A
504N/A /**
504N/A * Generate indexes recursively
504N/A * @param dir the root indexDirectory to generate indexes for
480N/A * @param path the path
480N/A */
504N/A private void indexDown(File dir, String parent) throws IOException {
504N/A if (isInterrupted()) {
504N/A return;
504N/A }
504N/A
504N/A if (!accept(dir)) {
504N/A return;
207N/A }
207N/A
1192N/A File[] files = dir.listFiles();
1192N/A if (files == null) {
1192N/A log.severe("Failed to get file listing for: " + dir.getAbsolutePath());
1192N/A return;
1192N/A }
1192N/A Arrays.sort(files, new Comparator<File>() {
1192N/A
1192N/A public int compare(File p1, File p2) {
1192N/A return p1.getName().compareTo(p2.getName());
1192N/A }
1192N/A });
1192N/A
1192N/A for (File file : files) {
1192N/A if (accept(file)) {
1192N/A String path = parent + '/' + file.getName();
1192N/A if (file.isDirectory()) {
1192N/A indexDown(file, path);
1192N/A } else {
1192N/A if (uidIter != null) {
1192N/A String uid = Util.uid(path, DateTools.timeToString(file.lastModified(), DateTools.Resolution.MILLISECOND)); // construct uid for doc
1192N/A while (uidIter.term() != null && uidIter.term().field().equals("u") &&
1192N/A uidIter.term().text().compareTo(uid) < 0) {
1192N/A removeFile();
1192N/A uidIter.next();
1192N/A }
1192N/A
1192N/A if (uidIter.term() != null && uidIter.term().field().equals("u") &&
1192N/A uidIter.term().text().compareTo(uid) == 0) {
207N/A uidIter.next(); // keep matching docs
1016N/A continue;
1016N/A }
1016N/A }
1016N/A try {
1016N/A addFile(file, path);
1016N/A } catch (Exception e) {
1051N/A log.log(Level.WARNING,
1051N/A "Failed to add file " + file.getAbsolutePath(),
1051N/A e);
1051N/A }
1051N/A }
1016N/A }
1016N/A }
1016N/A }
1016N/A
1016N/A /**
1016N/A * Interrupt the index generation (and the index generation will stop as
1016N/A * soon as possible)
1016N/A */
1016N/A public void interrupt() {
1016N/A synchronized (lock) {
1016N/A interrupted = true;
1016N/A }
1016N/A }
1051N/A
1051N/A private boolean isInterrupted() {
1051N/A synchronized (lock) {
1051N/A return interrupted;
1051N/A }
1051N/A }
1051N/A
1051N/A /**
1051N/A * Register an object to receive events when modifications is done to the
1051N/A * index database.
1051N/A *
1051N/A * @param listener the object to receive the events
1051N/A */
1051N/A public void addIndexChangedListener(IndexChangedListener listener) {
1051N/A listeners.add(listener);
1051N/A }
1051N/A
1051N/A /**
1051N/A * Remove an object from the lists of objects to receive events when
1051N/A * modifications is done to the index database
1051N/A *
1051N/A * @param listener the object to remove
1051N/A */
1051N/A public void removeIndexChangedListener(IndexChangedListener listener) {
1051N/A listeners.remove(listener);
1051N/A }
1051N/A
1051N/A /**
1051N/A * List all files in all of the index databases
1051N/A * @throws IOException if an error occurs
207N/A */
207N/A public static void listAllFiles() throws IOException {
207N/A listAllFiles(null);
1112N/A }
1112N/A
1112N/A /**
1112N/A * List all files in some of the index databases
207N/A * @param subFiles Subdirectories for the various projects to list the files
1108N/A * for (or null or an empty list to dump all projects)
1112N/A * @throws IOException if an error occurs
359N/A */
1112N/A public static void listAllFiles(List<String> subFiles) throws IOException {
207N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
207N/A if (env.hasProjects()) {
207N/A if (subFiles == null || subFiles.isEmpty()) {
1112N/A for (Project project : env.getProjects()) {
207N/A IndexDatabase db = new IndexDatabase(project);
207N/A db.listFiles();
207N/A }
207N/A } else {
1054N/A for (String path : subFiles) {
1112N/A Project project = Project.getProject(path);
207N/A if (project == null) {
282N/A log.warning("Warning: Could not find a project for \"" + path + "\"");
1054N/A } else {
282N/A IndexDatabase db = new IndexDatabase(project);
282N/A db.listFiles();
282N/A }
282N/A }
207N/A }
207N/A } else {
1192N/A IndexDatabase db = new IndexDatabase();
207N/A db.listFiles();
1108N/A }
207N/A }
1112N/A
207N/A /**
1112N/A * List all of the files in this index database
1112N/A *
1108N/A * @throws IOException If an IO error occurs while reading from the database
1112N/A */
1108N/A public void listFiles() throws IOException {
1114N/A IndexReader ireader = null;
1190N/A TermEnum iter = null;
1190N/A
1108N/A try {
1108N/A ireader = IndexReader.open(indexDirectory,false); // open existing index
594N/A iter = ireader.terms(new Term("u", "")); // init uid iterator
1185N/A while (iter.term() != null) {
207N/A log.info(Util.uid2url(iter.term().text()));
207N/A iter.next();
207N/A }
207N/A } finally {
207N/A if (iter != null) {
207N/A try {
207N/A iter.close();
207N/A } catch (IOException e) {
972N/A log.log(Level.WARNING, "An error occured while closing index iterator", e);
594N/A }
207N/A }
207N/A
594N/A if (ireader != null) {
594N/A try {
594N/A ireader.close();
594N/A } catch (IOException e) {
594N/A log.log(Level.WARNING, "An error occured while closing index reader", e);
594N/A }
594N/A }
207N/A }
207N/A }
207N/A
1108N/A static void listFrequentTokens() throws IOException {
1112N/A listFrequentTokens(null);
207N/A }
207N/A
207N/A static void listFrequentTokens(List<String> subFiles) throws IOException {
207N/A final int limit = 4;
207N/A
207N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
207N/A if (env.hasProjects()) {
359N/A if (subFiles == null || subFiles.isEmpty()) {
359N/A for (Project project : env.getProjects()) {
359N/A IndexDatabase db = new IndexDatabase(project);
359N/A db.listTokens(4);
359N/A }
359N/A } else {
359N/A for (String path : subFiles) {
359N/A Project project = Project.getProject(path);
1190N/A if (project == null) {
207N/A log.warning("Warning: Could not find a project for \"" + path + "\"");
207N/A } else {
207N/A IndexDatabase db = new IndexDatabase(project);
207N/A db.listTokens(4);
207N/A }
1190N/A }
207N/A }
207N/A } else {
316N/A IndexDatabase db = new IndexDatabase();
207N/A db.listTokens(limit);
207N/A }
207N/A }
207N/A
207N/A public void listTokens(int freq) throws IOException {
207N/A IndexReader ireader = null;
1190N/A TermEnum iter = null;
207N/A
207N/A try {
316N/A ireader = IndexReader.open(indexDirectory,false);
207N/A iter = ireader.terms(new Term("defs", ""));
207N/A while (iter.term() != null) {
207N/A if (iter.term().field().startsWith("f")) {
207N/A if (iter.docFreq() > 16 && iter.term().text().length() > freq) {
207N/A log.warning(iter.term().text());
359N/A }
207N/A iter.next();
312N/A } else {
207N/A break;
207N/A }
207N/A }
207N/A } finally {
207N/A if (iter != null) {
207N/A try {
207N/A iter.close();
359N/A } catch (IOException e) {
207N/A log.log(Level.WARNING, "An error occured while closing index iterator", e);
312N/A }
207N/A }
460N/A
207N/A if (ireader != null) {
207N/A try {
207N/A ireader.close();
207N/A } catch (IOException e) {
207N/A log.log(Level.WARNING, "An error occured while closing index reader", e);
207N/A }
207N/A }
207N/A }
207N/A }
1054N/A
207N/A /**
207N/A * Get an indexReader for the Index database where a given file
207N/A * @param path the file to get the database for
207N/A * @return The index database where the file should be located or null if
207N/A * it cannot be located.
207N/A */
460N/A public static IndexReader getIndexReader(String path) {
460N/A IndexReader ret = null;
460N/A
207N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
207N/A File indexDir = new File(env.getDataRootFile(), "index");
207N/A
207N/A if (env.hasProjects()) {
207N/A Project p = Project.getProject(path);
1190N/A if (p == null) {
359N/A return null;
207N/A } else {
312N/A indexDir = new File(indexDir, p.getPath());
207N/A }
207N/A }
207N/A try {
207N/A FSDirectory fdir=FSDirectory.open(indexDir,NoLockFactory.getNoLockFactory());
1425N/A if (indexDir.exists() && IndexReader.indexExists(fdir)) {
207N/A ret = IndexReader.open(fdir,false);
207N/A }
1112N/A } catch (Exception ex) {
207N/A log.severe("Failed to open index: " + indexDir.getAbsolutePath());
207N/A log.log(Level.FINE,"Stack Trace: ",ex);
207N/A }
207N/A return ret;
207N/A }
207N/A
459N/A @Override
580N/A public boolean equals(Object obj) {
207N/A if (obj == null) {
207N/A return false;
207N/A }
207N/A if (getClass() != obj.getClass()) {
207N/A return false;
207N/A }
459N/A final IndexDatabase other = (IndexDatabase) obj;
508N/A if (this.project != other.project && (this.project == null || !this.project.equals(other.project))) {
207N/A return false;
207N/A }
207N/A return true;
207N/A }
207N/A
459N/A @Override
207N/A public int hashCode() {
207N/A int hash = 7;
207N/A hash = 41 * hash + (this.project == null ? 0 : this.project.hashCode());
457N/A return hash;
207N/A }
207N/A
207N/A}
460N/A