Example usage for org.eclipse.jdt.core IJavaProject exists

List of usage examples for org.eclipse.jdt.core IJavaProject exists

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaProject exists.

Prototype

boolean exists();

Source Link

Document

Returns whether this Java element exists in the model.

Usage

From source file:org.eclipse.mylyn.internal.java.ui.search.AbstractJavaRelationProvider.java

License:Open Source License

private IJavaSearchScope createJavaSearchScope(IJavaElement element, int degreeOfSeparation) {
    Set<IInteractionElement> landmarks = ContextCore.getContextManager().getActiveLandmarks();
    List<IInteractionElement> interestingElements = ContextCore.getContextManager().getActiveContext()
            .getInteresting();//from  ww  w .  j  a v a2 s.c o  m

    Set<IJavaElement> searchElements = new HashSet<IJavaElement>();
    int includeMask = IJavaSearchScope.SOURCES;
    if (degreeOfSeparation == 1) {
        for (IInteractionElement landmark : landmarks) {
            AbstractContextStructureBridge bridge = ContextCore.getStructureBridge(landmark.getContentType());
            if (includeNodeInScope(landmark, bridge)) {
                Object o = bridge.getObjectForHandle(landmark.getHandleIdentifier());
                if (o instanceof IJavaElement) {
                    IJavaElement landmarkElement = (IJavaElement) o;
                    if (landmarkElement.exists()) {
                        if (landmarkElement instanceof IMember && !landmark.getInterest().isPropagated()) {
                            searchElements.add(((IMember) landmarkElement).getCompilationUnit());
                        } else if (landmarkElement instanceof ICompilationUnit) {
                            searchElements.add(landmarkElement);
                        }
                    }
                }
            }
        }
    } else if (degreeOfSeparation == 2) {
        for (IInteractionElement interesting : interestingElements) {
            AbstractContextStructureBridge bridge = ContextCore
                    .getStructureBridge(interesting.getContentType());
            if (includeNodeInScope(interesting, bridge)) {
                Object object = bridge.getObjectForHandle(interesting.getHandleIdentifier());
                if (object instanceof IJavaElement) {
                    IJavaElement interestingElement = (IJavaElement) object;
                    if (interestingElement.exists()) {
                        if (interestingElement instanceof IMember
                                && !interesting.getInterest().isPropagated()) {
                            searchElements.add(((IMember) interestingElement).getCompilationUnit());
                        } else if (interestingElement instanceof ICompilationUnit) {
                            searchElements.add(interestingElement);
                        }
                    }
                }
            }
        }
    } else if (degreeOfSeparation == 3 || degreeOfSeparation == 4) {
        for (IInteractionElement interesting : interestingElements) {
            AbstractContextStructureBridge bridge = ContextCore
                    .getStructureBridge(interesting.getContentType());
            if (includeNodeInScope(interesting, bridge)) {
                // TODO what to do when the element is not a java element,
                // how determine if a javaProject?
                IResource resource = ResourcesUiBridgePlugin.getDefault().getResourceForElement(interesting,
                        true);
                if (resource != null) {
                    IProject project = resource.getProject();
                    if (project != null && JavaProject.hasJavaNature(project) && project.exists()) {
                        IJavaProject javaProject = JavaCore.create(project);// ((IJavaElement)o).getJavaProject();
                        if (javaProject != null && javaProject.exists()) {
                            searchElements.add(javaProject);
                        }
                    }
                }
            }
        }
        if (degreeOfSeparation == 4) {

            includeMask = IJavaSearchScope.SOURCES | IJavaSearchScope.APPLICATION_LIBRARIES
                    | IJavaSearchScope.SYSTEM_LIBRARIES;
        }
    } else if (degreeOfSeparation == 5) {
        return SearchEngine.createWorkspaceScope();
    }

    if (searchElements.size() == 0) {
        return null;
    } else {
        IJavaElement[] elements = new IJavaElement[searchElements.size()];
        int j = 0;
        for (IJavaElement searchElement : searchElements) {
            elements[j] = searchElement;
            j++;
        }
        return SearchEngine.createJavaSearchScope(elements, includeMask);
    }
}

From source file:org.eclipse.objectteams.otdt.internal.ui.wizards.listeners.NewTypeWizardPageListener.java

License:Open Source License

private IType resolveSuperTypeName(IJavaProject jproject, String supertypeName) throws JavaModelException {
    if (!jproject.exists()) {
        return null;
    }/*from   w  w  w  . j  a v  a  2 s .  c o  m*/
    IType supertype = null;

    //TODO (kaschja): handle case of external defined role class        
    //innerclass (internal defined role class)
    if ((getObservedPage().getEnclosingType() != null) && (getObservedPage().isInlineTypeSelected())) {
        // search in the context of the enclosing type
        IType enclosingType = getObservedPage().getEnclosingType();

        String[][] res = enclosingType.resolveType(supertypeName);
        if (res != null && res.length > 0) {
            supertype = jproject.findType(res[0][0], res[0][1]);
        }
    } else {
        IPackageFragment currPack = getObservedPage().getPackageFragment();
        if (currPack != null) {
            String packName = currPack.getElementName();
            // search in own package
            if (!currPack.isDefaultPackage()) {
                supertype = jproject.findType(packName, supertypeName);
            }
            // search in java.lang
            if (supertype == null && !"java.lang".equals(packName)) //$NON-NLS-1$
            {
                supertype = jproject.findType("java.lang", supertypeName); //$NON-NLS-1$
            }
        }
        // search fully qualified
        if (supertype == null) {
            supertype = jproject.findType(supertypeName);
        }
    }
    return supertype;
}

From source file:org.eclipse.objectteams.otdt.tests.AbstractJavaModelTests.java

License:Open Source License

protected void deleteProject(IJavaProject project) throws CoreException {
    if (project.exists() && !project.isOpen()) { // force opening so that project can be deleted without logging (see bug 23629)
        project.open(null);/*from  ww  w.  ja v  a  2 s.c  om*/
    }
    deleteResource(project.getProject());
}

From source file:org.eclipse.objectteams.otdt.ui.tests.core.ProjectTestSetup.java

License:Open Source License

protected void setUp() throws Exception {
    super.setUp();

    IJavaProject project = getProject();
    if (project.exists()) { // allow nesting of ProjectTestSetups
        return;// w  w w.  j  a  v  a  2s  .  c om
    }

    fAutobuilding = CoreUtility.setAutoBuilding(false);
    //{ObjectTeams: create an OT project and keep otre.jar (don't overwrite with setRawClasspath)
    /* orig: 
          fJProject= JavaProjectHelper.createJavaProject(PROJECT_NAME, "bin");
          fJProject.setRawClasspath(getDefaultClasspath(), null);
      :giro */
    fJProject = org.eclipse.objectteams.otdt.ui.tests.util.JavaProjectHelper.createOTJavaProject(PROJECT_NAME,
            "bin");
    JavaProjectHelper.addRTJar(fJProject);
    //gbr}

    TestOptions.initializeProjectOptions(fJProject);

    JavaCore.setOptions(TestOptions.getDefaultOptions());
    TestOptions.initializeCodeGenerationOptions();
    JavaPlugin.getDefault().getCodeTemplateStore().load();
}

From source file:org.eclipse.pde.api.tools.internal.builder.ApiAnalysisBuilder.java

License:Open Source License

/**
 * Returns the complete listing of required projects from the classpath of
 * the backing project//from  w w w .j a  va  2 s . co  m
 * 
 * @param includeBinaryPrerequisites
 * @return the list of projects required
 * @throws CoreException
 */
IProject[] getRequiredProjects(boolean includebinaries) throws CoreException {
    IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
    if (this.currentproject == null || workspaceRoot == null) {
        return new IProject[0];
    }
    ArrayList<IProject> projects = new ArrayList<IProject>();
    try {
        IJavaProject javaProject = JavaCore.create(this.currentproject);
        HashSet<IPath> blocations = new HashSet<IPath>();
        blocations.add(javaProject.getOutputLocation());
        this.output_locs.put(this.currentproject, blocations);
        HashSet<IPath> slocations = new HashSet<IPath>();
        IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
        for (int i = 0; i < roots.length; i++) {
            if (roots[i].isArchive()) {
                continue;
            }
            slocations.add(roots[i].getPath());
        }
        this.src_locs.put(this.currentproject, slocations);
        IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
        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 (isOptional(entry) && !p.hasNature(ApiPlugin.NATURE_ID)) {// except
                    // if
                    // entry
                    // is
                    // optional
                    p = null;
                }
                break;
            }
            case IClasspathEntry.CPE_LIBRARY: {
                if (includebinaries && path.segmentCount() > 1) {
                    // 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;
                    }
                }
                break;
            }
            case IClasspathEntry.CPE_SOURCE: {
                IPath entrypath = entry.getOutputLocation();
                if (entrypath != null) {
                    blocations.add(entrypath);
                }
                break;
            }
            default: {
                break;
            }
            }
            if (p != null && !projects.contains(p)) {
                projects.add(p);
                // try to derive all of the output locations for each of the
                // projects
                javaProject = JavaCore.create(p);
                HashSet<IPath> bins = new HashSet<IPath>();
                HashSet<IPath> srcs = new HashSet<IPath>();
                if (javaProject.exists()) {
                    bins.add(javaProject.getOutputLocation());
                    IClasspathEntry[] source = javaProject.getRawClasspath();
                    IPath entrypath = null;
                    for (int j = 0; j < source.length; j++) {
                        if (source[j].getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                            srcs.add(source[j].getPath());
                            entrypath = source[j].getOutputLocation();
                            if (entrypath != null) {
                                bins.add(entrypath);
                            }
                        }
                    }
                    this.output_locs.put(p, bins);
                    this.src_locs.put(p, srcs);
                }
            }
        }
    } catch (JavaModelException e) {
        return new IProject[0];
    }
    IProject[] result = new IProject[projects.size()];
    projects.toArray(result);
    return result;
}

From source file:org.eclipse.pde.internal.core.builders.BuildErrorReporter.java

License:Open Source License

private void validateBuild(IBuild build) {

    IBuildEntry binIncludes = null;//from w  w w.j a  va2s  .c  om
    IBuildEntry binExcludes = null;
    IBuildEntry srcIncludes = null;
    IBuildEntry srcExcludes = null;
    IBuildEntry jarsExtra = null;
    IBuildEntry bundleList = null;
    IBuildEntry javacSource = null;
    IBuildEntry javacTarget = null;
    IBuildEntry jreCompilationProfile = null;
    IBuildEntry javaProjectWarnings = null;
    ArrayList<IBuildEntry> javacWarnings = new ArrayList<IBuildEntry>();
    ArrayList<IBuildEntry> javacErrors = new ArrayList<IBuildEntry>();
    ArrayList<IBuildEntry> sourceEntries = new ArrayList<IBuildEntry>(1);
    ArrayList<String> sourceEntryKeys = new ArrayList<String>(1);
    ArrayList<IBuildEntry> outputEntries = new ArrayList<IBuildEntry>(1);
    Map<String, String> encodingEntries = new HashMap<String, String>();
    IBuildEntry[] entries = build.getBuildEntries();
    for (int i = 0; i < entries.length; i++) {
        String name = entries[i].getName();
        if (entries[i].getTokens().length == 0)
            prepareError(name, null, PDECoreMessages.BuildErrorReporter_emptyEntry, PDEMarkerFactory.B_REMOVAL,
                    PDEMarkerFactory.CAT_FATAL);
        else if (name.equals(PROPERTY_BIN_INCLUDES))
            binIncludes = entries[i];
        else if (name.equals(PROPERTY_BIN_EXCLUDES))
            binExcludes = entries[i];
        else if (name.equals(PROPERTY_SRC_INCLUDES))
            srcIncludes = entries[i];
        else if (name.equals(PROPERTY_SRC_EXCLUDES))
            srcExcludes = entries[i];
        else if (name.equals(PROPERTY_JAVAC_SOURCE))
            javacSource = entries[i];
        else if (name.equals(PROPERTY_JAVAC_TARGET))
            javacTarget = entries[i];
        else if (name.equals(PROPERTY_PROJECT_SETTINGS))
            javaProjectWarnings = entries[i];
        else if (name.equals(PROPERTY_JRE_COMPILATION_PROFILE))
            jreCompilationProfile = entries[i];
        else if (name.startsWith(PROPERTY_JAVAC_WARNINGS_PREFIX))
            javacWarnings.add(entries[i]);
        else if (name.startsWith(PROPERTY_JAVAC_ERRORS_PREFIX))
            javacErrors.add(entries[i]);
        else if (name.startsWith(PROPERTY_SOURCE_PREFIX))
            sourceEntries.add(entries[i]);
        else if (name.startsWith(PROPERTY_OUTPUT_PREFIX))
            outputEntries.add(entries[i]);
        else if (name.startsWith(PROPERTY_JAVAC_DEFAULT_ENCODING_PREFIX))
            encodingEntries.put(entries[i].getName(), entries[i].getTokens()[0]);
        else if (name.equals(PROPERTY_JAR_EXTRA_CLASSPATH))
            jarsExtra = entries[i];
        else if (name.equals(IBuildEntry.SECONDARY_DEPENDENCIES))
            bundleList = entries[i];
        else if (name.equals(PROPERTY_CUSTOM)) {
            String[] tokens = entries[i].getTokens();
            if (tokens.length == 1 && tokens[0].equalsIgnoreCase("true")) //$NON-NLS-1$
                // nothing to validate in custom builds
                return;
        }

        // non else if statement to catch all names
        if (name.startsWith(PROPERTY_SOURCE_PREFIX))
            sourceEntryKeys.add(entries[i].getName());
    }

    // validation not relying on build flag
    if (fClasspathSeverity != CompilerFlags.IGNORE) {
        if (bundleList != null)
            validateDependencyManagement(bundleList);
    }

    if (jarsExtra != null)
        validateJarsExtraClasspath(jarsExtra);
    validateIncludes(binIncludes, sourceEntryKeys, fBinInclSeverity);
    validateIncludes(binExcludes, sourceEntryKeys, fBinInclSeverity);
    validateIncludes(srcIncludes, sourceEntryKeys, fSrcInclSeverity);
    validateIncludes(srcExcludes, sourceEntryKeys, fSrcInclSeverity);
    validateSourceFoldersInSrcIncludes(srcIncludes);

    try {
        IJavaProject jp = JavaCore.create(fProject);
        if (jp.exists()) {
            IClasspathEntry[] cpes = jp.getRawClasspath();
            validateMissingLibraries(sourceEntryKeys, cpes);
            validateSourceEntries(sourceEntries, srcExcludes, cpes);
            SourceEntryErrorReporter srcEntryErrReporter = new SourceEntryErrorReporter(fFile, build);
            srcEntryErrReporter.initialize(sourceEntries, outputEntries, cpes, fProject);
            srcEntryErrReporter.validate();
            ArrayList<BuildProblem> problems = srcEntryErrReporter.getProblemList();
            for (int i = 0; i < problems.size(); i++) {
                if (!fProblemList.contains(problems.get(i))) {
                    fProblemList.add(problems.get(i));
                }
            }

        }
    } catch (JavaModelException e) {
    }

    validateMissingSourceInBinIncludes(binIncludes, sourceEntryKeys, build);
    validateBinIncludes(binIncludes);
    validateExecutionEnvironment(javacSource, javacTarget, jreCompilationProfile, javacWarnings, javacErrors,
            getSourceLibraries(sourceEntries));
    validateJavaCompilerSettings(javaProjectWarnings);
}

From source file:org.eclipse.pde.internal.core.builders.BuildErrorReporter.java

License:Open Source License

/**
 * Matches the javacSource, javacTarget, javacWarnings, javacErrors and jre.compilation.prile entries in build.properties with the 
 * project specific Java Compiler properties and reports the errors found.
 * //from   w ww . jav  a  2 s .  co m
 * @param javacSourceEntry
 * @param javacTargetEntry
 * @param jreCompilationProfileEntry
 * @param javacWarningsEntries
 * @param javacErrorsEntries 
 * @param libraryNames list of library names (javacWarnings/javacErrors require an entry for each source library)
 */
private void validateExecutionEnvironment(IBuildEntry javacSourceEntry, IBuildEntry javacTargetEntry,
        IBuildEntry jreCompilationProfileEntry, ArrayList<IBuildEntry> javacWarningsEntries,
        ArrayList<IBuildEntry> javacErrorsEntries, List<String> libraryNames) {
    // if there is no source to compile, don't worry about compiler settings
    IJavaProject project = JavaCore.create(fProject);
    if (project.exists()) {
        IClasspathEntry[] classpath = null;
        try {
            classpath = project.getRawClasspath();
        } catch (JavaModelException e) {
            PDECore.log(e);
            return;
        }
        boolean source = false;
        for (int i = 0; i < classpath.length; i++) {
            IClasspathEntry cpe = classpath[i];
            if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                source = true;
            }
        }
        if (!source) {
            return;
        }

        String projectComplianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, false);

        if (projectComplianceLevel != null) {

            IPluginModelBase model = PluginRegistry.findModel(fProject);
            String[] execEnvs = null;
            if (model != null) {
                BundleDescription bundleDesc = model.getBundleDescription();
                if (bundleDesc != null) {
                    execEnvs = bundleDesc.getExecutionEnvironments();
                }
            }

            if (execEnvs == null || execEnvs.length == 0) {
                return;
            }

            //PDE Build uses top most entry to build the plug-in
            String execEnv = execEnvs[0];

            String projectSourceCompatibility = project.getOption(JavaCore.COMPILER_SOURCE, true);
            String projectClassCompatibility = project.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
                    true);
            if (projectComplianceLevel
                    .equals(findMatchingEE(projectSourceCompatibility, projectClassCompatibility, false))
                    && execEnv.equals(
                            findMatchingEE(projectSourceCompatibility, projectClassCompatibility, true))) {
                return; //The project compliance settings matches the BREE
            }

            Map<?, ?> defaultComplianceOptions = new HashMap<Object, Object>();
            JavaCore.setComplianceOptions(projectComplianceLevel, defaultComplianceOptions);

            //project compliance does not match the BREE
            String projectJavaCompatibility = findMatchingEE(projectSourceCompatibility,
                    projectClassCompatibility, true);
            String message = null;
            if (projectJavaCompatibility != null) {
                if (jreCompilationProfileEntry == null) {
                    message = NLS.bind(
                            PDECoreMessages.BuildErrorReporter_ProjectSpecificJavaComplianceMissingEntry,
                            PROPERTY_JRE_COMPILATION_PROFILE,
                            PDECoreMessages.BuildErrorReporter_CompilercomplianceLevel);
                    prepareError(PROPERTY_JRE_COMPILATION_PROFILE, projectJavaCompatibility, message,
                            PDEMarkerFactory.B_JAVA_ADDDITION, fJavaComplianceSeverity,
                            PDEMarkerFactory.CAT_EE);
                } else {
                    if (!projectJavaCompatibility.equalsIgnoreCase(jreCompilationProfileEntry.getTokens()[0])) {
                        message = NLS.bind(
                                PDECoreMessages.BuildErrorReporter_ProjectSpecificJavaComplianceDifferentToken,
                                PROPERTY_JRE_COMPILATION_PROFILE,
                                PDECoreMessages.BuildErrorReporter_CompilercomplianceLevel);
                        prepareError(PROPERTY_JRE_COMPILATION_PROFILE, projectJavaCompatibility, message,
                                PDEMarkerFactory.B_REPLACE, fJavaComplianceSeverity, PDEMarkerFactory.CAT_EE);
                    }
                }
            } else {
                // Check source level setting
                if (projectSourceCompatibility.equals(defaultComplianceOptions.get(JavaCore.COMPILER_SOURCE))) {
                    if (javacSourceEntry != null) {
                        message = NLS.bind(
                                PDECoreMessages.BuildErrorReporter_BuildEntryNotRequiredMatchesDefault,
                                PROPERTY_JAVAC_SOURCE, PDECoreMessages.BuildErrorReporter_SourceCompatibility);
                        prepareError(PROPERTY_JAVAC_SOURCE, null, message, PDEMarkerFactory.B_REMOVAL,
                                fJavaComplianceSeverity, PDEMarkerFactory.CAT_EE);
                    }
                } else {
                    if (javacSourceEntry == null) {
                        message = NLS.bind(
                                PDECoreMessages.BuildErrorReporter_ProjectSpecificJavaComplianceMissingEntry,
                                PROPERTY_JAVAC_SOURCE, PDECoreMessages.BuildErrorReporter_SourceCompatibility);
                        prepareError(PROPERTY_JAVAC_SOURCE, projectSourceCompatibility, message,
                                PDEMarkerFactory.B_JAVA_ADDDITION, fJavaComplianceSeverity,
                                PDEMarkerFactory.CAT_EE);
                    } else {
                        if (!projectSourceCompatibility.equalsIgnoreCase(javacSourceEntry.getTokens()[0])) {
                            message = NLS.bind(
                                    PDECoreMessages.BuildErrorReporter_ProjectSpecificJavaComplianceDifferentToken,
                                    PROPERTY_JAVAC_SOURCE,
                                    PDECoreMessages.BuildErrorReporter_SourceCompatibility);
                            prepareError(PROPERTY_JAVAC_SOURCE, projectSourceCompatibility, message,
                                    PDEMarkerFactory.B_REPLACE, fJavaComplianceSeverity,
                                    PDEMarkerFactory.CAT_EE);
                        }
                    }
                }

                // Check target level setting
                if (projectClassCompatibility
                        .equals(defaultComplianceOptions.get(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM))) {
                    if (javacTargetEntry != null) {
                        message = NLS.bind(
                                PDECoreMessages.BuildErrorReporter_BuildEntryNotRequiredMatchesDefault,
                                PROPERTY_JAVAC_TARGET,
                                PDECoreMessages.BuildErrorReporter_GeneratedClassFilesCompatibility);
                        prepareError(PROPERTY_JAVAC_TARGET, null, message, PDEMarkerFactory.B_REMOVAL,
                                fJavaComplianceSeverity, PDEMarkerFactory.CAT_EE);
                    }
                } else {
                    if (javacTargetEntry == null) {
                        message = NLS.bind(
                                PDECoreMessages.BuildErrorReporter_ProjectSpecificJavaComplianceMissingEntry,
                                PROPERTY_JAVAC_TARGET,
                                PDECoreMessages.BuildErrorReporter_GeneratedClassFilesCompatibility);
                        prepareError(PROPERTY_JAVAC_TARGET, projectClassCompatibility, message,
                                PDEMarkerFactory.B_JAVA_ADDDITION, fJavaComplianceSeverity,
                                PDEMarkerFactory.CAT_EE);
                    } else {
                        if (!projectClassCompatibility.equalsIgnoreCase(javacTargetEntry.getTokens()[0])) {
                            message = NLS.bind(
                                    PDECoreMessages.BuildErrorReporter_ProjectSpecificJavaComplianceDifferentToken,
                                    PROPERTY_JAVAC_TARGET,
                                    PDECoreMessages.BuildErrorReporter_GeneratedClassFilesCompatibility);
                            prepareError(PROPERTY_JAVAC_TARGET, projectClassCompatibility, message,
                                    PDEMarkerFactory.B_REPLACE, fJavaComplianceSeverity,
                                    PDEMarkerFactory.CAT_EE);
                        }
                    }
                }
            }

            boolean warnForJavacWarnings = message != null || javacSourceEntry != null
                    || javacTargetEntry != null || jreCompilationProfileEntry != null;
            if (warnForJavacWarnings == false) {
                return;
            }

            checkJavaComplianceSettings(projectComplianceLevel, javacWarningsEntries, javacErrorsEntries,
                    libraryNames);
        }
    }
}

From source file:org.eclipse.pde.internal.core.builders.BuildErrorReporter.java

License:Open Source License

/**
 * Matches the javacWarnings and javacErrors entries in build.properties with the 
 * project specific Java compliance properties and reports the errors found.  Since java
 * compiler settings are set on a per project basis, any special javacWarnings/javacErrors
 * must be set for each library./*from ww  w . j a  v  a  2  s.  c  o m*/
 * 
 * @param complianceLevel the compliance level to check settings against, used to get default values
 * @param javacWarningsEntries list of build entries with the java compiler warnings prefix javacWarnings.
 * @param javacErrorsEntries list of build entries with the java compiler errors prefix javacErrors.
 * @param libraryNames list of String library names
 */
private void checkJavaComplianceSettings(String complianceLevel, ArrayList<IBuildEntry> javacWarningsEntries,
        ArrayList<IBuildEntry> javacErrorsEntries, List<String> libraryNames) {
    List<String> complianceWarnSettings = new ArrayList<String>(3);
    List<String> complianceErrorSettings = new ArrayList<String>(3);

    IJavaProject project = JavaCore.create(fProject);
    if (project.exists()) {

        Map<?, ?> defaultComplianceOptions = new HashMap<Object, Object>();
        JavaCore.setComplianceOptions(complianceLevel, defaultComplianceOptions);

        //look for assertIdentifier and enumIdentifier entries in javacWarnings. If any is present let it be, if not warn.
        String assertIdentifier = project.getOption(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, false);
        String defaultAssert = (String) defaultComplianceOptions.get(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER);
        if (assertIdentifier != null && !assertIdentifier.equalsIgnoreCase(defaultAssert)) {
            if (JavaCore.ERROR.equalsIgnoreCase(assertIdentifier)) {
                complianceErrorSettings.add(ASSERT_IDENTIFIER);
            } else if (JavaCore.WARNING.equalsIgnoreCase(assertIdentifier)) {
                complianceWarnSettings.add(ASSERT_IDENTIFIER);
            }
        }

        String enumIdentifier = project.getOption(JavaCore.COMPILER_PB_ENUM_IDENTIFIER, false);
        String defaultEnum = (String) defaultComplianceOptions.get(JavaCore.COMPILER_PB_ENUM_IDENTIFIER);
        if (enumIdentifier != null && !enumIdentifier.equalsIgnoreCase(defaultEnum)) {
            if (JavaCore.ERROR.equalsIgnoreCase(enumIdentifier)) {
                complianceErrorSettings.add(ENUM_IDENTIFIER);
            } else if (JavaCore.WARNING.equalsIgnoreCase(enumIdentifier)) {
                complianceWarnSettings.add(ENUM_IDENTIFIER);
            }
        }

        // If a warnings entry is required, make sure there is one for each library with the correct content
        if (complianceWarnSettings.size() > 0) {
            for (Iterator<String> iterator = libraryNames.iterator(); iterator.hasNext();) {
                String libName = iterator.next();
                IBuildEntry matchingEntry = null;
                for (Iterator<IBuildEntry> iterator2 = javacWarningsEntries.iterator(); iterator2.hasNext();) {
                    IBuildEntry candidate = iterator2.next();
                    if (candidate.getName().equals(PROPERTY_JAVAC_WARNINGS_PREFIX + libName)) {
                        matchingEntry = candidate;
                        break;
                    }
                }
                if (matchingEntry == null) {
                    String missingTokens = ""; //$NON-NLS-1$
                    for (Iterator<String> iterator2 = complianceWarnSettings.iterator(); iterator2.hasNext();) {
                        String currentIdentifier = iterator2.next();
                        missingTokens = join(missingTokens, '-' + currentIdentifier);
                    }
                    String message = NLS.bind(
                            PDECoreMessages.BuildErrorReporter_ProjectSpecificJavaComplianceMissingEntry,
                            PROPERTY_JAVAC_WARNINGS_PREFIX + libName);
                    prepareError(PROPERTY_JAVAC_WARNINGS_PREFIX + libName, missingTokens, message,
                            PDEMarkerFactory.B_JAVA_ADDDITION, fJavaComplianceSeverity,
                            PDEMarkerFactory.CAT_EE);
                } else {
                    String missingTokens = ""; //$NON-NLS-1$
                    for (Iterator<String> iterator2 = complianceWarnSettings.iterator(); iterator2.hasNext();) {
                        String currentIdentifier = iterator2.next();
                        if (!matchingEntry.contains(currentIdentifier)
                                && !matchingEntry.contains('+' + currentIdentifier)
                                && !matchingEntry.contains('-' + currentIdentifier)) {
                            join(missingTokens, '-' + currentIdentifier);
                        }
                    }
                    if (missingTokens.length() > 0) {
                        String message = NLS.bind(
                                PDECoreMessages.BuildErrorReporter_ProjectSpecificJavaComplianceDifferentToken,
                                PROPERTY_JAVAC_WARNINGS_PREFIX + libName);
                        prepareError(PROPERTY_JAVAC_WARNINGS_PREFIX + libName, missingTokens, message,
                                PDEMarkerFactory.B_JAVA_ADDDITION, fJavaComplianceSeverity,
                                PDEMarkerFactory.CAT_EE);
                    }
                }
            }
        }

        // If a warnings entry is required, make sure there is one for each library with the correct content
        if (complianceErrorSettings.size() > 0) {
            for (Iterator<String> iterator = libraryNames.iterator(); iterator.hasNext();) {
                String libName = iterator.next();
                IBuildEntry matchingEntry = null;
                for (Iterator<IBuildEntry> iterator2 = javacErrorsEntries.iterator(); iterator2.hasNext();) {
                    IBuildEntry candidate = iterator2.next();
                    if (candidate.getName().equals(PROPERTY_JAVAC_ERRORS_PREFIX + libName)) {
                        matchingEntry = candidate;
                        break;
                    }
                }
                if (matchingEntry == null) {
                    String missingTokens = ""; //$NON-NLS-1$
                    for (Iterator<String> iterator2 = complianceErrorSettings.iterator(); iterator2
                            .hasNext();) {
                        String currentIdentifier = iterator2.next();
                        missingTokens = join(missingTokens, '-' + currentIdentifier);
                    }
                    String message = NLS.bind(
                            PDECoreMessages.BuildErrorReporter_ProjectSpecificJavaComplianceMissingEntry,
                            PROPERTY_JAVAC_ERRORS_PREFIX + libName);
                    prepareError(PROPERTY_JAVAC_ERRORS_PREFIX + libName, missingTokens, message,
                            PDEMarkerFactory.B_JAVA_ADDDITION, fJavaComplianceSeverity,
                            PDEMarkerFactory.CAT_EE);
                } else {
                    String missingTokens = ""; //$NON-NLS-1$
                    for (Iterator<String> iterator2 = complianceErrorSettings.iterator(); iterator2
                            .hasNext();) {
                        String currentIdentifier = iterator2.next();
                        if (!matchingEntry.contains(currentIdentifier)
                                && !matchingEntry.contains('+' + currentIdentifier)
                                && !matchingEntry.contains('-' + currentIdentifier)) {
                            missingTokens = join(missingTokens, '-' + currentIdentifier);
                        }
                    }
                    if (missingTokens.length() > 0) {
                        String message = NLS.bind(
                                PDECoreMessages.BuildErrorReporter_ProjectSpecificJavaComplianceDifferentToken,
                                PROPERTY_JAVAC_ERRORS_PREFIX + libName);
                        prepareError(PROPERTY_JAVAC_ERRORS_PREFIX + libName, missingTokens, message,
                                PDEMarkerFactory.B_JAVA_ADDDITION, fJavaComplianceSeverity,
                                PDEMarkerFactory.CAT_EE);
                    }
                }
            }
        }
    }
}

From source file:org.eclipse.pde.internal.core.builders.BuildErrorReporter.java

License:Open Source License

private void validateSourceFoldersInSrcIncludes(IBuildEntry includes) {
    if (includes == null)
        return;//w w  w.ja  v  a2 s . c o m

    List<IPath> sourceFolderList = new ArrayList<IPath>(0);
    try {
        IJavaProject javaProject = JavaCore.create(fProject);
        if (javaProject.exists()) {
            IClasspathEntry[] classPathEntries = javaProject.getResolvedClasspath(true);

            for (int index = 0; index < classPathEntries.length; index++) {
                if (classPathEntries[index].getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                    sourceFolderList.add(classPathEntries[index].getPath());
                }
            }
        }
    } catch (JavaModelException e) { //do nothing
    }

    List<String> reservedTokens = Arrays.asList(RESERVED_NAMES);

    String[] tokens = includes.getTokens();
    for (int i = 0; i < tokens.length; i++) {
        IResource res = fProject.findMember(tokens[i]);
        if (res == null)
            continue;
        String errorMessage = null;
        if (sourceFolderList.contains(res.getFullPath())) {
            errorMessage = PDECoreMessages.BuildErrorReporter_srcIncludesSourceFolder;
        } else if (tokens[i].startsWith(".") //$NON-NLS-1$
                || reservedTokens.contains(res.getName().toString().toLowerCase())) {
            errorMessage = NLS.bind(PDECoreMessages.BuildErrorReporter_srcIncludesSourceFolder1, res.getName());
        }

        if (errorMessage != null) {
            prepareError(includes.getName(), tokens[i], errorMessage, PDEMarkerFactory.B_REMOVAL,
                    fSrcInclSeverity, PDEMarkerFactory.CAT_OTHER);
        }
    }

}

From source file:org.eclipse.pde.internal.core.builders.BuildErrorReporter.java

License:Open Source License

/**
 * Checks that if the project has java compiler settings that build.properties contains a use project settings
 * entry so that the compiler picks up the settings using the .pref file.
 * /*from   w  w w . j av a 2  s. com*/
 * @param useJavaProjectSettings a build entry for using the project's compiler warning preferences file
 */
private void validateJavaCompilerSettings(IBuildEntry useJavaProjectSettings) {
    // Check if the project has compiler warnings set
    IJavaProject project = JavaCore.create(fProject);
    if (project.exists()) {
        Map<?, ?> options = project.getOptions(false);
        // If project specific options are turned on, all options will be stored.  Only need to check if at least one compiler option is set. Currently using the second option on the property page.
        if (options.containsKey(JavaCore.COMPILER_PB_INDIRECT_STATIC_ACCESS)) {
            if (useJavaProjectSettings != null) {
                boolean entryCorrect = false;
                String[] tokens = useJavaProjectSettings.getTokens();
                if (tokens != null && tokens.length == 1) {
                    if (Boolean.TRUE.toString().equalsIgnoreCase(tokens[0])) {
                        // True is valid if the bundle root is the default (the project)
                        entryCorrect = fProject.equals(PDEProject.getBundleRoot(fProject));
                    } else {
                        IPath prefFile = null;
                        prefFile = new Path(tokens[0]);
                        if (prefFile.isAbsolute()) {
                            entryCorrect = prefFile.toFile().exists();
                        } else {
                            IContainer root = PDEProject.getBundleRoot(fProject);
                            entryCorrect = root.getFile(prefFile).exists();
                        }
                    }
                }
                if (!entryCorrect) {
                    String token = null;
                    String message = null;
                    IContainer root = PDEProject.getBundleRoot(fProject);
                    if (fProject.equals(root)) {
                        // Default project root, just use 'true'
                        token = Boolean.TRUE.toString();
                        message = NLS.bind(PDECoreMessages.BuildErrorReporter_buildEntryMissingValidPath,
                                PROPERTY_PROJECT_SETTINGS);
                    } else {
                        // Non default bundle root, make a relative path
                        IPath prefFile = fProject.getFullPath().append(".settings") //$NON-NLS-1$
                                .append(JavaCore.PLUGIN_ID + ".prefs"); //$NON-NLS-1$
                        prefFile = prefFile.makeRelativeTo(root.getFullPath());
                        token = prefFile.toString();
                        message = NLS.bind(
                                PDECoreMessages.BuildErrorReporter_buildEntryMissingValidRelativePath,
                                PROPERTY_PROJECT_SETTINGS);
                    }
                    prepareError(PROPERTY_PROJECT_SETTINGS, token, message, PDEMarkerFactory.B_REPLACE,
                            fJavaCompilerSeverity, PDEMarkerFactory.CAT_EE);
                }
            } else {
                String token = null;
                IContainer root = PDEProject.getBundleRoot(fProject);
                if (fProject.equals(root)) {
                    // Default project root, just use 'true'
                    token = Boolean.TRUE.toString();
                } else {
                    // Non default bundle root, make a relative path
                    IPath prefFile = fProject.getFullPath().append(".settings") //$NON-NLS-1$
                            .append(JavaCore.PLUGIN_ID + ".prefs"); //$NON-NLS-1$
                    prefFile = prefFile.makeRelativeTo(root.getFullPath());
                    token = prefFile.toString();
                }
                String message = NLS.bind(
                        PDECoreMessages.BuildErrorReporter_buildEntryMissingProjectSpecificSettings,
                        PROPERTY_PROJECT_SETTINGS);
                prepareError(PROPERTY_PROJECT_SETTINGS, token, message, PDEMarkerFactory.B_JAVA_ADDDITION,
                        fJavaCompilerSeverity, PDEMarkerFactory.CAT_EE);
            }
        } else if (useJavaProjectSettings != null) {
            String message = NLS.bind(PDECoreMessages.BuildErrorReporter_buildEntryInvalidWhenNoProjectSettings,
                    PROPERTY_PROJECT_SETTINGS);
            prepareError(PROPERTY_PROJECT_SETTINGS, null, message, PDEMarkerFactory.B_REMOVAL,
                    fJavaCompilerSeverity, PDEMarkerFactory.CAT_EE);
        }
    }
}