IndexDatabase.java revision 694
0N/A/*
0N/A * CDDL HEADER START
0N/A *
0N/A * The contents of this file are subject to the terms of the
407N/A * Common Development and Distribution License (the "License").
0N/A * You may not use this file except in compliance with the License.
0N/A *
0N/A * See LICENSE.txt included in this distribution for the specific
0N/A * language governing permissions and limitations under the License.
0N/A *
0N/A * When distributing Covered Code, include this CDDL HEADER in each
0N/A * file and include the License file at LICENSE.txt.
0N/A * If applicable, add the following below this CDDL HEADER, with the
0N/A * fields enclosed by brackets "[]" replaced with your own identifying
0N/A * information: Portions Copyright [yyyy] [name of copyright owner]
0N/A *
0N/A * CDDL HEADER END
0N/A */
1220N/A
0N/A/*
1229N/A * Copyright 2008 Sun Microsystems, Inc. All rights reserved.
1185N/A * Use is subject to license terms.
0N/A */
0N/Apackage org.opensolaris.opengrok.index;
0N/A
1185N/Aimport java.io.BufferedInputStream;
1185N/Aimport java.io.File;
1185N/Aimport java.io.FileInputStream;
154N/Aimport java.io.FileNotFoundException;
1185N/Aimport java.io.IOException;
1185N/Aimport java.io.InputStream;
159N/Aimport java.util.ArrayList;
154N/Aimport java.util.Arrays;
292N/Aimport java.util.Comparator;
292N/Aimport java.util.List;
159N/Aimport java.util.concurrent.ExecutorService;
154N/Aimport java.util.logging.Level;
154N/Aimport java.util.logging.Logger;
1124N/Aimport org.apache.lucene.document.DateTools;
1185N/Aimport org.apache.lucene.document.Document;
434N/Aimport org.apache.lucene.index.IndexReader;
1219N/Aimport org.apache.lucene.index.IndexWriter;
1185N/Aimport org.apache.lucene.index.Term;
1185N/Aimport org.apache.lucene.index.TermEnum;
1185N/Aimport org.apache.lucene.search.spell.LuceneDictionary;
434N/Aimport org.apache.lucene.search.spell.SpellChecker;
259N/Aimport org.apache.lucene.store.FSDirectory;
89N/Aimport org.opensolaris.opengrok.analysis.AnalyzerGuru;
1124N/Aimport org.opensolaris.opengrok.analysis.Ctags;
1124N/Aimport org.opensolaris.opengrok.analysis.FileAnalyzer;
1195N/Aimport org.opensolaris.opengrok.analysis.FileAnalyzer.Genre;
0N/Aimport org.opensolaris.opengrok.configuration.Project;
0N/Aimport org.opensolaris.opengrok.configuration.RuntimeEnvironment;
1185N/Aimport org.opensolaris.opengrok.history.HistoryException;
0N/Aimport org.opensolaris.opengrok.history.HistoryGuru;
456N/Aimport org.opensolaris.opengrok.web.Util;
1185N/A
1185N/A/**
1185N/A * This class is used to create / update the index databases. Currently we use
1185N/A * one index database per project.
92N/A *
92N/A * @author Trond Norbye
1190N/A */
1185N/Apublic class IndexDatabase {
1185N/A
92N/A private Project project;
92N/A private FSDirectory indexDirectory;
345N/A private FSDirectory spellDirectory;
0N/A private IndexWriter writer;
345N/A private TermEnum uidIter;
0N/A private IgnoredNames ignoredNames;
0N/A private AnalyzerGuru analyzerGuru;
92N/A private File xrefDir;
92N/A private boolean interrupted;
1185N/A private List<IndexChangedListener> listeners;
1185N/A private File dirtyFile;
1190N/A private final Object lock = new Object();
1185N/A private boolean dirty;
1185N/A private boolean running;
92N/A private List<String> directories;
1185N/A private static final Logger log = Logger.getLogger(IndexDatabase.class.getName());
1185N/A private Ctags ctags;
1185N/A
1185N/A /**
1185N/A * Create a new instance of the Index Database. Use this constructor if
1185N/A * you don't use any projects
1185N/A *
1185N/A * @throws java.io.IOException if an error occurs while creating directories
1185N/A */
1190N/A public IndexDatabase() throws IOException {
1185N/A initialize();
1185N/A }
1185N/A
1185N/A /**
1185N/A * Create a new instance of an Index Database for a given project
1205N/A * @param project the project to create the database for
1185N/A * @throws java.io.IOException if an errror occurs while creating directories
1205N/A */
1185N/A public IndexDatabase(Project project) throws IOException {
1205N/A this.project = project;
1185N/A initialize();
0N/A }
0N/A
92N/A /**
92N/A * Update the index database for all of the projects. Print progress to
1190N/A * standard out.
1185N/A * @param executor An executor to run the job
1190N/A * @throws IOException if an error occurs
1185N/A */
1185N/A public static void updateAll(ExecutorService executor) throws IOException {
92N/A updateAll(executor, null);
1205N/A }
1185N/A
1185N/A /**
1185N/A * Update the index database for all of the projects
1185N/A * @param executor An executor to run the job
1185N/A * @param listener where to signal the changes to the database
1185N/A * @throws IOException if an error occurs
1185N/A */
1185N/A static void updateAll(ExecutorService executor, IndexChangedListener listener) throws IOException {
1185N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
1185N/A List<IndexDatabase> dbs = new ArrayList<IndexDatabase>();
1185N/A
1185N/A if (env.hasProjects()) {
1185N/A for (Project project : env.getProjects()) {
1185N/A dbs.add(new IndexDatabase(project));
1185N/A }
92N/A } else {
92N/A dbs.add(new IndexDatabase());
92N/A }
1185N/A
1185N/A for (IndexDatabase d : dbs) {
92N/A final IndexDatabase db = d;
1185N/A if (listener != null) {
1185N/A db.addIndexChangedListener(listener);
1185N/A }
1190N/A
990N/A executor.submit(new Runnable() {
990N/A
990N/A public void run() {
990N/A try {
990N/A db.update();
990N/A } catch (Exception e) {
604N/A log.log(Level.FINE,"Problem updating lucene index database: ",e);
1185N/A }
1185N/A }
1185N/A });
1185N/A }
1190N/A }
604N/A
604N/A /**
1185N/A * Update the index database for a number of sub-directories
1185N/A * @param executor An executor to run the job
0N/A * @param listener where to signal the changes to the database
154N/A * @param paths
583N/A * @throws IOException if an error occurs
583N/A */
583N/A public static void update(ExecutorService executor, IndexChangedListener listener, List<String> paths) throws IOException {
583N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
604N/A List<IndexDatabase> dbs = new ArrayList<IndexDatabase>();
604N/A
1205N/A for (String path : paths) {
1185N/A Project project = Project.getProject(path);
1190N/A if (project == null && env.hasProjects()) {
1185N/A log.warning("Could not find a project for \"" + path + "\"");
1185N/A } else {
1185N/A IndexDatabase db;
1190N/A
1185N/A try {
1185N/A if (project == null) {
604N/A db = new IndexDatabase();
1185N/A } else {
1185N/A db = new IndexDatabase(project);
1185N/A }
1185N/A
1185N/A int idx = dbs.indexOf(db);
1185N/A if (idx != -1) {
1205N/A db = dbs.get(idx);
1185N/A }
1190N/A
1185N/A if (db.addDirectory(path)) {
1185N/A if (idx == -1) {
1185N/A dbs.add(db);
1185N/A }
1185N/A } else {
1190N/A log.warning("Directory does not exist \"" + path + "\"");
1190N/A }
1185N/A } catch (IOException e) {
1185N/A log.log(Level.WARNING, "An error occured while updating index", e);
1185N/A
1185N/A }
1185N/A }
1185N/A
1185N/A for (final IndexDatabase db : dbs) {
1185N/A db.addIndexChangedListener(listener);
1185N/A executor.submit(new Runnable() {
1185N/A
1185N/A public void run() {
1185N/A try {
1185N/A db.update();
604N/A } catch (Exception e) {
604N/A log.log(Level.WARNING, "An error occured while updating index", e);
604N/A }
604N/A }
1185N/A });
1185N/A }
1185N/A }
1185N/A }
1185N/A
1185N/A @SuppressWarnings("PMD.CollapsibleIfStatements")
1190N/A private void initialize() throws IOException {
1185N/A synchronized (this) {
1185N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
1185N/A File indexDir = new File(env.getDataRootFile(), "index");
1185N/A File spellDir = new File(env.getDataRootFile(), "spellIndex");
1185N/A if (project != null) {
1185N/A indexDir = new File(indexDir, project.getPath());
1185N/A spellDir = new File(spellDir, project.getPath());
1185N/A }
1185N/A
1185N/A if (!indexDir.exists() && !indexDir.mkdirs()) {
1185N/A // to avoid race conditions, just recheck..
1185N/A if (!indexDir.exists()) {
1185N/A throw new FileNotFoundException("Failed to create root directory [" + indexDir.getAbsolutePath() + "]");
1185N/A }
1185N/A }
1190N/A
1185N/A if (!spellDir.exists() && !spellDir.mkdirs()) {
604N/A if (!spellDir.exists()) {
1185N/A throw new FileNotFoundException("Failed to create root directory [" + spellDir.getAbsolutePath() + "]");
1185N/A }
1185N/A }
1185N/A
1185N/A if (!env.isUsingLuceneLocking()) {
1185N/A FSDirectory.setDisableLocks(true);
1185N/A }
1185N/A indexDirectory = FSDirectory.getDirectory(indexDir);
1185N/A spellDirectory = FSDirectory.getDirectory(spellDir);
1185N/A ignoredNames = env.getIgnoredNames();
1206N/A analyzerGuru = new AnalyzerGuru();
1206N/A if (env.isGenerateHtml()) {
1185N/A xrefDir = new File(env.getDataRootFile(), "xref");
1185N/A }
1185N/A listeners = new ArrayList<IndexChangedListener>();
1185N/A dirtyFile = new File(indexDir, "dirty");
1205N/A dirty = dirtyFile.exists();
1185N/A directories = new ArrayList<String>();
1185N/A }
1185N/A }
1185N/A
604N/A /**
1185N/A * By default the indexer will traverse all directories in the project.
1185N/A * If you add directories with this function update will just process
1185N/A * the specified directories.
1185N/A *
1185N/A * @param dir The directory to scan
1205N/A * @return <code>true</code> if the file is added, false oth
1205N/A */
1185N/A @SuppressWarnings("PMD.UseStringBufferForStringAppends")
1185N/A public boolean addDirectory(String dir) {
1185N/A String directory = dir;
1185N/A if (directory.startsWith("\\")) {
1185N/A directory = directory.replace('\\', '/');
1185N/A } else if (directory.charAt(0) != '/') {
604N/A directory = "/" + directory;
604N/A }
604N/A File file = new File(RuntimeEnvironment.getInstance().getSourceRootFile(), directory);
1190N/A if (file.exists()) {
1190N/A directories.add(directory);
1185N/A return true;
1190N/A } else {
1190N/A return false;
1185N/A }
1185N/A }
1185N/A
1185N/A /**
1190N/A * Update the content of this index database
1190N/A * @throws IOException if an error occurs
1190N/A * @throws HistoryException if an error occurs when accessing the history
1190N/A */
1190N/A public void update() throws IOException, HistoryException {
1185N/A synchronized (lock) {
1185N/A if (running) {
1185N/A throw new IOException("Indexer already running!");
1185N/A }
604N/A running = true;
1185N/A interrupted = false;
1185N/A }
1185N/A
1185N/A String ctgs = RuntimeEnvironment.getInstance().getCtags();
1185N/A if (ctgs != null) {
1185N/A ctags = new Ctags();
1185N/A ctags.setBinary(ctgs);
604N/A }
1185N/A if (ctags == null) {
1185N/A log.severe("Unable to run ctags! searching definitions will not work!");
1185N/A }
1185N/A
0N/A try {
1185N/A writer = new IndexWriter(indexDirectory, AnalyzerGuru.getAnalyzer());
1190N/A writer.setMaxFieldLength(RuntimeEnvironment.getInstance().getIndexWordLimit());
1185N/A
1185N/A if (directories.isEmpty()) {
1185N/A if (project == null) {
1185N/A directories.add("");
1185N/A } else {
604N/A directories.add(project.getPath());
604N/A }
604N/A }
1185N/A
1185N/A for (String dir : directories) {
1185N/A File sourceRoot;
1190N/A if ("".equals(dir)) {
1185N/A sourceRoot = RuntimeEnvironment.getInstance().getSourceRootFile();
1185N/A } else {
1185N/A sourceRoot = new File(RuntimeEnvironment.getInstance().getSourceRootFile(), dir);
1185N/A }
1185N/A
604N/A HistoryGuru.getInstance().ensureHistoryCacheExists(sourceRoot);
1185N/A
1185N/A String startuid = Util.uid(dir, "");
1185N/A IndexReader reader = IndexReader.open(indexDirectory); // open existing index
1185N/A try {
1185N/A uidIter = reader.terms(new Term("u", startuid)); // init uid iterator
1185N/A
1185N/A indexDown(sourceRoot, dir);
1185N/A
1185N/A while (uidIter.term() != null && uidIter.term().field().equals("u") && uidIter.term().text().startsWith(startuid)) {
1185N/A removeFile();
1185N/A uidIter.next();
1185N/A }
1185N/A } finally {
605N/A reader.close();
1185N/A }
1185N/A }
1185N/A } finally {
1185N/A if (writer != null) {
605N/A try {
605N/A writer.close();
1185N/A } catch (IOException e) {
605N/A log.log(Level.WARNING, "An error occured while closing writer", e);
605N/A }
1185N/A }
1185N/A
604N/A if (ctags != null) {
604N/A try {
604N/A ctags.close();
1185N/A } catch (IOException e) {
1185N/A log.log(Level.WARNING, "An error occured while closing ctags process", e);
1190N/A }
1185N/A }
1185N/A
604N/A synchronized (lock) {
604N/A running = false;
604N/A }
604N/A }
604N/A
1185N/A if (!isInterrupted() && isDirty()) {
1185N/A if (RuntimeEnvironment.getInstance().isOptimizeDatabase()) {
604N/A optimize();
0N/A }
604N/A createSpellingSuggestions();
604N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
0N/A File timestamp = new File(env.getDataRootFile(), "timestamp");
154N/A if (timestamp.exists()) {
1205N/A if (!timestamp.setLastModified(System.currentTimeMillis())) {
1185N/A log.warning("Failed to set last modified time on '" + timestamp.getAbsolutePath() + "', used for timestamping the index database.");
1185N/A }
1185N/A } else {
1185N/A if (!timestamp.createNewFile()) {
1185N/A log.warning("Failed to create file '" + timestamp.getAbsolutePath() + "', used for timestamping the index database.");
1185N/A }
1185N/A }
1185N/A }
1185N/A }
154N/A
1185N/A /**
154N/A * Optimize all index databases
1185N/A * @param executor An executor to run the job
0N/A * @throws IOException if an error occurs
1185N/A */
0N/A static void optimizeAll(ExecutorService executor) throws IOException {
0N/A List<IndexDatabase> dbs = new ArrayList<IndexDatabase>();
154N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
878N/A if (env.hasProjects()) {
1185N/A for (Project project : env.getProjects()) {
1185N/A dbs.add(new IndexDatabase(project));
1190N/A }
1185N/A } else {
1185N/A dbs.add(new IndexDatabase());
878N/A }
878N/A
878N/A for (IndexDatabase d : dbs) {
1205N/A final IndexDatabase db = d;
1185N/A if (db.isDirty()) {
972N/A executor.submit(new Runnable() {
972N/A
972N/A public void run() {
972N/A try {
972N/A db.update();
972N/A } catch (Exception e) {
972N/A log.log(Level.FINE,"Problem updating lucene index database: ",e);
972N/A }
972N/A }
972N/A });
972N/A }
972N/A }
972N/A }
972N/A
972N/A /**
972N/A * Optimize the index database
972N/A */
972N/A public void optimize() {
972N/A synchronized (lock) {
972N/A if (running) {
972N/A log.warning("Optimize terminated... Someone else is updating / optimizing it!");
1185N/A return ;
972N/A }
972N/A running = true;
972N/A }
972N/A IndexWriter wrt = null;
972N/A try {
972N/A if (RuntimeEnvironment.getInstance().isVerbose()) {
972N/A log.info("Optimizing the index ... ");
972N/A }
972N/A wrt = new IndexWriter(indexDirectory, null, false);
972N/A wrt.optimize();
878N/A if (RuntimeEnvironment.getInstance().isVerbose()) {
1185N/A log.info("done");
1190N/A }
1185N/A synchronized (lock) {
1190N/A if (dirtyFile.exists() && !dirtyFile.delete()) {
1185N/A log.fine("Failed to remove \"dirty-file\": " +
1185N/A dirtyFile.getAbsolutePath());
1190N/A }
1185N/A dirty = false;
1185N/A }
1185N/A } catch (IOException e) {
1185N/A log.severe("ERROR: optimizing index: " + e);
1185N/A } finally {
1185N/A if (wrt != null) {
1185N/A try {
1185N/A wrt.close();
1185N/A } catch (IOException e) {
1185N/A log.log(Level.WARNING, "An error occured while closing writer", e);
0N/A }
54N/A }
54N/A synchronized (lock) {
54N/A running = false;
583N/A }
1185N/A }
0N/A }
0N/A
847N/A /**
847N/A * Generate a spelling suggestion for the definitions stored in defs
583N/A */
0N/A public void createSpellingSuggestions() {
583N/A IndexReader indexReader = null;
89N/A SpellChecker checker = null;
89N/A
168N/A try {
1185N/A if (RuntimeEnvironment.getInstance().isVerbose()) {
168N/A log.info("Generating spelling suggestion index ... ");
1185N/A }
1185N/A indexReader = IndexReader.open(indexDirectory);
168N/A checker = new SpellChecker(spellDirectory);
850N/A checker.indexDictionary(new LuceneDictionary(indexReader, "defs"));
168N/A if (RuntimeEnvironment.getInstance().isVerbose()) {
1185N/A log.info("done");
1185N/A }
1185N/A } catch (IOException e) {
1185N/A log.severe("ERROR: Generating spelling: " + e);
878N/A } finally {
583N/A if (indexReader != null) {
168N/A try {
1185N/A indexReader.close();
1185N/A } catch (IOException e) {
1185N/A log.log(Level.WARNING, "An error occured while closing reader", e);
1185N/A }
168N/A }
583N/A if (spellDirectory != null) {
168N/A spellDirectory.close();
89N/A }
1229N/A }
1229N/A }
1229N/A
1229N/A private boolean isDirty() {
1229N/A synchronized (lock) {
1229N/A return dirty;
1229N/A }
1185N/A }
1185N/A
1185N/A private void setDirty() {
259N/A synchronized (lock) {
1185N/A try {
1185N/A if (!dirty && !dirtyFile.createNewFile()) {
1100N/A if (!dirtyFile.exists()) {
583N/A log.log(Level.FINE, "Failed to create \"dirty-file\": ", dirtyFile.getAbsolutePath());
1185N/A }
1185N/A dirty = true;
1185N/A }
583N/A } catch (IOException e) {
259N/A log.log(Level.FINE,"When creating dirty file: ",e);
1185N/A }
89N/A }
0N/A }
154N/A /**
0N/A * Remove a stale file (uidIter.term().text()) from the index database
1185N/A * (and the xref file)
1190N/A * @throws java.io.IOException if an error occurs
1190N/A */
1185N/A private void removeFile() throws IOException {
1185N/A String path = Util.uid2url(uidIter.term().text());
1185N/A
1185N/A for (IndexChangedListener listener : listeners) {
0N/A listener.fileRemoved(path);
1185N/A }
153N/A writer.deleteDocuments(uidIter.term());
0N/A
154N/A File xrefFile;
1185N/A if (RuntimeEnvironment.getInstance().isCompressXref()) {
1190N/A xrefFile = new File(xrefDir, path + ".gz");
1185N/A } else {
1185N/A xrefFile = new File(xrefDir, path);
1185N/A }
1185N/A File parent = xrefFile.getParentFile();
0N/A
1185N/A if (!xrefFile.delete() && xrefFile.exists()) {
0N/A log.info("Failed to remove obsolete xref-file: " +
0N/A xrefFile.getAbsolutePath());
154N/A }
849N/A
849N/A // Remove the parent directory if it's empty
1190N/A if (parent.delete()) {
1185N/A log.fine("Removed empty xref dir:" + parent.getAbsolutePath());
1185N/A }
849N/A
1185N/A setDirty();
849N/A }
0N/A
1185N/A /**
1185N/A * Add a file to the Lucene index (and generate a xref file)
159N/A * @param file The file to add
830N/A * @param path The path to the file (from source root)
1219N/A * @throws java.io.IOException if an error occurs
0N/A */
1185N/A private void addFile(File file, String path) throws IOException {
0N/A final InputStream in =
154N/A new BufferedInputStream(new FileInputStream(file));
1185N/A try {
1185N/A FileAnalyzer fa = AnalyzerGuru.getAnalyzer(in, path);
1185N/A fa.setCtags(ctags);
1190N/A
1185N/A Document d = analyzerGuru.getDocument(file, in, path, fa);
1185N/A if (d == null) {
1185N/A log.warning("Warning: did not add " + path);
1185N/A } else {
1185N/A writer.addDocument(d, fa);
1185N/A Genre g = fa.getFactory().getGenre();
1185N/A if (xrefDir != null && (g == Genre.PLAIN || g == Genre.XREFABLE)) {
1205N/A File xrefFile = new File(xrefDir, path);
1190N/A // If mkdirs() returns false, the failure is most likely
1185N/A // because the file already exists. But to check for the
1185N/A // file first and only add it if it doesn't exists would
1185N/A // only increase the file IO...
1185N/A if (!xrefFile.getParentFile().mkdirs()) {
1185N/A assert xrefFile.getParentFile().exists();
1190N/A }
1185N/A fa.writeXref(xrefDir, path);
1185N/A }
1185N/A setDirty();
1185N/A for (IndexChangedListener listener : listeners) {
1185N/A listener.fileAdded(path, fa.getClass().getSimpleName());
1185N/A }
1185N/A }
158N/A } finally {
292N/A in.close();
1185N/A }
1185N/A }
292N/A
1185N/A /**
1185N/A * Check if I should accept this file into the index database
158N/A * @param file the file to check
1185N/A * @return true if the file should be included, false otherwise
158N/A */
158N/A private boolean accept(File file) {
1185N/A if (ignoredNames.ignore(file)) {
1185N/A return false;
1190N/A }
1185N/A
1190N/A if (!file.canRead()) {
1185N/A log.warning("Warning: could not read " + file.getAbsolutePath());
1185N/A return false;
0N/A }
1185N/A
58N/A try {
58N/A if (!file.getAbsolutePath().equals(file.getCanonicalPath())) {
0N/A if (file.getParentFile().equals(file.getCanonicalFile().getParentFile())) {
0N/A // Lets support symlinks within the same directory, this
1185N/A // should probably be extended to within the same repository
0N/A return true;
154N/A } else {
0N/A log.warning("Warning: ignored non-local symlink " + file.getAbsolutePath() +
0N/A " -> " + file.getCanonicalPath());
0N/A return false;
0N/A }
0N/A }
0N/A } catch (IOException exp) {
0N/A log.warning("Warning: Failed to resolve name: " + file.getAbsolutePath());
1025N/A log.log(Level.FINE,"Stack Trace: ",exp);
1185N/A }
1185N/A
1185N/A if (file.isDirectory()) {
1185N/A // always accept directories so that their files can be examined
1190N/A return true;
1025N/A }
1185N/A
1185N/A if (HistoryGuru.getInstance().hasHistory(file)) {
1185N/A // versioned files should always be accepted
1185N/A return true;
1190N/A }
1185N/A
1185N/A // this is an unversioned file, check if it should be indexed
1185N/A return !RuntimeEnvironment.getInstance().isIndexVersionedFilesOnly();
1190N/A }
1025N/A
1185N/A /**
1185N/A * Generate indexes recursively
1185N/A * @param dir the root indexDirectory to generate indexes for
1185N/A * @param path the path
1185N/A */
1185N/A private void indexDown(File dir, String parent) throws IOException {
1025N/A if (isInterrupted()) {
1185N/A return;
1185N/A }
1185N/A
1185N/A if (!accept(dir)) {
1185N/A return;
1185N/A }
1185N/A
1185N/A File[] files = dir.listFiles();
1185N/A if (files == null) {
1185N/A log.severe("Failed to get file listing for: " + dir.getAbsolutePath());
1185N/A return;
1185N/A }
1025N/A Arrays.sort(files, new Comparator<File>() {
1185N/A
1185N/A public int compare(File p1, File p2) {
1185N/A return p1.getName().compareTo(p2.getName());
1185N/A }
1185N/A });
1185N/A
1185N/A for (File file : files) {
1185N/A if (accept(file)) {
1185N/A String path = parent + '/' + file.getName();
1185N/A if (file.isDirectory()) {
1185N/A indexDown(file, path);
1185N/A } else {
1185N/A if (uidIter != null) {
1185N/A String uid = Util.uid(path, DateTools.timeToString(file.lastModified(), DateTools.Resolution.MILLISECOND)); // construct uid for doc
1185N/A while (uidIter.term() != null && uidIter.term().field().equals("u") &&
1185N/A uidIter.term().text().compareTo(uid) < 0) {
1185N/A removeFile();
1185N/A uidIter.next();
1185N/A }
1185N/A
1185N/A if (uidIter.term() != null && uidIter.term().field().equals("u") &&
1185N/A uidIter.term().text().compareTo(uid) == 0) {
1185N/A uidIter.next(); // keep matching docs
1185N/A continue;
1025N/A }
1124N/A }
1124N/A try {
1124N/A addFile(file, path);
1190N/A } catch (Exception e) {
1185N/A log.log(Level.WARNING,
1185N/A "Failed to add file " + file.getAbsolutePath(),
1185N/A e);
1185N/A }
1185N/A }
1185N/A }
1124N/A }
1185N/A }
1185N/A
1185N/A /**
1185N/A * Interrupt the index generation (and the index generation will stop as
1124N/A * soon as possible)
1124N/A */
1124N/A public void interrupt() {
1124N/A synchronized (lock) {
1124N/A interrupted = true;
1124N/A }
1124N/A }
1124N/A
1124N/A private boolean isInterrupted() {
1124N/A synchronized (lock) {
1124N/A return interrupted;
1124N/A }
1124N/A }
1124N/A
1124N/A /**
1124N/A * Register an object to receive events when modifications is done to the
1124N/A * index database.
1185N/A *
1185N/A * @param listener the object to receive the events
1185N/A */
1124N/A public void addIndexChangedListener(IndexChangedListener listener) {
1124N/A listeners.add(listener);
1124N/A }
1124N/A
1185N/A /**
1190N/A * Remove an object from the lists of objects to receive events when
1185N/A * modifications is done to the index database
1185N/A *
1185N/A * @param listener the object to remove
1185N/A */
1185N/A public void removeIndexChangedListener(IndexChangedListener listener) {
1205N/A listeners.remove(listener);
1185N/A }
1185N/A
1185N/A /**
1185N/A * List all files in all of the index databases
1185N/A * @throws IOException if an error occurs
1185N/A */
1185N/A public static void listAllFiles() throws IOException {
1185N/A listAllFiles(null);
1185N/A }
1190N/A
1185N/A /**
1190N/A * List all files in some of the index databases
1185N/A * @param subFiles Subdirectories for the various projects to list the files
1190N/A * for (or null or an empty list to dump all projects)
1185N/A * @throws IOException if an error occurs
1185N/A */
1185N/A public static void listAllFiles(List<String> subFiles) throws IOException {
1185N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
1190N/A if (env.hasProjects()) {
1185N/A if (subFiles == null || subFiles.isEmpty()) {
1185N/A for (Project project : env.getProjects()) {
1185N/A IndexDatabase db = new IndexDatabase(project);
1190N/A db.listFiles();
1190N/A }
1185N/A } else {
1185N/A for (String path : subFiles) {
1185N/A Project project = Project.getProject(path);
1185N/A if (project == null) {
1185N/A log.warning("Warning: Could not find a project for \"" + path + "\"");
1190N/A } else {
1185N/A IndexDatabase db = new IndexDatabase(project);
1190N/A db.listFiles();
1185N/A }
1185N/A }
1185N/A }
1190N/A } else {
1185N/A IndexDatabase db = new IndexDatabase();
1185N/A db.listFiles();
1185N/A }
1185N/A }
1185N/A
1185N/A /**
1185N/A * List all of the files in this index database
1185N/A *
1185N/A * @throws IOException If an IO error occurs while reading from the database
1185N/A */
1185N/A public void listFiles() throws IOException {
1185N/A IndexReader ireader = null;
1185N/A TermEnum iter = null;
1185N/A
1185N/A try {
1185N/A ireader = IndexReader.open(indexDirectory); // open existing index
1185N/A iter = ireader.terms(new Term("u", "")); // init uid iterator
1185N/A while (iter.term() != null) {
1185N/A log.info(Util.uid2url(iter.term().text()));
1185N/A iter.next();
1185N/A }
1185N/A } finally {
1185N/A if (iter != null) {
1185N/A try {
1195N/A iter.close();
1195N/A } catch (IOException e) {
1195N/A log.log(Level.WARNING, "An error occured while closing index iterator", e);
1185N/A }
1185N/A }
1185N/A
1185N/A if (ireader != null) {
1185N/A try {
1124N/A ireader.close();
1190N/A } catch (IOException e) {
1185N/A log.log(Level.WARNING, "An error occured while closing index reader", e);
1185N/A }
1185N/A }
1185N/A }
1185N/A }
1185N/A
1124N/A static void listFrequentTokens() throws IOException {
1124N/A listFrequentTokens(null);
1185N/A }
1185N/A
1124N/A static void listFrequentTokens(List<String> subFiles) throws IOException {
1185N/A final int limit = 4;
1124N/A
1124N/A RuntimeEnvironment env = RuntimeEnvironment.getInstance();
1124N/A if (env.hasProjects()) {
1185N/A if (subFiles == null || subFiles.isEmpty()) {
1185N/A for (Project project : env.getProjects()) {
1185N/A IndexDatabase db = new IndexDatabase(project);
1124N/A db.listTokens(4);
1124N/A }
1124N/A } else {
1124N/A for (String path : subFiles) {
1124N/A Project project = Project.getProject(path);
1124N/A if (project == null) {
1124N/A log.warning("Warning: Could not find a project for \"" + path + "\"");
1190N/A } else {
1185N/A IndexDatabase db = new IndexDatabase(project);
1185N/A db.listTokens(4);
1185N/A }
1185N/A }
1185N/A }
1185N/A } else {
1124N/A IndexDatabase db = new IndexDatabase();
1185N/A db.listTokens(limit);
1185N/A }
1185N/A }
1124N/A
1185N/A public void listTokens(int freq) throws IOException {
1124N/A IndexReader ireader = null;
1124N/A TermEnum iter = null;
1185N/A
1185N/A try {
1185N/A ireader = IndexReader.open(indexDirectory);
1124N/A iter = ireader.terms(new Term("defs", ""));
1124N/A while (iter.term() != null) {
1124N/A if (iter.term().field().startsWith("f")) {
1124N/A if (iter.docFreq() > 16 && iter.term().text().length() > freq) {
1145N/A log.warning(iter.term().text());
1145N/A }
1145N/A iter.next();
1190N/A } else {
1185N/A break;
1185N/A }
1145N/A }
1145N/A } finally {
1145N/A if (iter != null) {
1145N/A try {
1145N/A iter.close();
1185N/A } catch (IOException e) {
1145N/A log.log(Level.WARNING, "An error occured while closing index iterator", e);
1145N/A }
1145N/A }
1145N/A
1145N/A if (ireader != null) {
1145N/A try {
1145N/A ireader.close();
1145N/A } catch (IOException e) {
1145N/A log.log(Level.WARNING, "An error occured while closing index reader", e);
1145N/A }
1145N/A }
1145N/A }
1145N/A }
1145N/A
1145N/A /**
1145N/A * Get an indexReader for the Index database where a given file
1145N/A * @param path the file to get the database for
1145N/A * @return The index database where the file should be located or null if
1145N/A * it cannot be located.
1145N/A */
1145N/A public static IndexReader getIndexReader(String path) {
0N/A 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;
}
}