Example usage for org.eclipse.jdt.internal.core.search.indexing ReadWriteMonitor exitRead

List of usage examples for org.eclipse.jdt.internal.core.search.indexing ReadWriteMonitor exitRead

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.core.search.indexing ReadWriteMonitor exitRead.

Prototype

public synchronized void exitRead() 

Source Link

Document

Only notify waiting writer(s) if last reader

Usage

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

License:Open Source License

public boolean execute(IProgressMonitor progressMonitor) {

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

    File folder = new File(folderPath.toOSString());
    if (!folder.exists())
        return true; // nothing to do, source folder was removed

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

    try {/*from w  w  w .jav  a2s  . c o  m*/
        monitor.enterRead(); // ask permission to read

        final IPath container = this.containerPath;
        final IndexManager indexManager = this.manager;
        final SourceElementParser parser = indexManager.getSourceElementParser(this.project,
                null/*requestor will be set by indexer*/);
        Path path = FileSystems.getDefault().getPath(folderPath.toOSString());
        if (this.exclusionPatterns == null && this.inclusionPatterns == null) {

            Files.walkFileTree(path, new FileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    return null;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (Util.isJavaLikeFileName(file.toFile().getName()))
                        indexManager.addSource(file, container, parser);
                    return FileVisitResult.CONTINUE;
                }

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

                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    return null;
                }
            });

            //                folder.accept(
            //               new IResourceProxyVisitor() {
            //                  public boolean visit(IResourceProxy proxy) /* throws CoreException */{
            //                     if (proxy.getType() == IResource.FILE) {
            //
            //                        return false;
            //                     }
            //                     return true;
            //                  }
            //               },
            //               IResource.NONE
            //            );
        } else {
            Files.walkFileTree(path, new FileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    if (AddFolderToIndex.this.exclusionPatterns != null
                            && AddFolderToIndex.this.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()),
                                AddFolderToIndex.this.inclusionPatterns,
                                AddFolderToIndex.this.exclusionPatterns, true))
                            return FileVisitResult.SKIP_SUBTREE;
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (Util.isJavaLikeFileName(file.getFileName().toString())) {
                        //                                IResource resource = proxy.requestResource();
                        if (!Util.isExcluded(new org.eclipse.core.runtime.Path(file.toFile().getPath()),
                                AddFolderToIndex.this.inclusionPatterns,
                                AddFolderToIndex.this.exclusionPatterns, false))
                            indexManager.addSource(file, container, parser);
                    }
                    return null;
                }

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

                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    return null;
                }
            });
            //                folder.accept(
            //               new IResourceProxyVisitor() {
            //                  public boolean visit(IResourceProxy proxy) /* throws CoreException */{
            //                     switch(proxy.getType()) {
            //                        case IResource.FILE :
            //
            //                           return false;
            //                        case IResource.FOLDER :
            //
            //                     }
            //                     return true;
            //                  }
            //               },
            //               IResource.NONE
            //            );
        }
    } catch (IOException e) {
        if (JobManager.VERBOSE) {
            Util.verbose(
                    "-> failed to add " + this.folderPath + " to index because of the following exception:", //$NON-NLS-1$//$NON-NLS-2$
                    System.err);
            e.printStackTrace();
        }
        return false;
    } finally {
        monitor.exitRead(); // free read lock
    }
    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  ww  w.j  av  a2  s  . 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.IndexManager.java

License:Open Source License

/**
 * Commit all index memory changes to disk
 *//*from   w  ww .j  av a2s .c  o  m*/
public void saveIndexes() {
    // only save cached indexes... the rest were not modified
    ArrayList toSave = new ArrayList();
    synchronized (this) {
        Object[] valueTable = this.indexes.valueTable;
        for (int i = 0, l = valueTable.length; i < l; i++) {
            Index index = (Index) valueTable[i];
            if (index != null)
                toSave.add(index);
        }
    }

    boolean allSaved = true;
    for (int i = 0, length = toSave.size(); i < length; i++) {
        Index index = (Index) toSave.get(i);
        ReadWriteMonitor monitor = index.monitor;
        if (monitor == null)
            continue; // index got deleted since acquired
        try {
            // take read lock before checking if index has changed
            // don't take write lock yet since it can cause a deadlock (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=50571)
            monitor.enterRead();
            if (index.hasChanged()) {
                if (monitor.exitReadEnterWrite()) {
                    try {
                        saveIndex(index);
                    } catch (IOException e) {
                        if (VERBOSE) {
                            Util.verbose("-> got the following exception while saving:", System.err); //$NON-NLS-1$
                            e.printStackTrace();
                        }
                        allSaved = false;
                    } finally {
                        monitor.exitWriteEnterRead();
                    }
                } else {
                    allSaved = false;
                }
            }
        } finally {
            monitor.exitRead();
        }
    }
    if (this.participantsContainers != null && this.participantUpdated) {
        writeParticipantsIndexNamesFile();
        this.participantUpdated = false;
    }
    this.needToSave = !allSaved;
}

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 w  w .  j  a  v  a 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:com.codenvy.ide.ext.java.server.internal.core.search.PatternSearchJob.java

License:Open Source License

public boolean search(Index index, IProgressMonitor progressMonitor) {
    if (index == null)
        return COMPLETE;
    if (progressMonitor != null && progressMonitor.isCanceled())
        throw new OperationCanceledException();
    ReadWriteMonitor monitor = index.monitor;
    if (monitor == null)
        return COMPLETE; // index got deleted since acquired
    try {/*  www .  j  a v  a 2 s. c o m*/
        monitor.enterRead(); // ask permission to read
        long start = System.currentTimeMillis();
        MatchLocator.findIndexMatches(this.pattern, index, this.requestor, this.participant, this.scope,
                progressMonitor);
        this.executionTime += System.currentTimeMillis() - start;
        return COMPLETE;
    } catch (IOException e) {
        if (e instanceof java.io.EOFException)
            e.printStackTrace();
        return FAILED;
    } finally {
        monitor.exitRead(); // finished reading
    }
}