Example usage for org.eclipse.jdt.internal.core JavaProject hasJavaNature

List of usage examples for org.eclipse.jdt.internal.core JavaProject hasJavaNature

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.core JavaProject hasJavaNature.

Prototype

public static boolean hasJavaNature(IProject project) 

Source Link

Document

Returns true if the given project is accessible and it has a java nature, otherwise false.

Usage

From source file:com.centurylink.mdw.plugin.project.assembly.ProjectConfigurator.java

License:Apache License

public boolean hasJavaNature() {
    if (!project.isRemote() && !project.isCloudProject())
        return true;
    else//from  ww w  . j av  a 2s  .c o m
        return JavaProject.hasJavaNature(project.getSourceProject());
}

From source file:in.software.analytics.parichayana.core.internal.builder.ParichayanaBuilder.java

License:Open Source License

private IProject[] getRequiredProjects(boolean includeBinaryPrerequisites) {
    JavaProject javaProject = (JavaProject) JavaCore.create(this.project);
    IWorkspaceRoot workspaceRoot = this.project.getWorkspace().getRoot();
    if (javaProject == null || workspaceRoot == null) {
        return ZERO_PROJECT;
    }/*from w w  w  .ja  v  a 2s  . c o m*/

    List<IProject> projects = new ArrayList<IProject>();
    ExternalFoldersManager externalFoldersManager = JavaModelManager.getExternalManager();
    try {
        IClasspathEntry[] entries = javaProject.getExpandedClasspath();
        for (int i = 0, l = entries.length; i < l; i++) {
            IClasspathEntry entry = entries[i];
            IPath path = entry.getPath();
            IProject p = null;
            switch (entry.getEntryKind()) {
            case IClasspathEntry.CPE_PROJECT:
                p = workspaceRoot.getProject(path.lastSegment()); // missing projects are considered too
                if (((ClasspathEntry) entry).isOptional() && !JavaProject.hasJavaNature(p)) // except if entry is optional
                    p = null;
                break;
            case IClasspathEntry.CPE_LIBRARY:
                if (includeBinaryPrerequisites && path.segmentCount() > 0) {
                    // some binary resources on the class path can come from projects that are not included in the project references
                    IResource resource = workspaceRoot.findMember(path.segment(0));
                    if (resource instanceof IProject) {
                        p = (IProject) resource;
                    } else {
                        resource = externalFoldersManager.getFolder(path);
                        if (resource != null)
                            p = resource.getProject();
                    }
                }
            }
            if (p != null && !projects.contains(p))
                projects.add(p);
        }
    } catch (JavaModelException e) {
        return ZERO_PROJECT;
    }
    IProject[] result = new IProject[projects.size()];
    projects.toArray(result);
    return result;
}

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

License:Open Source License

private IProject[] getRequiredProjects(boolean includeBinaryPrerequisites) {
    if (this.javaProject == null || this.workspaceRoot == null)
        return new IProject[0];

    ArrayList projects = new ArrayList();
    ExternalFoldersManager externalFoldersManager = JavaModelManager.getExternalManager();
    try {//from   w w  w . jav a  2 s  .c o m
        IClasspathEntry[] entries = this.javaProject.getExpandedClasspath();
        for (int i = 0, l = entries.length; i < l; i++) {
            IClasspathEntry entry = entries[i];
            IPath path = entry.getPath();
            IProject p = null;
            switch (entry.getEntryKind()) {
            case IClasspathEntry.CPE_PROJECT:
                p = this.workspaceRoot.getProject(path.lastSegment()); // missing projects are considered too
                if (((ClasspathEntry) entry).isOptional() && !JavaProject.hasJavaNature(p)) // except if entry is optional
                    p = null;
                break;
            case IClasspathEntry.CPE_LIBRARY:
                if (includeBinaryPrerequisites && path.segmentCount() > 0) {
                    // some binary resources on the class path can come from projects that are not included in the project references
                    IResource resource = this.workspaceRoot.findMember(path.segment(0));
                    if (resource instanceof IProject) {
                        p = (IProject) resource;
                    } else {
                        resource = externalFoldersManager.getFolder(path);
                        if (resource != null)
                            p = resource.getProject();
                    }
                }
            }
            if (p != null && !projects.contains(p))
                projects.add(p);
        }
    } catch (JavaModelException e) {
        return new IProject[0];
    }
    IProject[] result = new IProject[projects.size()];
    projects.toArray(result);
    return result;
}

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);
    }//from  w  ww  . j ava 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);
                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:org.codehaus.jdt.groovy.model.GroovyCompilationUnit.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes", "nls", "restriction" })
@Override//from w  w w  .  j  ava2  s.  co m
protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements,
        IResource underlyingResource) throws JavaModelException {
    try {
        depth.set(depth.get() + 1);

        // if (!isOnBuildPath()) {
        // return false;
        // }

        if (GroovyLogManager.manager.hasLoggers()) {
            GroovyLogManager.manager.log(TraceCategory.COMPILER, "Build Structure starting for " + this.name);
            GroovyLogManager.manager
                    .logStart("Build structure: " + name + " : " + Thread.currentThread().getName());
        }

        CompilationUnitElementInfo unitInfo = (CompilationUnitElementInfo) info;

        // ensure buffer is opened
        IBuffer buffer = getBufferManager().getBuffer(this);
        if (buffer == null) {
            openBuffer(pm, unitInfo); // open buffer independently from the
            // info, since we are building the info
        }

        // generate structure and compute syntax problems if needed
        GroovyCompilationUnitStructureRequestor requestor = new GroovyCompilationUnitStructureRequestor(this,
                unitInfo, newElements);
        JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = getPerWorkingCopyInfo();
        JavaProject project = (JavaProject) getJavaProject();

        // determine what kind of buildStructure we are doing
        boolean createAST;
        int reconcileFlags;
        boolean resolveBindings;
        HashMap problems;
        if (info instanceof ASTHolderCUInfo) {
            ASTHolderCUInfo astHolder = (ASTHolderCUInfo) info;
            createAST = ((Integer) ReflectionUtils.getPrivateField(ASTHolderCUInfo.class, "astLevel", //$NON-NLS-1$
                    astHolder)).intValue() != NO_AST;
            resolveBindings = ((Boolean) ReflectionUtils.getPrivateField(ASTHolderCUInfo.class,
                    "resolveBindings", astHolder)).booleanValue();
            reconcileFlags = ((Integer) ReflectionUtils.getPrivateField(ASTHolderCUInfo.class, "reconcileFlags", //$NON-NLS-1$
                    astHolder)).intValue();
            problems = (HashMap) ReflectionUtils.getPrivateField(ASTHolderCUInfo.class, "problems", astHolder);
        } else {
            createAST = false;
            resolveBindings = false;
            reconcileFlags = 0;
            problems = null;
        }

        boolean computeProblems = perWorkingCopyInfo != null && perWorkingCopyInfo.isActive() && project != null
                && JavaProject.hasJavaNature(project.getProject());
        IProblemFactory problemFactory = new DefaultProblemFactory();

        // compiler options
        Map<String, String> options = (project == null ? JavaCore.getOptions() : project.getOptions(true));
        if (!computeProblems) {
            // disable task tags checking to speed up parsing
            options.put(JavaCore.COMPILER_TASK_TAGS, ""); //$NON-NLS-1$
        }

        // FIXASC deal with the case of project==null to reduce duplication in this next line and call to setGroovyClasspath
        // Required for Groovy, but not for Java
        options.put(CompilerOptions.OPTIONG_BuildGroovyFiles, CompilerOptions.ENABLED);

        CompilerOptions compilerOptions = new CompilerOptions(options);

        if (project != null) {
            CompilerUtils.setGroovyClasspath(compilerOptions, project);
        }

        // Required for Groovy, but not for Java
        ProblemReporter reporter = new ProblemReporter(new GroovyErrorHandlingPolicy(!computeProblems),
                compilerOptions, new DefaultProblemFactory());

        SourceElementParser parser = new MultiplexingSourceElementRequestorParser(reporter, requestor, /*
                                                                                                       * not needed if
                                                                                                       * computing groovy only
                                                                                                       */
                problemFactory, compilerOptions, true/* report local declarations */, !createAST /*
                                                                                                 * optimize string literals only if not
                                                                                                 * creating a DOM AST
                                                                                                 */);
        parser.reportOnlyOneSyntaxError = !computeProblems;
        // maybe not needed for groovy, but I don't want to find out.
        parser.setMethodsFullRecovery(true);
        parser.setStatementsRecovery((reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);

        if (!computeProblems && !resolveBindings && !createAST) // disable javadoc parsing if not computing problems, not
            // resolving
            // and not creating ast
            parser.javadocParser.checkDocComment = false;
        requestor.setParser(parser);

        // update timestamp (might be IResource.NULL_STAMP if original does not
        // exist)
        if (underlyingResource == null) {
            underlyingResource = getResource();
        }
        // underlying resource is null in the case of a working copy on a class
        // file in a jar
        if (underlyingResource != null) {
            ReflectionUtils.setPrivateField(CompilationUnitElementInfo.class, "timestamp", unitInfo, //$NON-NLS-1$
                    underlyingResource.getModificationStamp());
        }

        GroovyCompilationUnitDeclaration compilationUnitDeclaration = null;
        CompilationUnit source = cloneCachingContents();
        try {
            // GROOVY
            // note that this is a slightly different approach than taken by super.buildStructure
            // in super.buildStructure, there is a test here to see if computeProblems is true.
            // if false, then parser.parserCompilationUnit is called.
            // this will not work for Groovy because we need to ensure bindings are resolved
            // for many operations (content assist and code select) to work.
            // So, for groovy, always use CompilationUnitProblemFinder.process and then process problems
            // separately only if necessary
            // addendum (GRECLIPSE-942). The testcase for that bug includes a package with 200
            // types in that refer to each other in a chain, through field references. If a reconcile
            // references the top of the chain we can go through a massive number of recursive calls into
            // this buildStructure for each one. The 'full' parse (with bindings) is only required for
            // the top most (regardless of the computeProblems setting) and so we track how many recursive
            // calls we have made - if we are at depth 2 we do what JDT was going to do (the quick thing).
            if (computeProblems || depth.get() < 2) {
                if (problems == null) {
                    // report problems to the problem requestor
                    problems = new HashMap();
                    compilationUnitDeclaration = (GroovyCompilationUnitDeclaration) CompilationUnitProblemFinder
                            .process(source, parser, this.owner, problems, createAST, reconcileFlags, pm);
                    if (computeProblems) {
                        try {
                            perWorkingCopyInfo.beginReporting();
                            for (Iterator iteraror = problems.values().iterator(); iteraror.hasNext();) {
                                CategorizedProblem[] categorizedProblems = (CategorizedProblem[]) iteraror
                                        .next();
                                if (categorizedProblems == null)
                                    continue;
                                for (int i = 0, length = categorizedProblems.length; i < length; i++) {
                                    perWorkingCopyInfo.acceptProblem(categorizedProblems[i]);
                                }
                            }
                        } finally {
                            perWorkingCopyInfo.endReporting();
                        }
                    }
                } else {
                    // collect problems
                    compilationUnitDeclaration = (GroovyCompilationUnitDeclaration) CompilationUnitProblemFinder
                            .process(source, parser, this.owner, problems, createAST, reconcileFlags, pm);
                }
            } else {
                compilationUnitDeclaration = (GroovyCompilationUnitDeclaration) parser
                        .parseCompilationUnit(source, true /* full parse to find local elements */, pm);
            }

            // GROOVY
            // if this is a working copy, then we have more work to do
            maybeCacheModuleNode(perWorkingCopyInfo, compilationUnitDeclaration);

            // create the DOM AST from the compiler AST
            if (createAST) {
                org.eclipse.jdt.core.dom.CompilationUnit ast;
                try {
                    ast = AST.convertCompilationUnit(AST.JLS3, compilationUnitDeclaration, options,
                            computeProblems, source, reconcileFlags, pm);
                    ReflectionUtils.setPrivateField(ASTHolderCUInfo.class, "ast", info, ast); //$NON-NLS-1$
                } catch (OperationCanceledException e) {
                    // catch this exception so as to not enter the catch(RuntimeException e) below
                    // might need to do the same for AbortCompilation
                    throw e;
                } catch (IllegalArgumentException e) {
                    // if necessary, we can do some better reporting here.
                    Util.log(e, "Problem with build structure: Offset for AST node is incorrect in " //$NON-NLS-1$
                            + this.getParent().getElementName() + "." + getElementName()); //$NON-NLS-1$
                } catch (Exception e) {
                    Util.log(e, "Problem with build structure for " + this.getElementName()); //$NON-NLS-1$
                }
            }
        } catch (OperationCanceledException e) {
            // catch this exception so as to not enter the catch(RuntimeException e) below
            // might need to do the same for AbortCompilation
            throw e;
        } catch (JavaModelException e) {
            // GRECLIPSE-1480 don't log element does not exist exceptions. since this could occur when element is in a non-java
            // project
            if (e.getStatus().getCode() != IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST
                    || this.getJavaProject().exists()) {
                Util.log(e, "Problem with build structure for " + this.getElementName()); //$NON-NLS-1$
            }
        } catch (Exception e) {
            // GROOVY: The groovy compiler does not handle broken code well in many situations
            // use this general catch clause so that exceptions thrown by broken code
            // do not bubble up the stack.
            Util.log(e, "Problem with build structure for " + this.getElementName()); //$NON-NLS-1$
        } finally {
            if (compilationUnitDeclaration != null) {
                compilationUnitDeclaration.cleanUp();
            }
        }
        return unitInfo.isStructureKnown();
    } finally {
        depth.set(depth.get() - 1);
        if (GroovyLogManager.manager.hasLoggers()) {
            GroovyLogManager.manager.logEnd(
                    "Build structure: " + name + " : " + Thread.currentThread().getName(),
                    TraceCategory.COMPILER);
        }
    }
}

From source file:org.codehaus.jdt.groovy.model.GroovyReconcileWorkingCopyOperation.java

License:Open Source License

public org.eclipse.jdt.core.dom.CompilationUnit makeConsistent(CompilationUnit workingCopy)
        throws JavaModelException {
    if (!workingCopy.isConsistent()) {
        // make working copy consistent
        if (this.problems == null)
            this.problems = new HashMap();
        this.resolveBindings = this.requestorIsActive;
        this.ast = workingCopy.makeConsistent(this.astLevel, this.resolveBindings, this.reconcileFlags,
                this.problems, this.progressMonitor);
        this.deltaBuilder.buildDeltas();
        if (this.ast != null && this.deltaBuilder.delta != null)
            this.deltaBuilder.delta.changedAST(this.ast);
        return this.ast;
    }//from www . java2s .c  o  m
    if (this.ast != null)
        return this.ast; // no need to recompute AST if known already

    CompilationUnitDeclaration unit = null;
    try {
        JavaModelManager.getJavaModelManager().abortOnMissingSource.set(Boolean.TRUE);
        CompilationUnit source = workingCopy.cloneCachingContents();
        // find problems if needed
        if (JavaProject.hasJavaNature(workingCopy.getJavaProject().getProject())
                && (this.reconcileFlags & ICompilationUnit.FORCE_PROBLEM_DETECTION) != 0) {
            this.resolveBindings = this.requestorIsActive;
            if (this.problems == null)
                this.problems = new HashMap();
            unit = CompilationUnitProblemFinder.process(source, this.workingCopyOwner, this.problems,
                    this.astLevel != ICompilationUnit.NO_AST/* creating AST if level is not NO_AST */,
                    this.reconcileFlags, this.progressMonitor);
            // GROOVY cache the ModuleNode in the ModuleNodeMapper
            if (unit instanceof GroovyCompilationUnitDeclaration) {
                // should always be true
                ModuleNodeMapper.getInstance().maybeCacheModuleNode(workingCopy.getPerWorkingCopyInfo(),
                        (GroovyCompilationUnitDeclaration) unit);
            }
            // GROOVY end

            if (this.progressMonitor != null)
                this.progressMonitor.worked(1);
        }

        // create AST if needed
        if (this.astLevel != ICompilationUnit.NO_AST && unit != null/*
                                                                    * unit is null if working copy is consistent && (problem
                                                                    * detection not forced || non-Java project) -> don't create
                                                                    * AST as per API
                                                                    */) {
            Map options = workingCopy.getJavaProject().getOptions(true);
            // convert AST
            this.ast = AST.convertCompilationUnit(this.astLevel, unit, options, this.resolveBindings, source,
                    this.reconcileFlags, this.progressMonitor);
            if (this.ast != null) {
                if (this.deltaBuilder.delta == null) {
                    this.deltaBuilder.delta = new JavaElementDelta(workingCopy);
                }
                this.deltaBuilder.delta.changedAST(this.ast);
            }
            if (this.progressMonitor != null)
                this.progressMonitor.worked(1);
        }
    } catch (JavaModelException e) {
        if (JavaProject.hasJavaNature(workingCopy.getJavaProject().getProject()))
            throw e;
        // else JavaProject has lost its nature (or most likely was closed/deleted) while reconciling -> ignore
        // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=100919)
    } finally {
        JavaModelManager.getJavaModelManager().abortOnMissingSource.set(null);
        if (unit != null) {
            unit.cleanUp();
        }
    }
    return this.ast;
}

From source file:org.eclipse.ajdt.core.reconcile.AJReconcileWorkingCopyOperation.java

License:Open Source License

public org.eclipse.jdt.core.dom.CompilationUnit makeConsistent(CompilationUnit workingCopy)
        throws JavaModelException {
    if (!workingCopy.isConsistent()) {
        // make working copy consistent
        if (this.problems == null)
            this.problems = new HashMap();
        this.resolveBindings = this.requestorIsActive;
        this.ast = workingCopy.makeConsistent(this.astLevel, this.resolveBindings, reconcileFlags,
                this.problems, this.progressMonitor);
        this.deltaBuilder.buildDeltas();
        if (this.ast != null && this.deltaBuilder.delta != null)
            this.deltaBuilder.delta.changedAST(this.ast);
        return this.ast;
    }/*from   w  w w .  j av  a2 s . c o  m*/
    if (this.ast != null)
        return this.ast; // no need to recompute AST if known already

    CompilationUnitDeclaration unit = null;
    try {
        JavaModelManager.getJavaModelManager().abortOnMissingSource.set(Boolean.TRUE);
        CompilationUnit source;
        if (workingCopy instanceof AJCompilationUnit) {
            source = ((AJCompilationUnit) workingCopy).ajCloneCachingContents();
        } else {
            source = workingCopy.cloneCachingContents();
        }
        // find problems if needed
        if (JavaProject.hasJavaNature(workingCopy.getJavaProject().getProject())
                && (this.reconcileFlags & ICompilationUnit.FORCE_PROBLEM_DETECTION) != 0) {
            this.resolveBindings = this.requestorIsActive;
            if (this.problems == null)
                this.problems = new HashMap();
            unit = AJCompilationUnitProblemFinder.processAJ(source, this.workingCopyOwner, this.problems,
                    this.astLevel != ICompilationUnit.NO_AST/*creating AST if level is not NO_AST */,
                    reconcileFlags, this.progressMonitor);
            if (this.progressMonitor != null)
                this.progressMonitor.worked(1);
        }

        // create AST if needed
        if (this.astLevel != ICompilationUnit.NO_AST
                && unit != null/*unit is null if working copy is consistent && (problem detection not forced || non-Java project) -> don't create AST as per API*/) {
            Map options = workingCopy.getJavaProject().getOptions(true);
            // convert AST
            this.ast = AST.convertCompilationUnit(this.astLevel, unit, options, this.resolveBindings, source,
                    reconcileFlags, this.progressMonitor);
            if (this.ast != null) {
                if (this.deltaBuilder.delta == null) {
                    this.deltaBuilder.delta = new JavaElementDelta(workingCopy);
                }
                this.deltaBuilder.delta.changedAST(this.ast);
            }
            if (this.progressMonitor != null)
                this.progressMonitor.worked(1);
        }
    } catch (JavaModelException e) {
        if (JavaProject.hasJavaNature(workingCopy.getJavaProject().getProject()))
            throw e;
        // else JavaProject has lost its nature (or most likely was closed/deleted) while reconciling -> ignore
        // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=100919)
    } finally {
        JavaModelManager.getJavaModelManager().abortOnMissingSource.set(null);
        if (unit != null) {
            unit.cleanUp();
        }
    }
    return this.ast;
}

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);
    }/*  w w  w  .  jav  a  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);
                // 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.ajdt.internal.ui.editor.CompilationUnitAnnotationModelWrapper.java

License:Open Source License

public void beginReporting() {
    if (delegate != null) {
        ((IProblemRequestor) delegate).beginReporting();

        IJavaProject project = unit.getJavaProject();

        AJCompilationUnitStructureRequestor requestor = new AJCompilationUnitStructureRequestor(unit,
                new AJCompilationUnitInfo(), new HashMap());
        JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = ((CompilationUnit) unit)
                .getPerWorkingCopyInfo();
        boolean computeProblems = JavaProject.hasJavaNature(project.getProject()) && perWorkingCopyInfo != null
                && perWorkingCopyInfo.isActive();
        IProblemFactory problemFactory = new DefaultProblemFactory();
        Map options = project.getOptions(true);
        IBuffer buffer;/*from  w w w . j  ava2 s .c  o m*/
        try {
            buffer = unit.getBuffer();

            final char[] contents = buffer == null ? null : buffer.getCharacters();

            AJSourceElementParser parser = new AJSourceElementParser(requestor, problemFactory,
                    new CompilerOptions(options), true/*report local declarations*/, false);
            parser.reportOnlyOneSyntaxError = !computeProblems;

            parser.scanner.source = contents;
            requestor.setParser(parser);

            CompilationUnitDeclaration unitDec = parser.parseCompilationUnit(
                    new org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit() {
                        public char[] getContents() {
                            return contents;
                        }

                        public char[] getMainTypeName() {
                            return ((CompilationUnit) unit).getMainTypeName();
                        }

                        public char[][] getPackageName() {
                            return ((CompilationUnit) unit).getPackageName();
                        }

                        public char[] getFileName() {
                            return ((CompilationUnit) unit).getFileName();
                        }

                        public boolean ignoreOptionalProblems() {
                            return false;
                        }
                    }, true /*full parse to find local elements*/);
            org.aspectj.org.eclipse.jdt.core.compiler.IProblem[] problems = unitDec.compilationResult.problems;
            if (problems != null) {
                for (int i = 0; i < problems.length; i++) {
                    org.aspectj.org.eclipse.jdt.core.compiler.IProblem problem = problems[i];
                    if (problem == null)
                        continue;
                    ((IProblemRequestor) delegate)
                            .acceptProblem(
                                    new DefaultProblem(problem.getOriginatingFileName(), problem.getMessage(),
                                            problem.getID(), problem.getArguments(),
                                            problem.isError() ? ProblemSeverities.Error
                                                    : ProblemSeverities.Warning,
                                            problem.getSourceStart(), problem.getSourceEnd(),
                                            problem.getSourceLineNumber(), 0)); // unknown column
                }
            }
        } catch (JavaModelException e) {
        }
    }
}

From source file:org.eclipse.jdt.internal.core.CompilationUnit.java

License:Open Source License

protected boolean buildStructure(OpenableElementInfo info, final IProgressMonitor pm, Map newElements,
        IResource underlyingResource) throws JavaModelException {
    CompilationUnitElementInfo unitInfo = (CompilationUnitElementInfo) info;

    // ensure buffer is opened
    IBuffer buffer = getBufferManager().getBuffer(CompilationUnit.this);
    if (buffer == null) {
        openBuffer(pm, unitInfo); // open buffer independently from the info, since we are building the info
    }// ww w  .  jav  a 2  s  .  c  om

    // generate structure and compute syntax problems if needed
    CompilationUnitStructureRequestor requestor = new CompilationUnitStructureRequestor(this, unitInfo,
            newElements);
    JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = getPerWorkingCopyInfo();
    IJavaProject project = getJavaProject();

    boolean createAST;
    boolean resolveBindings;
    int reconcileFlags;
    HashMap problems;
    if (info instanceof ASTHolderCUInfo) {
        ASTHolderCUInfo astHolder = (ASTHolderCUInfo) info;
        createAST = astHolder.astLevel != NO_AST;
        resolveBindings = astHolder.resolveBindings;
        reconcileFlags = astHolder.reconcileFlags;
        problems = astHolder.problems;
    } else {
        createAST = false;
        resolveBindings = false;
        reconcileFlags = 0;
        problems = null;
    }

    boolean computeProblems = perWorkingCopyInfo != null && perWorkingCopyInfo.isActive() && project != null
            && JavaProject.hasJavaNature(project.getProject());
    IProblemFactory problemFactory = new DefaultProblemFactory();
    Map options = project == null ? JavaCore.getOptions() : project.getOptions(true);
    if (!computeProblems) {
        // disable task tags checking to speed up parsing
        options.put(JavaCore.COMPILER_TASK_TAGS, ""); //$NON-NLS-1$
    }
    CompilerOptions compilerOptions = new CompilerOptions(options);
    compilerOptions.ignoreMethodBodies = (reconcileFlags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0;
    SourceElementParser parser = new SourceElementParser(requestor, problemFactory, compilerOptions,
            true/*report local declarations*/,
            !createAST /*optimize string literals only if not creating a DOM AST*/);
    parser.reportOnlyOneSyntaxError = !computeProblems;
    parser.setMethodsFullRecovery(true);
    parser.setStatementsRecovery((reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);

    if (!computeProblems && !resolveBindings && !createAST) // disable javadoc parsing if not computing problems, not resolving and not creating ast
        parser.javadocParser.checkDocComment = false;
    requestor.parser = parser;

    // update timestamp (might be IResource.NULL_STAMP if original does not exist)
    if (underlyingResource == null) {
        underlyingResource = getResource();
    }
    // underlying resource is null in the case of a working copy on a class file in a jar
    if (underlyingResource != null)
        unitInfo.timestamp = ((IFile) underlyingResource).getModificationStamp();

    // compute other problems if needed
    CompilationUnitDeclaration compilationUnitDeclaration = null;
    CompilationUnit source = cloneCachingContents();
    try {
        if (computeProblems) {
            if (problems == null) {
                // report problems to the problem requestor
                problems = new HashMap();
                compilationUnitDeclaration = CompilationUnitProblemFinder.process(source, parser, this.owner,
                        problems, createAST, reconcileFlags, pm);
                try {
                    perWorkingCopyInfo.beginReporting();
                    for (Iterator iteraror = problems.values().iterator(); iteraror.hasNext();) {
                        CategorizedProblem[] categorizedProblems = (CategorizedProblem[]) iteraror.next();
                        if (categorizedProblems == null)
                            continue;
                        for (int i = 0, length = categorizedProblems.length; i < length; i++) {
                            perWorkingCopyInfo.acceptProblem(categorizedProblems[i]);
                        }
                    }
                } finally {
                    perWorkingCopyInfo.endReporting();
                }
            } else {
                // collect problems
                compilationUnitDeclaration = CompilationUnitProblemFinder.process(source, parser, this.owner,
                        problems, createAST, reconcileFlags, pm);
            }
        } else {
            compilationUnitDeclaration = parser.parseCompilationUnit(source,
                    true /*full parse to find local elements*/, pm);
        }

        if (createAST) {
            int astLevel = ((ASTHolderCUInfo) info).astLevel;
            org.eclipse.jdt.core.dom.CompilationUnit cu = AST.convertCompilationUnit(astLevel,
                    compilationUnitDeclaration, options, computeProblems, source, reconcileFlags, pm);
            ((ASTHolderCUInfo) info).ast = cu;
        }
    } finally {
        if (compilationUnitDeclaration != null) {
            compilationUnitDeclaration.cleanUp();
        }
    }

    return unitInfo.isStructureKnown();
}