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

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

Introduction

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

Prototype

public Object get(Object key) 

Source Link

Usage

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.//w  ww.ja  v  a  2  s.  com
 */
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

public synchronized void ensureIndexExists(IndexLocation indexLocation, IPath containerPath) {
    SimpleLookupTable states = getIndexStates();
    Object state = states.get(indexLocation);
    if (state == null) {
        updateIndexState(indexLocation, REBUILDING_STATE);
        getIndex(containerPath, indexLocation, true, true);
    }//from   ww  w  . j av  a2 s.com
}

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

License:Open Source License

public NameEnvironmentAnswer findClass(String sourceFileWithoutExtension, String qualifiedPackageName,
        String qualifiedSourceFileWithoutExtension) {
    SimpleLookupTable dirTable = directoryTable(qualifiedPackageName);
    if (dirTable != null && dirTable.elementSize > 0) {
        File file = (File) dirTable.get(sourceFileWithoutExtension);
        if (file != null) {
            return new NameEnvironmentAnswer(new ResourceCompilationUnit(file),
                    null /* no access restriction */);
        }//from   w ww. j av  a  2  s  .c o  m
    }
    return null;
}

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

License:Open Source License

public boolean build(SimpleLookupTable deltas) {
    // initialize builder
    // walk this project's deltas, find changed source files
    // walk prereq projects' deltas, find changed class files & add affected source files
    //   use the build state # to skip the deltas for certain prereq projects
    //   ignore changed zip/jar files since they caused a full build
    // compile the source files & acceptResult()
    // compare the produced class files against the existing ones on disk
    // recompile all dependent source files of any type with structural changes or new/removed secondary type
    // keep a loop counter to abort & perform a full build

    if (JavaBuilder.DEBUG)
        System.out.println("INCREMENTAL build"); //$NON-NLS-1$

    try {//w w  w  .j  av a 2 s.c o m
        resetCollections();

        this.notifier.subTask(Messages.build_analyzingDeltas);
        if (this.javaBuilder.hasBuildpathErrors()) {
            // if a mssing class file was detected in the last build, a build state was saved since its no longer fatal
            // but we need to rebuild every source file since problems were not recorded
            // AND to avoid the infinite build scenario if this project is involved in a cycle, see bug 160550
            // we need to avoid unnecessary deltas caused by doing a full build in this case
            if (JavaBuilder.DEBUG)
                System.out.println("COMPILING all source files since the buildpath has errors "); //$NON-NLS-1$
            this.javaBuilder.currentProject.deleteMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false,
                    IResource.DEPTH_ZERO);
            addAllSourceFiles(this.sourceFiles);
            this.notifier.updateProgressDelta(0.25f);
        } else {
            IResourceDelta sourceDelta = (IResourceDelta) deltas.get(this.javaBuilder.currentProject);
            if (sourceDelta != null)
                if (!findSourceFiles(sourceDelta))
                    return false;
            this.notifier.updateProgressDelta(0.10f);

            Object[] keyTable = deltas.keyTable;
            Object[] valueTable = deltas.valueTable;
            for (int i = 0, l = valueTable.length; i < l; i++) {
                IResourceDelta delta = (IResourceDelta) valueTable[i];
                if (delta != null) {
                    IProject p = (IProject) keyTable[i];
                    ClasspathLocation[] classFoldersAndJars = (ClasspathLocation[]) this.javaBuilder.binaryLocationsPerProject
                            .get(p);
                    if (classFoldersAndJars != null)
                        if (!findAffectedSourceFiles(delta, classFoldersAndJars, p))
                            return false;
                }
            }
            this.notifier.updateProgressDelta(0.10f);

            this.notifier.subTask(Messages.build_analyzingSources);
            addAffectedSourceFiles();
            this.notifier.updateProgressDelta(0.05f);
        }

        this.compileLoop = 0;
        float increment = 0.40f;
        while (this.sourceFiles.size() > 0) { // added to in acceptResult
            if (++this.compileLoop > MaxCompileLoop) {
                if (JavaBuilder.DEBUG)
                    System.out.println("ABORTING incremental build... exceeded loop count"); //$NON-NLS-1$
                return false;
            }
            this.notifier.checkCancel();

            SourceFile[] allSourceFiles = new SourceFile[this.sourceFiles.size()];
            this.sourceFiles.toArray(allSourceFiles);
            resetCollections();

            this.workQueue.addAll(allSourceFiles);
            this.notifier.setProgressPerCompilationUnit(increment / allSourceFiles.length);
            increment = increment / 2;
            compile(allSourceFiles);
            removeSecondaryTypes();
            addAffectedSourceFiles();
        }
        if (this.hasStructuralChanges && this.javaBuilder.javaProject.hasCycleMarker())
            this.javaBuilder.mustPropagateStructuralChanges();
    } catch (AbortIncrementalBuildException e) {
        // abort the incremental build and let the batch builder handle the problem
        if (JavaBuilder.DEBUG)
            System.out.println("ABORTING incremental build... problem with " + e.qualifiedTypeName + //$NON-NLS-1$
                    ". Likely renamed inside its existing source file."); //$NON-NLS-1$
        return false;
    } catch (CoreException e) {
        throw internalException(e);
    } finally {
        cleanUp();
    }
    return true;
}

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);
    }// www.  j  ava 2 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);
                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;//from   w ww  .jav  a 2  s  .  c  o  m
    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 a  2 s  . co  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.matching.ClasspathSourceDirectory.java

License:Open Source License

public NameEnvironmentAnswer findClass(String sourceFileWithoutExtension, String qualifiedPackageName,
        String qualifiedSourceFileWithoutExtension) {
    SimpleLookupTable dirTable = directoryTable(qualifiedPackageName);
    if (dirTable != null && dirTable.elementSize > 0) {
        String file = (String) dirTable.get(sourceFileWithoutExtension);
        if (file != null) {
            return new NameEnvironmentAnswer(new ResourceCompilationUnit(new File(file)),
                    null /* no access restriction */);
        }/*from  w  w  w.  j  a  v  a2  s. co  m*/
    }
    return null;
}

From source file:org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding.java

License:Open Source License

public AnnotationHolder retrieveAnnotationHolder(Binding binding, boolean forceInitialization) {
    SimpleLookupTable store = storedAnnotations(forceInitialization);
    return store == null ? null : (AnnotationHolder) store.get(binding);
}

From source file:org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding.java

License:Open Source License

void storeAnnotations(Binding binding, AnnotationBinding[] annotations) {
    AnnotationHolder holder = null;/*from w w  w  .  j  a va 2  s . c om*/
    if (annotations == null || annotations.length == 0) {
        SimpleLookupTable store = storedAnnotations(false);
        if (store != null)
            holder = (AnnotationHolder) store.get(binding);
        if (holder == null)
            return; // nothing to delete
    } else {
        SimpleLookupTable store = storedAnnotations(true);
        if (store == null)
            return; // not supported
        holder = (AnnotationHolder) store.get(binding);
        if (holder == null)
            holder = new AnnotationHolder();
    }
    storeAnnotationHolder(binding, holder.setAnnotations(annotations));
}