Example usage for org.eclipse.jdt.internal.core.index Index queryDocumentNames

List of usage examples for org.eclipse.jdt.internal.core.index Index queryDocumentNames

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.core.index Index queryDocumentNames.

Prototype

public String[] queryDocumentNames(String substring) throws IOException 

Source Link

Document

Returns the document names that contain the given substring, if null then returns all of them.

Usage

From source file:com.codenvy.ide.ext.java.server.internal.core.search.indexing.AddJarFileToIndex.java

License:Open Source License

public boolean execute(IProgressMonitor progressMonitor) {

    if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled())
        return true;

    if (hasPreBuiltIndex()) {
        boolean added = this.manager.addIndex(this.containerPath, this.indexFileURL);
        if (added)
            return true;
        this.indexFileURL = null;
    }//from   w  w  w . j  ava 2 s .co m

    try {
        // if index is already cached, then do not perform any check
        // MUST reset the IndexManager if a jar file is changed
        Index index = this.manager.getIndexForUpdate(this.containerPath, false,
                /*do not reuse index file*/ false /*do not create if none*/);
        if (index != null) {
            if (JobManager.VERBOSE)
                org.eclipse.jdt.internal.core.util.Util
                        .verbose("-> no indexing required (index already exists) for " + this.containerPath); //$NON-NLS-1$
            return true;
        }

        index = this.manager.getIndexForUpdate(this.containerPath, true,
                /*reuse index file*/ true /*create if none*/);
        if (index == null) {
            if (JobManager.VERBOSE)
                org.eclipse.jdt.internal.core.util.Util
                        .verbose("-> index could not be created for " + this.containerPath); //$NON-NLS-1$
            return true;
        }
        ReadWriteMonitor monitor = index.monitor;
        if (monitor == null) {
            if (JobManager.VERBOSE)
                org.eclipse.jdt.internal.core.util.Util
                        .verbose("-> index for " + this.containerPath + " just got deleted"); //$NON-NLS-1$//$NON-NLS-2$
            return true; // index got deleted since acquired
        }
        index.separator = JAR_SEPARATOR;
        ZipFile zip = null;
        try {
            // this path will be a relative path to the workspace in case the zipfile in the workspace otherwise it will be a path in the
            // local file system
            Path zipFilePath = null;

            monitor.enterWrite(); // ask permission to write
            if (this.resource != null) {
                URI location = this.resource.getLocationURI();
                if (location == null)
                    return false;
                if (JavaModelManager.ZIP_ACCESS_VERBOSE)
                    System.out.println("(" + Thread.currentThread() //$NON-NLS-1$
                            + ") [AddJarFileToIndex.execute()] Creating ZipFile on " + location.getPath()); //$NON-NLS-1$
                File file = null;
                try {
                    file = org.eclipse.jdt.internal.core.util.Util.toLocalFile(location, progressMonitor);
                } catch (CoreException e) {
                    if (JobManager.VERBOSE) {
                        org.eclipse.jdt.internal.core.util.Util.verbose("-> failed to index " //$NON-NLS-1$
                                + location.getPath() + " because of the following exception:"); //$NON-NLS-1$
                        e.printStackTrace();
                    }
                }
                if (file == null) {
                    if (JobManager.VERBOSE)
                        org.eclipse.jdt.internal.core.util.Util.verbose("-> failed to index " //$NON-NLS-1$
                                + location.getPath() + " because the file could not be fetched"); //$NON-NLS-1$
                    return false;
                }
                zip = new ZipFile(file);
                zipFilePath = (Path) this.resource.getFullPath().makeRelative();
                // absolute path relative to the workspace
            } else {
                if (JavaModelManager.ZIP_ACCESS_VERBOSE)
                    System.out.println("(" + Thread.currentThread() //$NON-NLS-1$
                            + ") [AddJarFileToIndex.execute()] Creating ZipFile on " + this.containerPath); //$NON-NLS-1$
                // external file -> it is ok to use toFile()
                zip = new ZipFile(this.containerPath.toFile());
                zipFilePath = (Path) this.containerPath;
                // path is already canonical since coming from a library classpath entry
            }

            if (this.isCancelled) {
                if (JobManager.VERBOSE)
                    org.eclipse.jdt.internal.core.util.Util
                            .verbose("-> indexing of " + zip.getName() + " has been cancelled"); //$NON-NLS-1$ //$NON-NLS-2$
                return false;
            }

            if (JobManager.VERBOSE)
                org.eclipse.jdt.internal.core.util.Util.verbose("-> indexing " + zip.getName()); //$NON-NLS-1$
            long initialTime = System.currentTimeMillis();

            String[] paths = index.queryDocumentNames(""); // all file names //$NON-NLS-1$
            if (paths != null) {
                int max = paths.length;
                /* check integrity of the existing index file
                 * if the length is equal to 0, we want to index the whole jar again
                 * If not, then we want to check that there is no missing entry, if
                 * one entry is missing then we recreate the index
                 */
                String EXISTS = "OK"; //$NON-NLS-1$
                String DELETED = "DELETED"; //$NON-NLS-1$
                SimpleLookupTable indexedFileNames = new SimpleLookupTable(max == 0 ? 33 : max + 11);
                for (int i = 0; i < max; i++)
                    indexedFileNames.put(paths[i], DELETED);
                for (Enumeration e = zip.entries(); e.hasMoreElements();) {
                    // iterate each entry to index it
                    ZipEntry ze = (ZipEntry) e.nextElement();
                    String zipEntryName = ze.getName();
                    if (Util.isClassFileName(zipEntryName) && isValidPackageNameForClass(zipEntryName))
                        // the class file may not be there if the package name is not valid
                        indexedFileNames.put(zipEntryName, EXISTS);
                }
                boolean needToReindex = indexedFileNames.elementSize != max; // a new file was added
                if (!needToReindex) {
                    Object[] valueTable = indexedFileNames.valueTable;
                    for (int i = 0, l = valueTable.length; i < l; i++) {
                        if (valueTable[i] == DELETED) {
                            needToReindex = true; // a file was deleted so re-index
                            break;
                        }
                    }
                    if (!needToReindex) {
                        if (JobManager.VERBOSE)
                            org.eclipse.jdt.internal.core.util.Util
                                    .verbose("-> no indexing required (index is consistent with library) for " //$NON-NLS-1$
                                            + zip.getName() + " (" //$NON-NLS-1$
                                            + (System.currentTimeMillis() - initialTime) + "ms)"); //$NON-NLS-1$
                        this.manager.saveIndex(index); // to ensure its placed into the saved state
                        return true;
                    }
                }
            }

            // Index the jar for the first time or reindex the jar in case the previous index file has been corrupted
            // index already existed: recreate it so that we forget about previous entries
            SearchParticipant participant = SearchEngine.getDefaultSearchParticipant(manager);
            if (!this.manager.resetIndex(this.containerPath)) {
                // failed to recreate index, see 73330
                this.manager.removeIndex(this.containerPath);
                return false;
            }
            index.separator = JAR_SEPARATOR;
            IPath indexPath = null;
            IndexLocation indexLocation;
            if ((indexLocation = index.getIndexLocation()) != null) {
                indexPath = new Path(indexLocation.getCanonicalFilePath());
            }
            for (Enumeration e = zip.entries(); e.hasMoreElements();) {
                if (this.isCancelled) {
                    if (JobManager.VERBOSE)
                        org.eclipse.jdt.internal.core.util.Util
                                .verbose("-> indexing of " + zip.getName() + " has been cancelled"); //$NON-NLS-1$ //$NON-NLS-2$
                    return false;
                }

                // iterate each entry to index it
                ZipEntry ze = (ZipEntry) e.nextElement();
                String zipEntryName = ze.getName();
                if (Util.isClassFileName(zipEntryName) && isValidPackageNameForClass(zipEntryName)) {
                    // index only classes coming from valid packages - https://bugs.eclipse.org/bugs/show_bug.cgi?id=293861
                    final byte[] classFileBytes = org.eclipse.jdt.internal.compiler.util.Util
                            .getZipEntryByteContent(ze, zip);
                    JavaSearchDocument entryDocument = new JavaSearchDocument(ze, zipFilePath, classFileBytes,
                            participant);
                    this.manager.indexDocument(entryDocument, participant, index, indexPath);
                }
            }
            this.manager.saveIndex(index);
            if (JobManager.VERBOSE)
                org.eclipse.jdt.internal.core.util.Util.verbose("-> done indexing of " //$NON-NLS-1$
                        + zip.getName() + " (" //$NON-NLS-1$
                        + (System.currentTimeMillis() - initialTime) + "ms)"); //$NON-NLS-1$
        } finally {
            if (zip != null) {
                if (JavaModelManager.ZIP_ACCESS_VERBOSE)
                    System.out.println("(" + Thread.currentThread() //$NON-NLS-1$
                            + ") [AddJarFileToIndex.execute()] Closing ZipFile " + zip); //$NON-NLS-1$
                zip.close();
            }
            monitor.exitWrite(); // free write lock
        }
    } catch (IOException e) {
        if (JobManager.VERBOSE) {
            org.eclipse.jdt.internal.core.util.Util.verbose(
                    "-> failed to index " + this.containerPath + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$
            e.printStackTrace();
        }
        this.manager.removeIndex(this.containerPath);
        return false;
    }
    return true;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.indexing.IndexAllProject.java

License:Open Source License

/**
 * Ensure consistency of a project index. Need to walk all nested resources,
 * and discover resources which have either been changed, added or deleted
 * since the index was produced.//from   w  w w .ja va  2s .co m
 */
public boolean execute(IProgressMonitor progressMonitor) {

    if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled())
        return true;
    //      if (!this.project.isAccessible()) return true; // nothing to do

    ReadWriteMonitor monitor = null;
    try {
        // Get source folder entries. Libraries are done as a separate job
        //         JavaProject javaProject = (JavaProject)JavaCore.create(this.project);
        // Do not create marker while getting raw classpath (see bug 41859)
        IClasspathEntry[] entries = project.getRawClasspath();
        int length = entries.length;
        IClasspathEntry[] sourceEntries = new IClasspathEntry[length];
        int sourceEntriesNumber = 0;
        for (int i = 0; i < length; i++) {
            IClasspathEntry entry = entries[i];
            if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE)
                sourceEntries[sourceEntriesNumber++] = entry;
        }
        if (sourceEntriesNumber == 0) {
            IPath projectPath = project.getPath();
            for (int i = 0; i < length; i++) {
                IClasspathEntry entry = entries[i];
                if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY
                        && entry.getPath().equals(projectPath)) {
                    // the project is also a library folder (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=89815)
                    // ensure a job exists to index it as a binary folder
                    this.manager.indexLibrary(projectPath,
                            /*this.project,*/ ((ClasspathEntry) entry).getLibraryIndexLocation());
                    return true;
                }
            }

            // nothing to index but want to save an empty index file so its not 'rebuilt' when part of a search request
            Index index = this.manager.getIndexForUpdate(this.containerPath, true,
                    /*reuse index file*/ true /*create if none*/);
            if (index != null)
                this.manager.saveIndex(index);
            return true;
        }
        if (sourceEntriesNumber != length)
            System.arraycopy(sourceEntries, 0, sourceEntries = new IClasspathEntry[sourceEntriesNumber], 0,
                    sourceEntriesNumber);

        Index index = this.manager.getIndexForUpdate(this.containerPath, true,
                /*reuse index file*/ true /*create if none*/);
        if (index == null)
            return true;
        monitor = index.monitor;
        if (monitor == null)
            return true; // index got deleted since acquired

        monitor.enterRead(); // ask permission to read

        String[] paths = index.queryDocumentNames(""); // all file names //$NON-NLS-1$
        int max = paths == null ? 0 : paths.length;
        final SimpleLookupTable indexedFileNames = new SimpleLookupTable(max == 0 ? 33 : max + 11);
        final String OK = "OK"; //$NON-NLS-1$
        final String DELETED = "DELETED"; //$NON-NLS-1$
        if (paths != null) {
            for (int i = 0; i < max; i++)
                indexedFileNames.put(paths[i], DELETED);
        }
        final long indexLastModified = max == 0 ? 0L : index.getIndexLastModified();

        //         IWorkspaceRoot root = this.project.getWorkspace().getRoot();
        for (int i = 0; i < sourceEntriesNumber; i++) {
            if (this.isCancelled)
                return false;

            IClasspathEntry entry = sourceEntries[i];
            //            IResource sourceFolder = root.findMember(entry.getPath());
            Path sourceFolder = FileSystems.getDefault().getPath(entry.getPath().toOSString());
            if (sourceFolder != null) {

                // collect output locations if source is project (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=32041)
                final HashSet outputs = new HashSet();
                //TODO
                //               if (sourceFolder.getType() == IResource.PROJECT) {
                //                  // Do not create marker while getting output location (see bug 41859)
                //                  outputs.add(javaProject.getOutputLocation());
                //                  for (int j = 0; j < sourceEntriesNumber; j++) {
                //                     IPath output = sourceEntries[j].getOutputLocation();
                //                     if (output != null) {
                //                        outputs.add(output);
                //                     }
                //                  }
                //               }
                final boolean hasOutputs = !outputs.isEmpty();

                final char[][] inclusionPatterns = ((ClasspathEntry) entry).fullInclusionPatternChars();
                final char[][] exclusionPatterns = ((ClasspathEntry) entry).fullExclusionPatternChars();
                if (max == 0) {
                    Files.walkFileTree(sourceFolder, new FileVisitor<Path>() {
                        @Override
                        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                                throws IOException {
                            if (exclusionPatterns != null && inclusionPatterns == null) {
                                // if there are inclusion patterns then we must walk the children
                                if (Util.isExcluded(new org.eclipse.core.runtime.Path(dir.toFile().getPath()),
                                        inclusionPatterns, exclusionPatterns, true))
                                    return FileVisitResult.SKIP_SUBTREE;
                            }
                            if (hasOutputs && outputs.contains(dir.toAbsolutePath()))
                                return FileVisitResult.SKIP_SUBTREE;
                            return FileVisitResult.CONTINUE;
                        }

                        @Override
                        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                                throws IOException {
                            if (Util.isJavaLikeFileName(file.getFileName().toString())) {
                                //                                    IFile file = (IFile) proxy.requestResource();
                                org.eclipse.core.runtime.Path resourcePath = new org.eclipse.core.runtime.Path(
                                        file.toFile().getPath());
                                if (exclusionPatterns != null || inclusionPatterns != null) {
                                    if (Util.isExcluded(resourcePath, inclusionPatterns, exclusionPatterns,
                                            false))
                                        return FileVisitResult.CONTINUE;
                                }
                                indexedFileNames.put(resourcePath.makeRelativeTo(containerPath).toOSString(),
                                        file);
                            }
                            return FileVisitResult.CONTINUE;
                        }

                        @Override
                        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                            return FileVisitResult.CONTINUE;
                        }

                        @Override
                        public FileVisitResult postVisitDirectory(Path dir, IOException exc)
                                throws IOException {
                            return FileVisitResult.CONTINUE;
                        }
                    });
                    //                  sourceFolder.accept(
                    //                     new IResourceProxyVisitor() {
                    //                        public boolean visit(IResourceProxy proxy) {
                    //                           if (IndexAllProject.this.isCancelled) return false;
                    //                           switch(proxy.getType()) {
                    //                              case IResource.FILE :
                    //
                    //                              case IResource.FOLDER :
                    //
                    //                           }
                    //                           return true;
                    //                        }
                    //                     },
                    //                     IResource.NONE
                    //                  );
                } else {
                    Files.walkFileTree(sourceFolder, new FileVisitor<Path>() {
                        @Override
                        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                                throws IOException {
                            if (exclusionPatterns != null || inclusionPatterns != null)
                                if (Util.isExcluded(new org.eclipse.core.runtime.Path(dir.toFile().getPath()),
                                        inclusionPatterns, exclusionPatterns, true))
                                    return FileVisitResult.SKIP_SUBTREE;
                            if (hasOutputs && outputs.contains(dir.toAbsolutePath()))
                                return FileVisitResult.SKIP_SUBTREE;
                            return FileVisitResult.CONTINUE;
                        }

                        @Override
                        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                                throws IOException {
                            if (Util.isJavaLikeFileName(file.getFileName().toString())) {
                                //                                    IFile file = (IFile) proxy.requestResource();
                                URI location = file.toUri();
                                if (location == null)
                                    return FileVisitResult.CONTINUE;
                                if (exclusionPatterns != null || inclusionPatterns != null)
                                    if (Util.isExcluded(
                                            new org.eclipse.core.runtime.Path(file.toFile().getPath()),
                                            inclusionPatterns, exclusionPatterns, false))
                                        return FileVisitResult.CONTINUE;
                                String relativePathString = new org.eclipse.core.runtime.Path(
                                        file.toFile().getPath()).makeRelativeTo(containerPath).toOSString();
                                //Util.relativePath(new org.eclipse.core.runtime.Path(file.toFile().getPath()), 1/*remove project segment*/);
                                indexedFileNames.put(relativePathString, indexedFileNames
                                        .get(relativePathString) == null
                                        || indexLastModified < 0 /*EFS.getStore(location).fetchInfo().getLastModified()*/
                                                ? (Object) file
                                                : (Object) OK);
                            }
                            return FileVisitResult.CONTINUE;
                        }

                        @Override
                        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                            return FileVisitResult.CONTINUE;
                        }

                        @Override
                        public FileVisitResult postVisitDirectory(Path dir, IOException exc)
                                throws IOException {
                            return FileVisitResult.CONTINUE;
                        }
                    });
                    //                  sourceFolder.accept(
                    //                     new IResourceProxyVisitor() {
                    //                        public boolean visit(IResourceProxy proxy) throws CoreException {
                    //                           if (IndexAllProject.this.isCancelled) return false;
                    //                           switch(proxy.getType()) {
                    //                              case IResource.FILE :
                    //                                 if (Util.isJavaLikeFileName(proxy.getName())) {
                    //                                    IFile file = (IFile) proxy.requestResource();
                    //                                    URI location = file.getLocationURI();
                    //                                    if (location == null) return false;
                    //                                    if (exclusionPatterns != null || inclusionPatterns != null)
                    //                                       if (Util.isExcluded(file, inclusionPatterns, exclusionPatterns))
                    //                                          return false;
                    //                                    String relativePathString = Util
                    //                                                        .relativePath(file.getFullPath(), 1/*remove project segment*/);
                    //                                    indexedFileNames.put(relativePathString,
                    //                                       indexedFileNames.get(relativePathString) == null
                    //                                             || indexLastModified < 0 /*EFS.getStore(location).fetchInfo().getLastModified()*/
                    //                                          ? (Object) file
                    //                                          : (Object) OK);
                    //                                 }
                    //                                 return false;
                    //                              case IResource.FOLDER :
                    //                                 if (exclusionPatterns != null || inclusionPatterns != null)
                    //                                    if (Util.isExcluded(proxy.requestResource(), inclusionPatterns, exclusionPatterns))
                    //                                       return false;
                    //                                 if (hasOutputs && outputs.contains(proxy.requestFullPath()))
                    //                                    return false;
                    //                           }
                    //                           return true;
                    //                        }
                    //                     },
                    //                     IResource.NONE
                    //                  );
                }
            }
        }

        SourceElementParser parser = this.manager.getSourceElementParser(project,
                null/*requestor will be set by indexer*/);
        Object[] names = indexedFileNames.keyTable;
        Object[] values = indexedFileNames.valueTable;
        for (int i = 0, namesLength = names.length; i < namesLength; i++) {
            String name = (String) names[i];
            if (name != null) {
                if (this.isCancelled)
                    return false;

                Object value = values[i];
                if (value != OK) {
                    if (value == DELETED)
                        this.manager.remove(name, this.containerPath);
                    else
                        this.manager.addSource((Path) value, this.containerPath, parser);
                }
            }
        }

        // request to save index when all cus have been indexed... also sets state to SAVED_STATE
        this.manager.request(new SaveIndex(this.containerPath, this.manager));
    } catch (CoreException e) {
        if (JobManager.VERBOSE) {
            Util.verbose("-> failed to index " + this.project + " because of the following exception:", //$NON-NLS-1$//$NON-NLS-2$
                    System.err);
            e.printStackTrace();
        }
        this.manager.removeIndex(this.containerPath);
        return false;
    } catch (IOException e) {
        if (JobManager.VERBOSE) {
            Util.verbose("-> failed to index " + this.project + " because of the following exception:", //$NON-NLS-1$//$NON-NLS-2$
                    System.err);
            e.printStackTrace();
        }
        this.manager.removeIndex(this.containerPath);
        return false;
    } finally {
        if (monitor != null)
            monitor.exitRead(); // free read lock
    }
    return true;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.indexing.RemoveFolderFromIndex.java

License:Open Source License

public boolean execute(IProgressMonitor progressMonitor) {

    if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled())
        return true;

    /* ensure no concurrent write access to index */
    Index index = this.manager.getIndex(this.containerPath, true,
            /*reuse index file*/ false /*create if none*/);
    if (index == null)
        return true;
    ReadWriteMonitor monitor = index.monitor;
    if (monitor == null)
        return true; // index got deleted since acquired

    try {/* w ww.  java  2  s . c  o  m*/
        monitor.enterRead(); // ask permission to read
        String containerRelativePath = Util.relativePath(this.folderPath, this.containerPath.segmentCount());
        String[] paths = index.queryDocumentNames(containerRelativePath);
        // all file names belonging to the folder or its subfolders and that are not excluded (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=32607)
        if (paths != null) {
            if (this.exclusionPatterns == null && this.inclusionPatterns == null) {
                for (int i = 0, max = paths.length; i < max; i++) {
                    this.manager.remove(paths[i], this.containerPath); // write lock will be acquired by the remove operation
                }
            } else {
                for (int i = 0, max = paths.length; i < max; i++) {
                    String documentPath = this.containerPath.toString() + '/' + paths[i];
                    if (!Util.isExcluded(new Path(documentPath), this.inclusionPatterns, this.exclusionPatterns,
                            false))
                        this.manager.remove(paths[i], this.containerPath); // write lock will be acquired by the remove operation
                }
            }
        }
    } catch (IOException e) {
        if (JobManager.VERBOSE) {
            Util.verbose("-> failed to remove " + this.folderPath //$NON-NLS-1$
                    + " from index because of the following exception:", System.err); //$NON-NLS-1$
            e.printStackTrace();
        }
        return false;
    } finally {
        monitor.exitRead(); // free read lock
    }
    return true;
}

From source file:org.eclipse.che.jdt.internal.core.search.indexing.AddJarFileToIndex.java

License:Open Source License

public boolean execute(IProgressMonitor progressMonitor) {

    if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled())
        return true;

    if (hasPreBuiltIndex()) {
        boolean added = this.manager.addIndex(this.containerPath, this.indexFileURL);
        if (added)
            return true;
        this.indexFileURL = null;
    }//from w w  w .  j a v  a 2 s  .c o  m

    try {
        // if index is already cached, then do not perform any check
        // MUST reset the IndexManager if a jar file is changed
        Index index = this.manager.getIndexForUpdate(this.containerPath, false,
                /*do not reuse index file*/ false /*do not create if
                                                  none*/);
        if (index != null) {
            if (JobManager.VERBOSE)
                org.eclipse.jdt.internal.core.util.Util
                        .verbose("-> no indexing required (index already exists) for " + this.containerPath); //$NON-NLS-1$
            return true;
        }

        index = this.manager.getIndexForUpdate(this.containerPath, true,
                /*reuse index file*/ true /*create if none*/);
        if (index == null) {
            if (JobManager.VERBOSE)
                org.eclipse.jdt.internal.core.util.Util
                        .verbose("-> index could not be created for " + this.containerPath); //$NON-NLS-1$
            return true;
        }
        ReadWriteMonitor monitor = index.monitor;
        if (monitor == null) {
            if (JobManager.VERBOSE)
                org.eclipse.jdt.internal.core.util.Util
                        .verbose("-> index for " + this.containerPath + " just got deleted"); //$NON-NLS-1$//$NON-NLS-2$
            return true; // index got deleted since acquired
        }
        index.separator = JAR_SEPARATOR;
        ZipFile zip = null;
        try {
            // this path will be a relative path to the workspace in case the zipfile in the workspace otherwise it will be a path in the
            // local file system
            Path zipFilePath = null;

            monitor.enterWrite(); // ask permission to write
            if (this.resource != null) {
                URI location = this.resource.getLocationURI();
                if (location == null)
                    return false;
                if (JavaModelManager.ZIP_ACCESS_VERBOSE)
                    System.out.println("(" + Thread.currentThread() //$NON-NLS-1$
                            + ") [AddJarFileToIndex.execute()] Creating ZipFile on " + location.getPath()); //$NON-NLS-1$
                File file = null;
                try {
                    file = org.eclipse.jdt.internal.core.util.Util.toLocalFile(location, progressMonitor);
                } catch (CoreException e) {
                    if (JobManager.VERBOSE) {
                        org.eclipse.jdt.internal.core.util.Util.verbose("-> failed to index " //$NON-NLS-1$
                                + location.getPath() + " because of the following exception:"); //$NON-NLS-1$
                        e.printStackTrace();
                    }
                }
                if (file == null) {
                    if (JobManager.VERBOSE)
                        org.eclipse.jdt.internal.core.util.Util.verbose("-> failed to index " //$NON-NLS-1$
                                + location.getPath() + " because the file could not be fetched"); //$NON-NLS-1$
                    return false;
                }
                zip = new ZipFile(file);
                zipFilePath = (Path) this.resource.getFullPath().makeRelative();
                // absolute path relative to the workspace
            } else {
                if (JavaModelManager.ZIP_ACCESS_VERBOSE)
                    System.out.println("(" + Thread.currentThread() //$NON-NLS-1$
                            + ") [AddJarFileToIndex.execute()] Creating ZipFile on " + this.containerPath); //$NON-NLS-1$
                // external file -> it is ok to use toFile()
                zip = new ZipFile(this.containerPath.toFile());
                zipFilePath = (Path) this.containerPath;
                // path is already canonical since coming from a library classpath entry
            }

            if (this.isCancelled) {
                if (JobManager.VERBOSE)
                    org.eclipse.jdt.internal.core.util.Util
                            .verbose("-> indexing of " + zip.getName() + " has been cancelled"); //$NON-NLS-1$ //$NON-NLS-2$
                return false;
            }

            if (JobManager.VERBOSE)
                org.eclipse.jdt.internal.core.util.Util.verbose("-> indexing " + zip.getName()); //$NON-NLS-1$
            long initialTime = System.currentTimeMillis();

            String[] paths = index.queryDocumentNames(""); // all file names //$NON-NLS-1$
            if (paths != null) {
                int max = paths.length;
                /* check integrity of the existing index file
                 * if the length is equal to 0, we want to index the whole jar again
                 * If not, then we want to check that there is no missing entry, if
                 * one entry is missing then we recreate the index
                 */
                String EXISTS = "OK"; //$NON-NLS-1$
                String DELETED = "DELETED"; //$NON-NLS-1$
                SimpleLookupTable indexedFileNames = new SimpleLookupTable(max == 0 ? 33 : max + 11);
                for (int i = 0; i < max; i++)
                    indexedFileNames.put(paths[i], DELETED);
                for (Enumeration e = zip.entries(); e.hasMoreElements();) {
                    // iterate each entry to index it
                    ZipEntry ze = (ZipEntry) e.nextElement();
                    String zipEntryName = ze.getName();
                    if (Util.isClassFileName(zipEntryName) && isValidPackageNameForClass(zipEntryName))
                        // the class file may not be there if the package name is not valid
                        indexedFileNames.put(zipEntryName, EXISTS);
                }
                boolean needToReindex = indexedFileNames.elementSize != max; // a new file was added
                if (!needToReindex) {
                    Object[] valueTable = indexedFileNames.valueTable;
                    for (int i = 0, l = valueTable.length; i < l; i++) {
                        if (valueTable[i] == DELETED) {
                            needToReindex = true; // a file was deleted so re-index
                            break;
                        }
                    }
                    if (!needToReindex) {
                        if (JobManager.VERBOSE)
                            org.eclipse.jdt.internal.core.util.Util
                                    .verbose("-> no indexing required (index is consistent with library) for " //$NON-NLS-1$
                                            + zip.getName() + " (" //$NON-NLS-1$
                                            + (System.currentTimeMillis() - initialTime) + "ms)"); //$NON-NLS-1$
                        this.manager.saveIndex(index); // to ensure its placed into the saved state
                        return true;
                    }
                }
            }

            // Index the jar for the first time or reindex the jar in case the previous index file has been corrupted
            // index already existed: recreate it so that we forget about previous entries
            SearchParticipant participant = SearchEngine.getDefaultSearchParticipant(manager, javaProject);
            if (!this.manager.resetIndex(this.containerPath)) {
                // failed to recreate index, see 73330
                this.manager.removeIndex(this.containerPath);
                return false;
            }
            index.separator = JAR_SEPARATOR;
            IPath indexPath = null;
            IndexLocation indexLocation;
            if ((indexLocation = index.getIndexLocation()) != null) {
                indexPath = new Path(indexLocation.getCanonicalFilePath());
            }
            for (Enumeration e = zip.entries(); e.hasMoreElements();) {
                if (this.isCancelled) {
                    if (JobManager.VERBOSE)
                        org.eclipse.jdt.internal.core.util.Util
                                .verbose("-> indexing of " + zip.getName() + " has been cancelled"); //$NON-NLS-1$ //$NON-NLS-2$
                    return false;
                }

                // iterate each entry to index it
                ZipEntry ze = (ZipEntry) e.nextElement();
                String zipEntryName = ze.getName();
                if (Util.isClassFileName(zipEntryName) && isValidPackageNameForClass(zipEntryName)) {
                    // index only classes coming from valid packages - https://bugs.eclipse.org/bugs/show_bug.cgi?id=293861
                    final byte[] classFileBytes = org.eclipse.jdt.internal.compiler.util.Util
                            .getZipEntryByteContent(ze, zip);
                    JavaSearchDocument entryDocument = new JavaSearchDocument(ze, zipFilePath, classFileBytes,
                            participant);
                    this.manager.indexDocument(entryDocument, participant, index, indexPath);
                }
            }
            this.manager.saveIndex(index);
            if (JobManager.VERBOSE)
                org.eclipse.jdt.internal.core.util.Util.verbose("-> done indexing of " //$NON-NLS-1$
                        + zip.getName() + " (" //$NON-NLS-1$
                        + (System.currentTimeMillis() - initialTime) + "ms)"); //$NON-NLS-1$
        } finally {
            if (zip != null) {
                if (JavaModelManager.ZIP_ACCESS_VERBOSE)
                    System.out.println("(" + Thread.currentThread() //$NON-NLS-1$
                            + ") [AddJarFileToIndex.execute()] Closing ZipFile " + zip); //$NON-NLS-1$
                zip.close();
            }
            monitor.exitWrite(); // free write lock
        }
    } catch (IOException e) {
        if (JobManager.VERBOSE) {
            org.eclipse.jdt.internal.core.util.Util.verbose(
                    "-> failed to index " + this.containerPath + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$
            e.printStackTrace();
        }
        this.manager.removeIndex(this.containerPath);
        return false;
    }
    return true;
}