IndexDatabase.java revision 922
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/*
207N/A * Copyright 2008 Sun Microsystems, Inc. All rights reserved.
207N/A * Use is subject to license terms.
207N/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;
207N/Aimport org.apache.lucene.document.DateTools;
207N/Aimport org.apache.lucene.document.Document;
207N/Aimport org.apache.lucene.index.IndexReader;
207N/Aimport org.apache.lucene.index.IndexWriter;
207N/Aimport org.apache.lucene.index.Term;
207N/Aimport org.apache.lucene.index.TermEnum;
207N/Aimport org.apache.lucene.search.spell.LuceneDictionary;
207N/Aimport org.apache.lucene.search.spell.SpellChecker;
207N/Aimport org.apache.lucene.store.FSDirectory;
207N/Aimport org.opensolaris.opengrok.analysis.AnalyzerGuru;
207N/Aimport org.opensolaris.opengrok.analysis.Ctags;
207N/Aimport org.opensolaris.opengrok.analysis.FileAnalyzer;
207N/Aimport org.opensolaris.opengrok.analysis.FileAnalyzer.Genre;
207N/Aimport org.opensolaris.opengrok.configuration.Project;
480N/Aimport org.opensolaris.opengrok.configuration.RuntimeEnvironment;
207N/Aimport org.opensolaris.opengrok.history.HistoryException;
207N/Aimport org.opensolaris.opengrok.history.HistoryGuru;
207N/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.
207N/A *
207N/A * @author Trond Norbye
207N/A */
207N/Apublic class IndexDatabase {
207N/A
207N/A private Project project;
207N/A private FSDirectory indexDirectory;
207N/A private FSDirectory spellDirectory;
207N/A private IndexWriter writer;
207N/A private TermEnum uidIter;
207N/A private IgnoredNames ignoredNames;
207N/A private AnalyzerGuru analyzerGuru;
207N/A private File xrefDir;
253N/A private boolean interrupted;
359N/A private List<IndexChangedListener> listeners;
207N/A private File dirtyFile;
359N/A private final Object lock = new Object();
274N/A private boolean dirty;
320N/A private boolean running;
274N/A private List<String> directories;
207N/A private static final Logger log = Logger.getLogger(IndexDatabase.class.getName());
207N/A private Ctags ctags;
207N/A
207N/A /**
207N/A * Create a new instance of the Index Database. Use this constructor if
207N/A * you don't use any projects
207N/A *
207N/A * @throws java.io.IOException if an error occurs while creating directories
207N/A */
207N/A public IndexDatabase() throws IOException {
207N/A initialize();
207N/A }
207N/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
207N/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;
207N/A initialize();
207N/A }
207N/A
261N/A /**
459N/A * Update the index database for all of the projects. Print progress to
207N/A * standard out.
459N/A * @param executor An executor to run the job
261N/A * @throws IOException if an error occurs
207N/A */
207N/A public static void updateAll(ExecutorService executor) throws IOException {
207N/A updateAll(executor, null);
207N/A }
261N/A
207N/A /**
459N/A * Update the index database for all of the projects
207N/A * @param executor An executor to run the job
312N/A * @param listener where to signal the changes to the database
207N/A * @throws IOException if an error occurs
564N/A */
564N/A static void updateAll(ExecutorService executor, IndexChangedListener listener) throws IOException {
207N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
207N/A List<IndexDatabase> dbs = new ArrayList<IndexDatabase>();
564N/A
207N/A if (env.hasProjects()) {
207N/A for (Project project : env.getProjects()) {
564N/A dbs.add(new IndexDatabase(project));
564N/A }
564N/A } else {
564N/A dbs.add(new IndexDatabase());
564N/A }
207N/A
207N/A for (IndexDatabase d : dbs) {
207N/A final IndexDatabase db = d;
261N/A if (listener != null) {
261N/A db.addIndexChangedListener(listener);
261N/A }
261N/A
261N/A executor.submit(new Runnable() {
261N/A
261N/A public void run() {
320N/A try {
261N/A db.update();
261N/A } catch (Exception e) {
261N/A log.log(Level.FINE,"Problem updating lucene index database: ",e);
207N/A }
207N/A }
207N/A });
460N/A }
338N/A }
207N/A
207N/A /**
207N/A * Update the index database for a number of sub-directories
207N/A * @param executor An executor to run the job
207N/A * @param listener where to signal the changes to the database
207N/A * @param paths
207N/A * @throws IOException if an error occurs
207N/A */
460N/A public static void update(ExecutorService executor, IndexChangedListener listener, List<String> paths) throws IOException {
460N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
460N/A List<IndexDatabase> dbs = new ArrayList<IndexDatabase>();
460N/A
207N/A for (String path : paths) {
359N/A Project project = Project.getProject(path);
359N/A if (project == null && env.hasProjects()) {
460N/A log.warning("Could not find a project for \"" + path + "\"");
460N/A } else {
460N/A IndexDatabase db;
207N/A
207N/A try {
207N/A if (project == null) {
296N/A db = new IndexDatabase();
296N/A } else {
296N/A db = new IndexDatabase(project);
207N/A }
207N/A
207N/A int idx = dbs.indexOf(db);
207N/A if (idx != -1) {
296N/A db = dbs.get(idx);
207N/A }
207N/A
207N/A if (db.addDirectory(path)) {
253N/A if (idx == -1) {
253N/A dbs.add(db);
274N/A }
207N/A } else {
207N/A log.warning("Directory does not exist \"" + path + "\"");
207N/A }
274N/A } catch (IOException e) {
274N/A log.log(Level.WARNING, "An error occured while updating index", e);
274N/A
274N/A }
274N/A }
297N/A
274N/A for (final IndexDatabase db : dbs) {
464N/A db.addIndexChangedListener(listener);
274N/A executor.submit(new Runnable() {
439N/A
439N/A public void run() {
439N/A try {
464N/A db.update();
439N/A } catch (Exception e) {
297N/A log.log(Level.WARNING, "An error occured while updating index", e);
439N/A }
460N/A }
439N/A });
274N/A }
460N/A }
460N/A }
274N/A
274N/A @SuppressWarnings("PMD.CollapsibleIfStatements")
274N/A private void initialize() throws IOException {
274N/A synchronized (this) {
207N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
459N/A File indexDir = new File(env.getDataRootFile(), "index");
207N/A File spellDir = new File(env.getDataRootFile(), "spellIndex");
459N/A if (project != null) {
359N/A indexDir = new File(indexDir, project.getPath());
359N/A spellDir = new File(spellDir, project.getPath());
459N/A }
359N/A
359N/A if (!indexDir.exists() && !indexDir.mkdirs()) {
359N/A // to avoid race conditions, just recheck..
359N/A if (!indexDir.exists()) {
207N/A throw new FileNotFoundException("Failed to create root directory [" + indexDir.getAbsolutePath() + "]");
207N/A }
255N/A }
207N/A
456N/A if (!spellDir.exists() && !spellDir.mkdirs()) {
460N/A if (!spellDir.exists()) {
460N/A throw new FileNotFoundException("Failed to create root directory [" + spellDir.getAbsolutePath() + "]");
460N/A }
274N/A }
274N/A
207N/A if (!env.isUsingLuceneLocking()) {
274N/A FSDirectory.setDisableLocks(true);
274N/A }
274N/A indexDirectory = FSDirectory.getDirectory(indexDir);
456N/A spellDirectory = FSDirectory.getDirectory(spellDir);
274N/A ignoredNames = env.getIgnoredNames();
274N/A analyzerGuru = new AnalyzerGuru();
274N/A if (env.isGenerateHtml()) {
274N/A xrefDir = new File(env.getDataRootFile(), "xref");
274N/A }
274N/A listeners = new ArrayList<IndexChangedListener>();
457N/A dirtyFile = new File(indexDir, "dirty");
457N/A dirty = dirtyFile.exists();
457N/A directories = new ArrayList<String>();
207N/A }
457N/A }
207N/A
457N/A /**
457N/A * By default the indexer will traverse all directories in the project.
457N/A * If you add directories with this function update will just process
457N/A * the specified directories.
457N/A *
457N/A * @param dir The directory to scan
274N/A * @return <code>true</code> if the file is added, false oth
207N/A */
207N/A @SuppressWarnings("PMD.UseStringBufferForStringAppends")
207N/A public boolean addDirectory(String dir) {
207N/A String directory = dir;
207N/A if (directory.startsWith("\\")) {
207N/A directory = directory.replace('\\', '/');
508N/A } else if (directory.charAt(0) != '/') {
207N/A directory = "/" + directory;
207N/A }
359N/A File file = new File(RuntimeEnvironment.getInstance().getSourceRootFile(), directory);
359N/A if (file.exists()) {
359N/A directories.add(directory);
207N/A return true;
207N/A } else {
359N/A return false;
253N/A }
253N/A }
253N/A
207N/A /**
207N/A * Update the content of this index database
207N/A * @throws IOException if an error occurs
207N/A * @throws HistoryException if an error occurs when accessing the history
207N/A */
270N/A public void update() throws IOException, HistoryException {
270N/A synchronized (lock) {
459N/A if (running) {
270N/A throw new IOException("Indexer already running!");
312N/A }
564N/A running = true;
270N/A interrupted = false;
270N/A }
270N/A
564N/A String ctgs = RuntimeEnvironment.getInstance().getCtags();
270N/A if (ctgs != null) {
270N/A ctags = new Ctags();
564N/A ctags.setBinary(ctgs);
564N/A }
564N/A if (ctags == null) {
564N/A log.severe("Unable to run ctags! searching definitions will not work!");
564N/A }
359N/A
270N/A try {
270N/A //TODO we might need to add writer.commit after certain phases of index generation, right now it will only happen in the end
270N/A writer = new IndexWriter(indexDirectory, AnalyzerGuru.getAnalyzer(),IndexWriter.MaxFieldLength.UNLIMITED);
270N/A writer.setMaxFieldLength(RuntimeEnvironment.getInstance().getIndexWordLimit());
270N/A
459N/A if (directories.isEmpty()) {
320N/A if (project == null) {
270N/A directories.add("");
270N/A } else {
270N/A directories.add(project.getPath());
270N/A }
270N/A }
270N/A
270N/A for (String dir : directories) {
270N/A File sourceRoot;
207N/A if ("".equals(dir)) {
207N/A sourceRoot = RuntimeEnvironment.getInstance().getSourceRootFile();
207N/A } else {
359N/A sourceRoot = new File(RuntimeEnvironment.getInstance().getSourceRootFile(), dir);
359N/A }
359N/A
359N/A HistoryGuru.getInstance().ensureHistoryCacheExists(sourceRoot);
359N/A
359N/A String startuid = Util.uid(dir, "");
359N/A IndexReader reader = IndexReader.open(indexDirectory); // open existing index
207N/A try {
207N/A uidIter = reader.terms(new Term("u", startuid)); // init uid iterator
207N/A
320N/A indexDown(sourceRoot, dir);
207N/A
207N/A while (uidIter.term() != null && uidIter.term().field().equals("u") && uidIter.term().text().startsWith(startuid)) {
207N/A removeFile();
207N/A uidIter.next();
320N/A }
207N/A } finally {
359N/A reader.close();
460N/A }
460N/A }
460N/A } finally {
359N/A if (writer != null) {
359N/A try {
359N/A writer.close();
207N/A } catch (IOException e) {
320N/A log.log(Level.WARNING, "An error occured while closing writer", e);
207N/A }
207N/A }
207N/A
207N/A if (ctags != null) {
207N/A try {
508N/A ctags.close();
207N/A } catch (IOException e) {
207N/A log.log(Level.WARNING, "An error occured while closing ctags process", e);
359N/A }
359N/A }
359N/A
207N/A synchronized (lock) {
207N/A running = false;
207N/A }
207N/A }
207N/A
207N/A if (!isInterrupted() && isDirty()) {
207N/A if (RuntimeEnvironment.getInstance().isOptimizeDatabase()) {
207N/A optimize();
207N/A }
207N/A createSpellingSuggestions();
207N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
207N/A File timestamp = new File(env.getDataRootFile(), "timestamp");
320N/A if (timestamp.exists()) {
207N/A if (!timestamp.setLastModified(System.currentTimeMillis())) {
207N/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()) {
320N/A log.warning("Failed to create file '" + timestamp.getAbsolutePath() + "', used for timestamping the index database.");
207N/A }
207N/A }
320N/A }
207N/A }
207N/A
207N/A /**
207N/A * Optimize all index databases
207N/A * @param executor An executor to run the job
508N/A * @throws IOException if an error occurs
207N/A */
207N/A static void optimizeAll(ExecutorService executor) throws IOException {
207N/A List<IndexDatabase> dbs = new ArrayList<IndexDatabase>();
207N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
207N/A if (env.hasProjects()) {
207N/A for (Project project : env.getProjects()) {
207N/A dbs.add(new IndexDatabase(project));
207N/A }
359N/A } else {
359N/A dbs.add(new IndexDatabase());
359N/A }
359N/A
359N/A for (IndexDatabase d : dbs) {
359N/A final IndexDatabase db = d;
359N/A if (db.isDirty()) {
359N/A executor.submit(new Runnable() {
359N/A
460N/A public void run() {
460N/A try {
460N/A db.update();
359N/A } catch (Exception e) {
359N/A log.log(Level.FINE,"Problem updating lucene index database: ",e);
359N/A }
359N/A }
359N/A });
253N/A }
253N/A }
253N/A }
207N/A
207N/A /**
207N/A * Optimize the index database
207N/A */
207N/A public void optimize() {
207N/A synchronized (lock) {
207N/A if (running) {
207N/A log.warning("Optimize terminated... Someone else is updating / optimizing it!");
207N/A return ;
207N/A }
207N/A running = true;
207N/A }
207N/A IndexWriter wrt = null;
515N/A try {
515N/A if (RuntimeEnvironment.getInstance().isVerbose()) {
515N/A log.info("Optimizing the index ... ");
515N/A }
515N/A wrt = new IndexWriter(indexDirectory, null, false,IndexWriter.MaxFieldLength.UNLIMITED);
515N/A wrt.optimize();
359N/A if (RuntimeEnvironment.getInstance().isVerbose()) {
359N/A log.info("done");
359N/A }
359N/A synchronized (lock) {
359N/A if (dirtyFile.exists() && !dirtyFile.delete()) {
359N/A log.fine("Failed to remove \"dirty-file\": " +
359N/A dirtyFile.getAbsolutePath());
506N/A }
506N/A dirty = false;
506N/A }
506N/A } catch (IOException e) {
359N/A log.severe("ERROR: optimizing index: " + e);
253N/A } finally {
207N/A if (wrt != null) {
207N/A try {
207N/A wrt.close();
207N/A } catch (IOException e) {
207N/A log.log(Level.WARNING, "An error occured while closing writer", e);
207N/A }
207N/A }
207N/A synchronized (lock) {
207N/A running = false;
212N/A }
553N/A }
212N/A }
553N/A
553N/A /**
553N/A * Generate a spelling suggestion for the definitions stored in defs
207N/A */
553N/A public void createSpellingSuggestions() {
553N/A IndexReader indexReader = null;
553N/A SpellChecker checker = null;
207N/A
553N/A try {
553N/A if (RuntimeEnvironment.getInstance().isVerbose()) {
553N/A log.info("Generating spelling suggestion index ... ");
553N/A }
553N/A indexReader = IndexReader.open(indexDirectory);
553N/A checker = new SpellChecker(spellDirectory);
553N/A //TODO below seems only to index "defs" , possible bug ?
553N/A checker.indexDictionary(new LuceneDictionary(indexReader, "defs"));
553N/A if (RuntimeEnvironment.getInstance().isVerbose()) {
553N/A log.info("done");
553N/A }
553N/A } catch (IOException e) {
553N/A log.severe("ERROR: Generating spelling: " + e);
553N/A } finally {
553N/A if (indexReader != null) {
553N/A try {
506N/A indexReader.close();
553N/A } catch (IOException e) {
207N/A log.log(Level.WARNING, "An error occured while closing reader", e);
553N/A }
553N/A }
553N/A if (spellDirectory != null) {
553N/A spellDirectory.close();
508N/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
207N/A private void setDirty() {
207N/A synchronized (lock) {
207N/A try {
207N/A if (!dirty && !dirtyFile.createNewFile()) {
320N/A if (!dirtyFile.exists()) {
207N/A log.log(Level.FINE,
207N/A "Failed to create \"dirty-file\": {0}",
207N/A dirtyFile.getAbsolutePath());
207N/A }
207N/A dirty = true;
310N/A }
310N/A } catch (IOException e) {
310N/A log.log(Level.FINE,"When creating dirty file: ",e);
310N/A }
310N/A }
320N/A }
310N/A /**
310N/A * Remove a stale file (uidIter.term().text()) from the index database
310N/A * (and the xref file)
207N/A * @throws java.io.IOException if an error occurs
207N/A */
320N/A private void removeFile() throws IOException {
320N/A String path = Util.uid2url(uidIter.term().text());
207N/A
207N/A for (IndexChangedListener listener : listeners) {
504N/A listener.fileRemoved(path);
504N/A }
504N/A writer.deleteDocuments(uidIter.term());
480N/A
480N/A File xrefFile;
504N/A if (RuntimeEnvironment.getInstance().isCompressXref()) {
504N/A xrefFile = new File(xrefDir, path + ".gz");
504N/A } else {
504N/A xrefFile = new File(xrefDir, path);
504N/A }
504N/A File parent = xrefFile.getParentFile();
504N/A
207N/A if (!xrefFile.delete() && xrefFile.exists()) {
207N/A log.info("Failed to remove obsolete xref-file: " +
207N/A xrefFile.getAbsolutePath());
207N/A }
207N/A
207N/A // Remove the parent directory if it's empty
207N/A if (parent.delete()) {
207N/A log.fine("Removed empty xref dir:" + parent.getAbsolutePath());
359N/A }
207N/A
207N/A setDirty();
207N/A }
207N/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
320N/A */
207N/A private void addFile(File file, String path) throws IOException {
207N/A final InputStream in =
282N/A new BufferedInputStream(new FileInputStream(file));
282N/A try {
282N/A FileAnalyzer fa = AnalyzerGuru.getAnalyzer(in, path);
282N/A fa.setCtags(ctags);
282N/A fa.setProject(Project.getProject(path));
282N/A
207N/A Document d;
207N/A try {
207N/A d = analyzerGuru.getDocument(file, in, path, fa);
207N/A } catch (Exception e) {
207N/A log.log(Level.INFO,
207N/A "Skipped file ''{0}'' because the analyzer didn''t " +
207N/A "understand it.",
460N/A path);
460N/A log.log(Level.FINE, "Exception from analyzer:", e);
460N/A return;
207N/A }
207N/A
207N/A writer.addDocument(d, fa);
207N/A Genre g = fa.getFactory().getGenre();
207N/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 }
207N/A fa.writeXref(xrefDir, path);
207N/A }
207N/A setDirty();
207N/A for (IndexChangedListener listener : listeners) {
207N/A listener.fileAdded(path, fa.getClass().getSimpleName());
207N/A }
207N/A } finally {
207N/A in.close();
207N/A }
207N/A }
207N/A
359N/A /**
359N/A * Check if I should accept this file into the index database
359N/A * @param file the file to check
359N/A * @return true if the file should be included, false otherwise
359N/A */
359N/A private boolean accept(File file) {
359N/A if (ignoredNames.ignore(file)) {
359N/A return false;
359N/A }
207N/A
207N/A if (!file.canRead()) {
207N/A log.warning("Warning: could not read " + file.getAbsolutePath());
207N/A return false;
207N/A }
207N/A
207N/A try {
207N/A if (!file.getAbsolutePath().equals(file.getCanonicalPath())) {
316N/A if (file.getParentFile().equals(file.getCanonicalFile().getParentFile())) {
207N/A // Lets support symlinks within the same directory, this
207N/A // should probably be extended to within the same repository
207N/A return true;
207N/A } else {
207N/A log.warning("Warning: ignored non-local symlink " + file.getAbsolutePath() +
207N/A " -> " + file.getCanonicalPath());
207N/A return false;
207N/A }
207N/A }
316N/A //below will only let go files and directories, anything else is considered special and is not added
207N/A if (!file.isFile() && !file.isDirectory()) {
207N/A log.warning("Warning: ignored special file " + file.getAbsolutePath());
207N/A return false;
207N/A }
207N/A } catch (IOException exp) {
359N/A log.warning("Warning: Failed to resolve name: " + file.getAbsolutePath());
207N/A log.log(Level.FINE,"Stack Trace: ",exp);
312N/A }
207N/A
207N/A if (file.isDirectory()) {
207N/A // always accept directories so that their files can be examined
207N/A return true;
207N/A }
207N/A
207N/A if (HistoryGuru.getInstance().hasHistory(file)) {
359N/A // versioned files should always be accepted
207N/A return true;
312N/A }
207N/A
460N/A // this is an unversioned file, check if it should be indexed
207N/A return !RuntimeEnvironment.getInstance().isIndexVersionedFilesOnly();
207N/A }
207N/A
207N/A /**
207N/A * Generate indexes recursively
207N/A * @param dir the root indexDirectory to generate indexes for
207N/A * @param path the path
207N/A */
207N/A private void indexDown(File dir, String parent) throws IOException {
320N/A if (isInterrupted()) {
207N/A return;
207N/A }
207N/A
207N/A if (!accept(dir)) {
207N/A return;
207N/A }
460N/A
460N/A File[] files = dir.listFiles();
460N/A if (files == null) {
207N/A log.severe("Failed to get file listing for: " + dir.getAbsolutePath());
207N/A return;
207N/A }
207N/A Arrays.sort(files, new Comparator<File>() {
207N/A
207N/A public int compare(File p1, File p2) {
359N/A return p1.getName().compareTo(p2.getName());
207N/A }
312N/A });
207N/A
207N/A for (File file : files) {
207N/A if (accept(file)) {
207N/A String path = parent + '/' + file.getName();
207N/A if (file.isDirectory()) {
207N/A indexDown(file, path);
207N/A } else {
320N/A if (uidIter != null) {
207N/A String uid = Util.uid(path, DateTools.timeToString(file.lastModified(), DateTools.Resolution.MILLISECOND)); // construct uid for doc
207N/A while (uidIter.term() != null && uidIter.term().field().equals("u") &&
207N/A uidIter.term().text().compareTo(uid) < 0) {
207N/A removeFile();
207N/A uidIter.next();
207N/A }
459N/A
508N/A if (uidIter.term() != null && uidIter.term().field().equals("u") &&
207N/A uidIter.term().text().compareTo(uid) == 0) {
207N/A uidIter.next(); // keep matching docs
207N/A continue;
207N/A }
207N/A }
207N/A try {
459N/A addFile(file, path);
508N/A } catch (Exception e) {
207N/A log.log(Level.WARNING,
207N/A "Failed to add file " + file.getAbsolutePath(),
207N/A e);
207N/A }
207N/A }
459N/A }
207N/A }
207N/A }
207N/A
457N/A /**
207N/A * Interrupt the index generation (and the index generation will stop as
207N/A * soon as possible)
207N/A */
460N/A public void interrupt() {
207N/A synchronized (lock) {
207N/A interrupted = true;
207N/A }
207N/A }
207N/A
207N/A private boolean isInterrupted() {
207N/A synchronized (lock) {
207N/A return interrupted;
207N/A }
320N/A }
207N/A
207N/A /**
207N/A * Register an object to receive events when modifications is done to the
207N/A * index database.
207N/A *
207N/A * @param listener the object to receive the events
460N/A */
460N/A public void addIndexChangedListener(IndexChangedListener listener) {
460N/A listeners.add(listener);
207N/A }
207N/A
207N/A /**
312N/A * Remove an object from the lists of objects to receive events when
207N/A * modifications is done to the index database
207N/A *
207N/A * @param listener the object to remove
207N/A */
207N/A public void removeIndexChangedListener(IndexChangedListener listener) {
207N/A listeners.remove(listener);
207N/A }
207N/A
207N/A /**
320N/A * List all files in all of the index databases
207N/A * @throws IOException if an error occurs
207N/A */
207N/A public static void listAllFiles() throws IOException {
207N/A listAllFiles(null);
207N/A }
207N/A
207N/A /**
207N/A * List all files in some of the index databases
207N/A * @param subFiles Subdirectories for the various projects to list the files
207N/A * for (or null or an empty list to dump all projects)
459N/A * @throws IOException if an error occurs
508N/A */
207N/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()) {
207N/A for (Project project : env.getProjects()) {
207N/A IndexDatabase db = new IndexDatabase(project);
459N/A db.listFiles();
508N/A }
207N/A } else {
207N/A for (String path : subFiles) {
207N/A Project project = Project.getProject(path);
207N/A if (project == null) {
208N/A log.warning("Warning: Could not find a project for \"" + path + "\"");
208N/A } else {
208N/A IndexDatabase db = new IndexDatabase(project);
208N/A db.listFiles();
208N/A }
208N/A }
208N/A }
208N/A } else {
208N/A IndexDatabase db = new IndexDatabase();
208N/A db.listFiles();
208N/A }
208N/A }
208N/A
208N/A /**
208N/A * List all of the files in this index database
460N/A *
460N/A * @throws IOException If an IO error occurs while reading from the database
460N/A */
208N/A public void listFiles() throws IOException {
208N/A IndexReader ireader = null;
208N/A TermEnum iter = null;
208N/A
208N/A try {
208N/A ireader = IndexReader.open(indexDirectory); // open existing index
208N/A iter = ireader.terms(new Term("u", "")); // init uid iterator
208N/A while (iter.term() != null) {
320N/A log.info(Util.uid2url(iter.term().text()));
320N/A iter.next();
208N/A }
208N/A } finally {
208N/A if (iter != null) {
208N/A try {
208N/A iter.close();
274N/A } catch (IOException e) {
274N/A log.log(Level.WARNING, "An error occured while closing index iterator", e);
274N/A }
274N/A }
274N/A
274N/A if (ireader != null) {
274N/A try {
274N/A ireader.close();
274N/A } catch (IOException e) {
274N/A log.log(Level.WARNING, "An error occured while closing index reader", e);
274N/A }
274N/A }
274N/A }
274N/A }
274N/A
274N/A static void listFrequentTokens() throws IOException {
274N/A listFrequentTokens(null);
274N/A }
274N/A
460N/A static void listFrequentTokens(List<String> subFiles) throws IOException {
274N/A final int limit = 4;
274N/A
274N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
207N/A if (env.hasProjects()) {
if (subFiles == null || subFiles.isEmpty()) {
for (Project project : env.getProjects()) {
IndexDatabase db = new IndexDatabase(project);
db.listTokens(4);
}
} else {
for (String path : subFiles) {
Project project = Project.getProject(path);
if (project == null) {
log.warning("Warning: Could not find a project for \"" + path + "\"");
} else {
IndexDatabase db = new IndexDatabase(project);
db.listTokens(4);
}
}
}
} else {
IndexDatabase db = new IndexDatabase();
db.listTokens(limit);
}
}
public void listTokens(int freq) throws IOException {
IndexReader ireader = null;
TermEnum iter = null;
try {
ireader = IndexReader.open(indexDirectory);
iter = ireader.terms(new Term("defs", ""));
while (iter.term() != null) {
if (iter.term().field().startsWith("f")) {
if (iter.docFreq() > 16 && iter.term().text().length() > freq) {
log.warning(iter.term().text());
}
iter.next();
} else {
break;
}
}
} finally {
if (iter != null) {
try {
iter.close();
} catch (IOException e) {
log.log(Level.WARNING, "An error occured while closing index iterator", e);
}
}
if (ireader != null) {
try {
ireader.close();
} catch (IOException e) {
log.log(Level.WARNING, "An error occured while closing index reader", e);
}
}
}
}
/**
* Get an indexReader for the Index database where a given file
* @param path the file to get the database for
* @return The index database where the file should be located or null if
* it cannot be located.
*/
public static IndexReader getIndexReader(String path) {
IndexReader ret = null;
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
File indexDir = new File(env.getDataRootFile(), "index");
if (env.hasProjects()) {
Project p = Project.getProject(path);
if (p == null) {
return null;
} else {
indexDir = new File(indexDir, p.getPath());
}
}
if (indexDir.exists() && IndexReader.indexExists(indexDir)) {
try {
ret = IndexReader.open(indexDir);
} catch (Exception ex) {
log.severe("Failed to open index: " + indexDir.getAbsolutePath());
log.log(Level.FINE,"Stack Trace: ",ex);
}
}
return ret;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final IndexDatabase other = (IndexDatabase) obj;
if (this.project != other.project && (this.project == null || !this.project.equals(other.project))) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 41 * hash + (this.project == null ? 0 : this.project.hashCode());
return hash;
}
}