Example usage for org.eclipse.jdt.internal.compiler.util SimpleLookupTable put

List of usage examples for org.eclipse.jdt.internal.compiler.util SimpleLookupTable put

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler.util SimpleLookupTable put.

Prototype

public Object put(Object key, Object value) 

Source Link

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;
    }/*  w ww  .j av  a  2  s  .  com*/

    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  .j a  v  a  2s  .  c o 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

private void readParticipantsIndexNamesFile() {
    SimpleLookupTable containers = new SimpleLookupTable(3);
    try {/*from   ww  w. j a v  a2 s  . co m*/
        char[] participantIndexNames = org.eclipse.jdt.internal.compiler.util.Util
                .getFileCharContent(this.participantIndexNamesFile, null);
        if (participantIndexNames.length > 0) {
            char[][] names = CharOperation.splitOn('\n', participantIndexNames);
            if (names.length >= 3) {
                // First line is DiskIndex signature  (see writeParticipantsIndexNamesFile())
                if (DiskIndex.SIGNATURE.equals(new String(names[0]))) {
                    for (int i = 1, l = names.length - 1; i < l; i += 2) {
                        IndexLocation indexLocation = new FileIndexLocation(new File(new String(names[i])),
                                true);
                        containers.put(indexLocation, new Path(new String(names[i + 1])));
                    }
                }
            }
        }
    } catch (IOException ignored) {
        if (VERBOSE)
            Util.verbose("Failed to read participant index file names"); //$NON-NLS-1$
    }
    this.participantsContainers = containers;
    return;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.ClasspathSourceDirectory.java

License:Open Source License

SimpleLookupTable directoryTable(String qualifiedPackageName) {
    SimpleLookupTable dirTable = (SimpleLookupTable) this.directoryCache.get(qualifiedPackageName);
    if (dirTable == this.missingPackageHolder)
        return null; // package exists in another classpath directory or jar
    if (dirTable != null)
        return dirTable;

    try {//www .  j  a  va  2  s .c  om
        //            IResource container = this.sourceFolder.findMember(qualifiedPackageName); // this is a case-sensitive check
        File container = new File(sourceFolder, qualifiedPackageName);
        if (container.isDirectory()) {
            dirTable = new SimpleLookupTable();
            DirectoryStream<Path> members = Files.newDirectoryStream(container.toPath());
            for (Path member : members) {
                String name;
                if (!member.toFile().isDirectory()) {
                    int index = Util.indexOfJavaLikeExtension(name = member.getFileName().toString());
                    if (index >= 0) {
                        String fullPath = member.toAbsolutePath().toString();
                        if (!org.eclipse.jdt.internal.compiler.util.Util.isExcluded(fullPath.toCharArray(),
                                this.fulInclusionPatternChars, this.fullExclusionPatternChars,
                                false/*not a folder path*/)) {
                            dirTable.put(name.substring(0, index), member.toFile());
                        }
                    }
                }
            }
            this.directoryCache.put(qualifiedPackageName, dirTable);
            return dirTable;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    this.directoryCache.put(qualifiedPackageName, this.missingPackageHolder);
    return null;
}

From source file:net.sf.j2s.core.builder.JavaBuilder.java

License:Open Source License

private SimpleLookupTable findDeltas() {
    this.notifier.subTask(Messages.bind(Messages.build_readingDelta, this.currentProject.getName()));
    IResourceDelta delta = getDelta(this.currentProject);
    SimpleLookupTable deltas = new SimpleLookupTable(3);
    if (delta != null) {
        if (delta.getKind() != IResourceDelta.NO_CHANGE) {
            if (DEBUG)
                System.out.println("JavaBuilder: Found source delta for: " + this.currentProject.getName()); //$NON-NLS-1$
            deltas.put(this.currentProject, delta);
        }/*  w w w  . j  av a2 s.  c o m*/
    } else {
        if (DEBUG)
            System.out.println("JavaBuilder: Missing delta for: " + this.currentProject.getName()); //$NON-NLS-1$
        this.notifier.subTask(""); //$NON-NLS-1$
        return null;
    }

    Object[] keyTable = this.binaryLocationsPerProject.keyTable;
    Object[] valueTable = this.binaryLocationsPerProject.valueTable;
    nextProject: for (int i = 0, l = keyTable.length; i < l; i++) {
        IProject p = (IProject) keyTable[i];
        if (p != null && p != this.currentProject) {
            State s = getLastState(p);
            if (!this.lastState.wasStructurallyChanged(p, s)) { // see if we can skip its delta
                if (s.wasNoopBuild())
                    continue nextProject; // project has no source folders and can be skipped
                ClasspathLocation[] classFoldersAndJars = (ClasspathLocation[]) valueTable[i];
                boolean canSkip = true;
                for (int j = 0, m = classFoldersAndJars.length; j < m; j++) {
                    if (classFoldersAndJars[j].isOutputFolder())
                        classFoldersAndJars[j] = null; // can ignore output folder since project was not structurally changed
                    else
                        canSkip = false;
                }
                if (canSkip)
                    continue nextProject; // project has no structural changes in its output folders
            }

            this.notifier.subTask(Messages.bind(Messages.build_readingDelta, p.getName()));
            delta = getDelta(p);
            if (delta != null) {
                if (delta.getKind() != IResourceDelta.NO_CHANGE) {
                    if (DEBUG)
                        System.out.println("JavaBuilder: Found binary delta for: " + p.getName()); //$NON-NLS-1$
                    deltas.put(p, delta);
                }
            } else {
                if (DEBUG)
                    System.out.println("JavaBuilder: Missing delta for: " + p.getName()); //$NON-NLS-1$
                this.notifier.subTask(""); //$NON-NLS-1$
                return null;
            }
        }
    }
    this.notifier.subTask(""); //$NON-NLS-1$
    return deltas;
}

From source file:net.sf.j2s.core.builder.NameEnvironment.java

License:Open Source License

private void computeClasspathLocations(IWorkspaceRoot root, JavaProject javaProject,
        SimpleLookupTable binaryLocationsPerProject) throws CoreException {

    /* Update cycle marker */
    IMarker cycleMarker = javaProject.getCycleMarker();
    if (cycleMarker != null) {
        int severity = JavaCore.ERROR.equals(javaProject.getOption(JavaCore.CORE_CIRCULAR_CLASSPATH, true))
                ? IMarker.SEVERITY_ERROR
                : IMarker.SEVERITY_WARNING;
        if (severity != cycleMarker.getAttribute(IMarker.SEVERITY, severity))
            cycleMarker.setAttribute(IMarker.SEVERITY, severity);
    }// w  ww . j a  v a 2  s.  c  om

    IClasspathEntry[] classpathEntries = javaProject.getExpandedClasspath();
    ArrayList sLocations = new ArrayList(classpathEntries.length);
    ArrayList bLocations = new ArrayList(classpathEntries.length);
    nextEntry: for (int i = 0, l = classpathEntries.length; i < l; i++) {
        ClasspathEntry entry = (ClasspathEntry) classpathEntries[i];
        IPath path = entry.getPath();
        Object target = JavaModel.getTarget(path, true);
        if (target == null)
            continue nextEntry;

        switch (entry.getEntryKind()) {
        case IClasspathEntry.CPE_SOURCE:
            if (!(target instanceof IContainer))
                continue nextEntry;
            IPath outputPath = entry.getOutputLocation() != null ? entry.getOutputLocation()
                    : javaProject.getOutputLocation();
            IContainer outputFolder;
            if (outputPath.segmentCount() == 1) {
                outputFolder = javaProject.getProject();
            } else {
                outputFolder = root.getFolder(outputPath);
                if (!outputFolder.exists())
                    createOutputFolder(outputFolder);
            }
            sLocations.add(ClasspathLocation.forSourceFolder((IContainer) target, outputFolder,
                    entry.fullInclusionPatternChars(), entry.fullExclusionPatternChars(),
                    entry.ignoreOptionalProblems()));
            continue nextEntry;

        case IClasspathEntry.CPE_PROJECT:
            if (!(target instanceof IProject))
                continue nextEntry;
            IProject prereqProject = (IProject) target;
            if (!JavaProject.hasJavaNature(prereqProject))
                continue nextEntry; // if project doesn't have java nature or is not accessible

            JavaProject prereqJavaProject = (JavaProject) JavaCore.create(prereqProject);
            IClasspathEntry[] prereqClasspathEntries = prereqJavaProject.getRawClasspath();
            ArrayList seen = new ArrayList();
            nextPrereqEntry: for (int j = 0, m = prereqClasspathEntries.length; j < m; j++) {
                IClasspathEntry prereqEntry = prereqClasspathEntries[j];
                if (prereqEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                    Object prereqTarget = JavaModel.getTarget(prereqEntry.getPath(), true);
                    if (!(prereqTarget instanceof IContainer))
                        continue nextPrereqEntry;
                    IPath prereqOutputPath = prereqEntry.getOutputLocation() != null
                            ? prereqEntry.getOutputLocation()
                            : prereqJavaProject.getOutputLocation();
                    IContainer binaryFolder = prereqOutputPath.segmentCount() == 1 ? (IContainer) prereqProject
                            : (IContainer) root.getFolder(prereqOutputPath);
                    if (binaryFolder.exists() && !seen.contains(binaryFolder)) {
                        seen.add(binaryFolder);
                        ClasspathLocation bLocation = ClasspathLocation.forBinaryFolder(binaryFolder, true,
                                entry.getAccessRuleSet());
                        bLocations.add(bLocation);
                        if (binaryLocationsPerProject != null) { // normal builder mode
                            ClasspathLocation[] existingLocations = (ClasspathLocation[]) binaryLocationsPerProject
                                    .get(prereqProject);
                            if (existingLocations == null) {
                                existingLocations = new ClasspathLocation[] { bLocation };
                            } else {
                                int size = existingLocations.length;
                                System.arraycopy(existingLocations, 0,
                                        existingLocations = new ClasspathLocation[size + 1], 0, size);
                                existingLocations[size] = bLocation;
                            }
                            binaryLocationsPerProject.put(prereqProject, existingLocations);
                        }
                    }
                }
            }
            continue nextEntry;

        case IClasspathEntry.CPE_LIBRARY:
            if (target instanceof IResource) {
                IResource resource = (IResource) target;
                ClasspathLocation bLocation = null;
                if (resource instanceof IFile) {
                    AccessRuleSet accessRuleSet = (JavaCore.IGNORE
                            .equals(javaProject.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, true))
                            && JavaCore.IGNORE.equals(
                                    javaProject.getOption(JavaCore.COMPILER_PB_DISCOURAGED_REFERENCE, true)))
                                            ? null
                                            : entry.getAccessRuleSet();
                    bLocation = ClasspathLocation.forLibrary((IFile) resource, accessRuleSet);
                } else if (resource instanceof IContainer) {
                    AccessRuleSet accessRuleSet = (JavaCore.IGNORE
                            .equals(javaProject.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, true))
                            && JavaCore.IGNORE.equals(
                                    javaProject.getOption(JavaCore.COMPILER_PB_DISCOURAGED_REFERENCE, true)))
                                            ? null
                                            : entry.getAccessRuleSet();
                    bLocation = ClasspathLocation.forBinaryFolder((IContainer) target, false, accessRuleSet); // is library folder not output folder
                }
                bLocations.add(bLocation);
                if (binaryLocationsPerProject != null) { // normal builder mode
                    IProject p = resource.getProject(); // can be the project being built
                    ClasspathLocation[] existingLocations = (ClasspathLocation[]) binaryLocationsPerProject
                            .get(p);
                    if (existingLocations == null) {
                        existingLocations = new ClasspathLocation[] { bLocation };
                    } else {
                        int size = existingLocations.length;
                        System.arraycopy(existingLocations, 0,
                                existingLocations = new ClasspathLocation[size + 1], 0, size);
                        existingLocations[size] = bLocation;
                    }
                    binaryLocationsPerProject.put(p, existingLocations);
                }
            } else if (target instanceof File) {
                AccessRuleSet accessRuleSet = (JavaCore.IGNORE
                        .equals(javaProject.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, true))
                        && JavaCore.IGNORE.equals(
                                javaProject.getOption(JavaCore.COMPILER_PB_DISCOURAGED_REFERENCE, true))) ? null
                                        : entry.getAccessRuleSet();
                bLocations.add(ClasspathLocation.forLibrary(path.toString(), accessRuleSet));
            }
            continue nextEntry;
        }
    }

    // now split the classpath locations... place the output folders ahead of the other .class file folders & jars
    ArrayList outputFolders = new ArrayList(1);
    this.sourceLocations = new ClasspathMultiDirectory[sLocations.size()];
    if (!sLocations.isEmpty()) {
        sLocations.toArray(this.sourceLocations);

        // collect the output folders, skipping duplicates
        next: for (int i = 0, l = this.sourceLocations.length; i < l; i++) {
            ClasspathMultiDirectory md = this.sourceLocations[i];
            IPath outputPath = md.binaryFolder.getFullPath();
            for (int j = 0; j < i; j++) { // compare against previously walked source folders
                if (outputPath.equals(this.sourceLocations[j].binaryFolder.getFullPath())) {
                    md.hasIndependentOutputFolder = this.sourceLocations[j].hasIndependentOutputFolder;
                    continue next;
                }
            }
            outputFolders.add(md);

            // also tag each source folder whose output folder is an independent folder & is not also a source folder
            for (int j = 0, m = this.sourceLocations.length; j < m; j++)
                if (outputPath.equals(this.sourceLocations[j].sourceFolder.getFullPath()))
                    continue next;
            md.hasIndependentOutputFolder = true;
        }
    }

    // combine the output folders with the binary folders & jars... place the output folders before other .class file folders & jars
    this.binaryLocations = new ClasspathLocation[outputFolders.size() + bLocations.size()];
    int index = 0;
    for (int i = 0, l = outputFolders.size(); i < l; i++)
        this.binaryLocations[index++] = (ClasspathLocation) outputFolders.get(i);
    for (int i = 0, l = bLocations.size(); i < l; i++)
        this.binaryLocations[index++] = (ClasspathLocation) bLocations.get(i);
}

From source file:net.sf.j2s.core.builder.State.java

License:Open Source License

void write(DataOutputStream out) throws IOException {
    int length;//  w w  w.  j ava 2 s . com
    Object[] keyTable;
    Object[] valueTable;

    /*
     * byte      VERSION
     * String      project name
     * int         build number
     * int         last structural build number
    */
    out.writeByte(VERSION);
    out.writeUTF(this.javaProjectName);
    out.writeInt(this.buildNumber);
    out.writeLong(this.lastStructuralBuildTime);

    /*
     * ClasspathMultiDirectory[]
     * int         id
     * String      path(s)
    */
    out.writeInt(length = this.sourceLocations.length);
    for (int i = 0; i < length; i++) {
        ClasspathMultiDirectory md = this.sourceLocations[i];
        out.writeUTF(md.sourceFolder.getProjectRelativePath().toString());
        out.writeUTF(md.binaryFolder.getProjectRelativePath().toString());
        writeNames(md.inclusionPatterns, out);
        writeNames(md.exclusionPatterns, out);
        out.writeBoolean(md.ignoreOptionalProblems);
        out.writeBoolean(md.hasIndependentOutputFolder);
    }

    /*
     * ClasspathLocation[]
     * int         id
     * String      path(s)
    */
    out.writeInt(length = this.binaryLocations.length);
    next: for (int i = 0; i < length; i++) {
        ClasspathLocation c = this.binaryLocations[i];
        if (c instanceof ClasspathMultiDirectory) {
            out.writeByte(SOURCE_FOLDER);
            for (int j = 0, m = this.sourceLocations.length; j < m; j++) {
                if (this.sourceLocations[j] == c) {
                    out.writeInt(j);
                    continue next;
                }
            }
        } else if (c instanceof ClasspathDirectory) {
            out.writeByte(BINARY_FOLDER);
            ClasspathDirectory cd = (ClasspathDirectory) c;
            out.writeUTF(cd.binaryFolder.getFullPath().toString());
            out.writeBoolean(cd.isOutputFolder);
            writeRestriction(cd.accessRuleSet, out);
        } else {
            ClasspathJar jar = (ClasspathJar) c;
            if (jar.resource == null) {
                out.writeByte(EXTERNAL_JAR);
                out.writeUTF(jar.zipFilename);
                out.writeLong(jar.lastModified());
            } else {
                out.writeByte(INTERNAL_JAR);
                out.writeUTF(jar.resource.getFullPath().toString());
            }
            writeRestriction(jar.accessRuleSet, out);
        }
    }

    /*
     * Structural build numbers table
     * String      prereq project name
     * int         last structural build number
    */
    out.writeInt(length = this.structuralBuildTimes.elementSize);
    if (length > 0) {
        keyTable = this.structuralBuildTimes.keyTable;
        valueTable = this.structuralBuildTimes.valueTable;
        for (int i = 0, l = keyTable.length; i < l; i++) {
            if (keyTable[i] != null) {
                length--;
                out.writeUTF((String) keyTable[i]);
                out.writeLong(((Long) valueTable[i]).longValue());
            }
        }
        if (JavaBuilder.DEBUG && length != 0)
            System.out.println("structuralBuildNumbers table is inconsistent"); //$NON-NLS-1$
    }

    /*
     * String[]   Interned type locators
     */
    out.writeInt(length = this.references.elementSize);
    SimpleLookupTable internedTypeLocators = new SimpleLookupTable(length);
    if (length > 0) {
        keyTable = this.references.keyTable;
        for (int i = 0, l = keyTable.length; i < l; i++) {
            if (keyTable[i] != null) {
                length--;
                String key = (String) keyTable[i];
                out.writeUTF(key);
                internedTypeLocators.put(key, new Integer(internedTypeLocators.elementSize));
            }
        }
        if (JavaBuilder.DEBUG && length != 0)
            System.out.println("references table is inconsistent"); //$NON-NLS-1$
    }

    /*
     * Type locators table
     * String      type name
     * int         interned locator id
     */
    out.writeInt(length = this.typeLocators.elementSize);
    if (length > 0) {
        keyTable = this.typeLocators.keyTable;
        valueTable = this.typeLocators.valueTable;
        for (int i = 0, l = keyTable.length; i < l; i++) {
            if (keyTable[i] != null) {
                length--;
                out.writeUTF((String) keyTable[i]);
                Integer index = (Integer) internedTypeLocators.get(valueTable[i]);
                out.writeInt(index.intValue());
            }
        }
        if (JavaBuilder.DEBUG && length != 0)
            System.out.println("typeLocators table is inconsistent"); //$NON-NLS-1$
    }

    /*
     * char[][]   Interned root names
     * char[][][]   Interned qualified names
     * char[][]   Interned simple names
     */
    SimpleLookupTable internedRootNames = new SimpleLookupTable(3);
    SimpleLookupTable internedQualifiedNames = new SimpleLookupTable(31);
    SimpleLookupTable internedSimpleNames = new SimpleLookupTable(31);
    valueTable = this.references.valueTable;
    for (int i = 0, l = valueTable.length; i < l; i++) {
        if (valueTable[i] != null) {
            ReferenceCollection collection = (ReferenceCollection) valueTable[i];
            char[][] rNames = collection.rootReferences;
            for (int j = 0, m = rNames.length; j < m; j++) {
                char[] rName = rNames[j];
                if (!internedRootNames.containsKey(rName)) // remember the names have been interned
                    internedRootNames.put(rName, new Integer(internedRootNames.elementSize));
            }
            char[][][] qNames = collection.qualifiedNameReferences;
            for (int j = 0, m = qNames.length; j < m; j++) {
                char[][] qName = qNames[j];
                if (!internedQualifiedNames.containsKey(qName)) { // remember the names have been interned
                    internedQualifiedNames.put(qName, new Integer(internedQualifiedNames.elementSize));
                    for (int k = 0, n = qName.length; k < n; k++) {
                        char[] sName = qName[k];
                        if (!internedSimpleNames.containsKey(sName)) // remember the names have been interned
                            internedSimpleNames.put(sName, new Integer(internedSimpleNames.elementSize));
                    }
                }
            }
            char[][] sNames = collection.simpleNameReferences;
            for (int j = 0, m = sNames.length; j < m; j++) {
                char[] sName = sNames[j];
                if (!internedSimpleNames.containsKey(sName)) // remember the names have been interned
                    internedSimpleNames.put(sName, new Integer(internedSimpleNames.elementSize));
            }
        }
    }
    char[][] internedArray = new char[internedRootNames.elementSize][];
    Object[] rootNames = internedRootNames.keyTable;
    Object[] positions = internedRootNames.valueTable;
    for (int i = positions.length; --i >= 0;) {
        if (positions[i] != null) {
            int index = ((Integer) positions[i]).intValue();
            internedArray[index] = (char[]) rootNames[i];
        }
    }
    writeNames(internedArray, out);
    // now write the interned simple names
    internedArray = new char[internedSimpleNames.elementSize][];
    Object[] simpleNames = internedSimpleNames.keyTable;
    positions = internedSimpleNames.valueTable;
    for (int i = positions.length; --i >= 0;) {
        if (positions[i] != null) {
            int index = ((Integer) positions[i]).intValue();
            internedArray[index] = (char[]) simpleNames[i];
        }
    }
    writeNames(internedArray, out);
    // now write the interned qualified names as arrays of interned simple names
    char[][][] internedQArray = new char[internedQualifiedNames.elementSize][][];
    Object[] qualifiedNames = internedQualifiedNames.keyTable;
    positions = internedQualifiedNames.valueTable;
    for (int i = positions.length; --i >= 0;) {
        if (positions[i] != null) {
            int index = ((Integer) positions[i]).intValue();
            internedQArray[index] = (char[][]) qualifiedNames[i];
        }
    }
    out.writeInt(length = internedQArray.length);
    for (int i = 0; i < length; i++) {
        char[][] qName = internedQArray[i];
        int qLength = qName.length;
        out.writeInt(qLength);
        for (int j = 0; j < qLength; j++) {
            Integer index = (Integer) internedSimpleNames.get(qName[j]);
            out.writeInt(index.intValue());
        }
    }

    /*
     * References table
     * int      interned locator id
     * ReferenceCollection
    */
    out.writeInt(length = this.references.elementSize);
    if (length > 0) {
        keyTable = this.references.keyTable;
        for (int i = 0, l = keyTable.length; i < l; i++) {
            if (keyTable[i] != null) {
                length--;
                Integer index = (Integer) internedTypeLocators.get(keyTable[i]);
                out.writeInt(index.intValue());
                ReferenceCollection collection = (ReferenceCollection) valueTable[i];
                if (collection instanceof AdditionalTypeCollection) {
                    out.writeByte(1);
                    AdditionalTypeCollection atc = (AdditionalTypeCollection) collection;
                    writeNames(atc.definedTypeNames, out);
                } else {
                    out.writeByte(2);
                }
                char[][][] qNames = collection.qualifiedNameReferences;
                int qLength = qNames.length;
                out.writeInt(qLength);
                for (int j = 0; j < qLength; j++) {
                    index = (Integer) internedQualifiedNames.get(qNames[j]);
                    out.writeInt(index.intValue());
                }
                char[][] sNames = collection.simpleNameReferences;
                int sLength = sNames.length;
                out.writeInt(sLength);
                for (int j = 0; j < sLength; j++) {
                    index = (Integer) internedSimpleNames.get(sNames[j]);
                    out.writeInt(index.intValue());
                }
                char[][] rNames = collection.rootReferences;
                int rLength = rNames.length;
                out.writeInt(rLength);
                for (int j = 0; j < rLength; j++) {
                    index = (Integer) internedRootNames.get(rNames[j]);
                    out.writeInt(index.intValue());
                }
            }
        }
        if (JavaBuilder.DEBUG && length != 0)
            System.out.println("references table is inconsistent"); //$NON-NLS-1$
    }
}

From source file:org.eclipse.ajdt.internal.core.builder.BuildClasspathResolver.java

License:Open Source License

private void computeClasspathLocations(IWorkspaceRoot root, JavaProject javaProject,
        SimpleLookupTable binaryLocationsPerProject) throws CoreException {

    /* Update cycle marker */
    IMarker cycleMarker = javaProject.getCycleMarker();
    if (cycleMarker != null) {
        int severity = JavaCore.ERROR.equals(javaProject.getOption(JavaCore.CORE_CIRCULAR_CLASSPATH, true))
                ? IMarker.SEVERITY_ERROR
                : IMarker.SEVERITY_WARNING;
        if (severity != ((Integer) cycleMarker.getAttribute(IMarker.SEVERITY)).intValue())
            cycleMarker.setAttribute(IMarker.SEVERITY, severity);
    }//from  w w w .  j a v  a2  s .  c o  m

    IClasspathEntry[] classpathEntries = javaProject.getExpandedClasspath();
    ArrayList sLocations = new ArrayList(classpathEntries.length);
    ArrayList bLocations = new ArrayList(classpathEntries.length);
    nextEntry: for (int i = 0, l = classpathEntries.length; i < l; i++) {
        ClasspathEntry entry = (ClasspathEntry) classpathEntries[i];
        IPath path = entry.getPath();
        Object target = JavaModel.getTarget(path, true);
        if (target == null)
            continue nextEntry;

        switch (entry.getEntryKind()) {
        case IClasspathEntry.CPE_SOURCE:
            if (!(target instanceof IContainer))
                continue nextEntry;
            IPath outputPath = entry.getOutputLocation() != null ? entry.getOutputLocation()
                    : javaProject.getOutputLocation();
            IContainer outputFolder;
            if (outputPath.segmentCount() == 1) {
                outputFolder = javaProject.getProject();
            } else {
                outputFolder = root.getFolder(outputPath);
                // AspectJ Change Begin
                // This method can be executing on the wrong thread, where createFolder() will hang, so don't do it!
                // if (!outputFolder.exists())
                //    createFolder(outputFolder);
                // AspectJ Change End
            }
            sLocations.add(ClasspathLocation.forSourceFolder((IContainer) target, outputFolder,
                    entry.fullInclusionPatternChars(), entry.fullExclusionPatternChars()));
            continue nextEntry;

        case IClasspathEntry.CPE_PROJECT:
            if (!(target instanceof IProject))
                continue nextEntry;
            IProject prereqProject = (IProject) target;
            if (!JavaProject.hasJavaNature(prereqProject))
                continue nextEntry; // if project doesn't have java nature or is not accessible

            JavaProject prereqJavaProject = (JavaProject) JavaCore.create(prereqProject);
            IClasspathEntry[] prereqClasspathEntries = prereqJavaProject.getRawClasspath();
            ArrayList seen = new ArrayList();
            nextPrereqEntry: for (int j = 0, m = prereqClasspathEntries.length; j < m; j++) {
                IClasspathEntry prereqEntry = prereqClasspathEntries[j];
                if (prereqEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                    Object prereqTarget = JavaModel.getTarget(prereqEntry.getPath(), true);
                    if (!(prereqTarget instanceof IContainer))
                        continue nextPrereqEntry;
                    IPath prereqOutputPath = prereqEntry.getOutputLocation() != null
                            ? prereqEntry.getOutputLocation()
                            : prereqJavaProject.getOutputLocation();
                    IContainer binaryFolder = prereqOutputPath.segmentCount() == 1 ? (IContainer) prereqProject
                            : (IContainer) root.getFolder(prereqOutputPath);
                    if (binaryFolder.exists() && !seen.contains(binaryFolder)) {
                        seen.add(binaryFolder);
                        ClasspathLocation bLocation = ClasspathLocation.forBinaryFolder(binaryFolder, true,
                                entry.getAccessRuleSet());
                        bLocations.add(bLocation);
                        if (binaryLocationsPerProject != null) { // normal builder mode
                            ClasspathLocation[] existingLocations = (ClasspathLocation[]) binaryLocationsPerProject
                                    .get(prereqProject);
                            if (existingLocations == null) {
                                existingLocations = new ClasspathLocation[] { bLocation };
                            } else {
                                int size = existingLocations.length;
                                System.arraycopy(existingLocations, 0,
                                        existingLocations = new ClasspathLocation[size + 1], 0, size);
                                existingLocations[size] = bLocation;
                            }
                            binaryLocationsPerProject.put(prereqProject, existingLocations);
                        }
                    }
                }
            }
            continue nextEntry;

        case IClasspathEntry.CPE_LIBRARY:
            if (target instanceof IResource) {
                IResource resource = (IResource) target;
                ClasspathLocation bLocation = null;
                if (resource instanceof IFile) {
                    if (!(org.eclipse.jdt.internal.compiler.util.Util
                            .isPotentialZipArchive(path.lastSegment())))
                        continue nextEntry;
                    AccessRuleSet accessRuleSet = JavaCore.IGNORE.equals(
                            javaProject.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, true)) ? null
                                    : entry.getAccessRuleSet();
                    bLocation = ClasspathLocation.forLibrary((IFile) resource, accessRuleSet);
                } else if (resource instanceof IContainer) {
                    AccessRuleSet accessRuleSet = JavaCore.IGNORE.equals(
                            javaProject.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, true)) ? null
                                    : entry.getAccessRuleSet();
                    bLocation = ClasspathLocation.forBinaryFolder((IContainer) target, false, accessRuleSet); // is library folder not output folder
                }
                bLocations.add(bLocation);
                if (binaryLocationsPerProject != null) { // normal builder mode
                    IProject p = resource.getProject(); // can be the project being built
                    ClasspathLocation[] existingLocations = (ClasspathLocation[]) binaryLocationsPerProject
                            .get(p);
                    if (existingLocations == null) {
                        existingLocations = new ClasspathLocation[] { bLocation };
                    } else {
                        int size = existingLocations.length;
                        System.arraycopy(existingLocations, 0,
                                existingLocations = new ClasspathLocation[size + 1], 0, size);
                        existingLocations[size] = bLocation;
                    }
                    binaryLocationsPerProject.put(p, existingLocations);
                }
            } else if (target instanceof File) {
                if (!(org.eclipse.jdt.internal.compiler.util.Util.isPotentialZipArchive(path.lastSegment())))
                    continue nextEntry;
                AccessRuleSet accessRuleSet = JavaCore.IGNORE
                        .equals(javaProject.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, true)) ? null
                                : entry.getAccessRuleSet();
                bLocations.add(ClasspathLocation.forLibrary(path.toString(), accessRuleSet));
            }
            continue nextEntry;
        }
    }

    // now split the classpath locations... place the output folders ahead of the other .class file folders & jars
    ArrayList outputFolders = new ArrayList(1);
    this.sourceLocations = new ClasspathMultiDirectory[sLocations.size()];
    if (!sLocations.isEmpty()) {
        sLocations.toArray(this.sourceLocations);

        // collect the output folders, skipping duplicates
        next: for (int i = 0, l = sourceLocations.length; i < l; i++) {
            ClasspathMultiDirectory md = sourceLocations[i];
            IPath outputPath = md.binaryFolder.getFullPath();
            for (int j = 0; j < i; j++) { // compare against previously walked source folders
                if (outputPath.equals(sourceLocations[j].binaryFolder.getFullPath())) {
                    md.hasIndependentOutputFolder = sourceLocations[j].hasIndependentOutputFolder;
                    continue next;
                }
            }
            outputFolders.add(md);

            // also tag each source folder whose output folder is an independent folder & is not also a source folder
            for (int j = 0, m = sourceLocations.length; j < m; j++)
                if (outputPath.equals(sourceLocations[j].sourceFolder.getFullPath()))
                    continue next;
            md.hasIndependentOutputFolder = true;
        }
    }

    // combine the output folders with the binary folders & jars... place the output folders before other .class file folders & jars
    this.binaryLocations = new ClasspathLocation[outputFolders.size() + bLocations.size()];
    int index = 0;
    for (int i = 0, l = outputFolders.size(); i < l; i++)
        this.binaryLocations[index++] = (ClasspathLocation) outputFolders.get(i);
    for (int i = 0, l = bLocations.size(); i < l; i++)
        this.binaryLocations[index++] = (ClasspathLocation) bLocations.get(i);
}

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;
    }// w w  w  .  j av a2s  . 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;
}

From source file:org.eclipse.che.jdt.internal.core.search.matching.ClasspathSourceDirectory.java

License:Open Source License

SimpleLookupTable directoryTable(final String qualifiedPackageName) {
    final ConcurrentHashMap<String, Future<SimpleLookupTable>> directoryCache = this.directoryCache;
    Future<SimpleLookupTable> future = directoryCache.get(qualifiedPackageName);
    if (future == missingPackageHolder) {
        // package exists in another classpath directory or jar
        return null;
    }/*from w w  w.j  a v a 2s .c om*/
    if (future == null) {
        FutureTask<SimpleLookupTable> newFuture = new FutureTask<>(new Callable<SimpleLookupTable>() {
            @Override
            public SimpleLookupTable call() throws Exception {
                File container = new File(sourceFolder, qualifiedPackageName);
                SimpleLookupTable dirTable = new SimpleLookupTable();
                if (container.isDirectory()) {
                    try (DirectoryStream<Path> members = Files.newDirectoryStream(container.toPath())) {
                        for (Path member : members) {
                            String name;
                            if (!member.toFile().isDirectory()) {
                                int index = Util
                                        .indexOfJavaLikeExtension(name = member.getFileName().toString());
                                if (index >= 0) {
                                    String fullPath = member.toAbsolutePath().toString();
                                    if (!org.eclipse.jdt.internal.compiler.util.Util.isExcluded(
                                            fullPath.toCharArray(), fulInclusionPatternChars,
                                            fullExclusionPatternChars, false/*not a folder path*/)) {
                                        dirTable.put(name.substring(0, index), member.toString());
                                    }
                                }
                            }
                        }
                        return dirTable;
                    }
                }
                directoryCache.put(qualifiedPackageName, missingPackageHolder);
                return null;
            }
        });
        future = directoryCache.putIfAbsent(qualifiedPackageName, newFuture);
        if (future == null) {
            future = newFuture;
            newFuture.run();
        }
    }
    try {
        return future.get();
    } catch (InterruptedException | ExecutionException e) {
        LOG.error("Error while reading source directory", e);
    }
    directoryCache.put(qualifiedPackageName, missingPackageHolder);
    return null;
}