Example usage for org.eclipse.jdt.core JavaCore ERROR

List of usage examples for org.eclipse.jdt.core JavaCore ERROR

Introduction

In this page you can find the example usage for org.eclipse.jdt.core JavaCore ERROR.

Prototype

String ERROR

To view the source code for org.eclipse.jdt.core JavaCore ERROR.

Click Source Link

Document

Configurable option value: .

Usage

From source file:com.sabre.buildergenerator.TestHelper.java

License:Open Source License

/**
 * @param projectName name of the project
 * @param sourcePath e.g. "src"//from   w w  w. j ava  2 s .c o m
 * @param javaVMVersion e.g. JavaCore.VERSION_1_6; null indicates default
 * @param targetPlatform e.g. JavaCore.VERSION_1_5; must not be null
 * @throws CoreException error
 * @throws JavaModelException error
 */
@SuppressWarnings("unchecked")
public static IJavaProject createJavaProject(String projectName, String sourcePath, String javaVMVersion,
        String targetPlatform) throws CoreException, JavaModelException {
    // create project
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
    project.create(null);
    project.open(null);

    // create source folder
    IPath srcPath = new Path(sourcePath);
    IFolder srcFolder = project.getFolder(srcPath);
    srcFolder.create(true, true, null);

    // class path
    IClasspathEntry sourceEntry = JavaCore.newSourceEntry(project.getFullPath().append(srcPath));

    IClasspathEntry[] jreLibrary = null;
    if (javaVMVersion != null) {
        vmType: for (IVMInstallType vmInstallType : JavaRuntime.getVMInstallTypes()) {
            for (IVMInstall vmInstall : vmInstallType.getVMInstalls()) {
                if (javaVMVersion.equals(((AbstractVMInstall) vmInstall).getJavaVersion())) {
                    IPath containerPath = new Path(JavaRuntime.JRE_CONTAINER);
                    IPath vmPath = containerPath.append(vmInstall.getVMInstallType().getId())
                            .append(vmInstall.getName());
                    jreLibrary = new IClasspathEntry[] { JavaCore.newContainerEntry(vmPath) };
                    break vmType;
                }
            }
        }
    }
    if (jreLibrary == null) {
        jreLibrary = PreferenceConstants.getDefaultJRELibrary();
    }

    // create java project
    IJavaProject javaProject = JavaCore.create(project);
    IProjectDescription description = project.getDescription();
    String[] natureIds = description.getNatureIds();
    String[] newNatureIds = new String[natureIds.length + 1];
    System.arraycopy(natureIds, 0, newNatureIds, 0, natureIds.length);
    newNatureIds[newNatureIds.length - 1] = JavaCore.NATURE_ID;
    description.setNatureIds(newNatureIds);
    project.setDescription(description, null);

    // create binary folder
    String binName = PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME);
    IFolder binFolder = project.getFolder(binName);
    binFolder.create(IResource.FORCE | IResource.DERIVED, true, null);
    binFolder.setDerived(true);

    project.refreshLocal(IResource.DEPTH_INFINITE, null);

    // set project class path
    javaProject.setRawClasspath(merge(jreLibrary, new IClasspathEntry[] { sourceEntry }),
            binFolder.getFullPath(), null);

    // set options
    Map<String, String> options = javaProject.getOptions(true);
    options.put(JavaCore.COMPILER_COMPLIANCE, targetPlatform);
    options.put(JavaCore.COMPILER_SOURCE, targetPlatform);
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, targetPlatform);
    options.put(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaCore.ERROR);
    options.put(JavaCore.COMPILER_PB_ENUM_IDENTIFIER, JavaCore.ERROR);
    javaProject.setOptions(options);

    return javaProject;
}

From source file:com.siteview.mde.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.// w ww  .  j av  a  2s. 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 javacWarningsEntries,
        ArrayList javacErrorsEntries, List libraryNames) {
    List complianceWarnSettings = new ArrayList(3);
    List complianceErrorSettings = new ArrayList(3);

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

        Map defaultComplianceOptions = new HashMap();
        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 iterator = libraryNames.iterator(); iterator.hasNext();) {
                String libName = (String) iterator.next();
                IBuildEntry matchingEntry = null;
                for (Iterator iterator2 = javacWarningsEntries.iterator(); iterator2.hasNext();) {
                    IBuildEntry candidate = (IBuildEntry) iterator2.next();
                    if (candidate.getName().equals(PROPERTY_JAVAC_WARNINGS_PREFIX + libName)) {
                        matchingEntry = candidate;
                        break;
                    }
                }
                if (matchingEntry == null) {
                    String missingTokens = ""; //$NON-NLS-1$
                    for (Iterator iterator2 = complianceWarnSettings.iterator(); iterator2.hasNext();) {
                        String currentIdentifier = (String) iterator2.next();
                        missingTokens = join(missingTokens, '-' + currentIdentifier);
                    }
                    String message = NLS.bind(
                            MDECoreMessages.BuildErrorReporter_ProjectSpecificJavaComplianceMissingEntry,
                            PROPERTY_JAVAC_WARNINGS_PREFIX + libName);
                    prepareError(PROPERTY_JAVAC_WARNINGS_PREFIX + libName, missingTokens, message,
                            MDEMarkerFactory.B_JAVA_ADDDITION, fJavaComplianceSeverity,
                            MDEMarkerFactory.CAT_EE);
                } else {
                    String missingTokens = ""; //$NON-NLS-1$
                    for (Iterator iterator2 = complianceWarnSettings.iterator(); iterator2.hasNext();) {
                        String currentIdentifier = (String) iterator2.next();
                        if (!matchingEntry.contains(currentIdentifier)
                                && !matchingEntry.contains('+' + currentIdentifier)
                                && !matchingEntry.contains('-' + currentIdentifier)) {
                            join(missingTokens, '-' + currentIdentifier);
                        }
                    }
                    if (missingTokens.length() > 0) {
                        String message = NLS.bind(
                                MDECoreMessages.BuildErrorReporter_ProjectSpecificJavaComplianceDifferentToken,
                                PROPERTY_JAVAC_WARNINGS_PREFIX + libName);
                        prepareError(PROPERTY_JAVAC_WARNINGS_PREFIX + libName, missingTokens, message,
                                MDEMarkerFactory.B_JAVA_ADDDITION, fJavaComplianceSeverity,
                                MDEMarkerFactory.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 iterator = libraryNames.iterator(); iterator.hasNext();) {
                String libName = (String) iterator.next();
                IBuildEntry matchingEntry = null;
                for (Iterator iterator2 = javacErrorsEntries.iterator(); iterator2.hasNext();) {
                    IBuildEntry candidate = (IBuildEntry) iterator2.next();
                    if (candidate.getName().equals(PROPERTY_JAVAC_ERRORS_PREFIX + libName)) {
                        matchingEntry = candidate;
                        break;
                    }
                }
                if (matchingEntry == null) {
                    String missingTokens = ""; //$NON-NLS-1$
                    for (Iterator iterator2 = complianceErrorSettings.iterator(); iterator2.hasNext();) {
                        String currentIdentifier = (String) iterator2.next();
                        missingTokens = join(missingTokens, '-' + currentIdentifier);
                    }
                    String message = NLS.bind(
                            MDECoreMessages.BuildErrorReporter_ProjectSpecificJavaComplianceMissingEntry,
                            PROPERTY_JAVAC_ERRORS_PREFIX + libName);
                    prepareError(PROPERTY_JAVAC_ERRORS_PREFIX + libName, missingTokens, message,
                            MDEMarkerFactory.B_JAVA_ADDDITION, fJavaComplianceSeverity,
                            MDEMarkerFactory.CAT_EE);
                } else {
                    String missingTokens = ""; //$NON-NLS-1$
                    for (Iterator iterator2 = complianceErrorSettings.iterator(); iterator2.hasNext();) {
                        String currentIdentifier = (String) iterator2.next();
                        if (!matchingEntry.contains(currentIdentifier)
                                && !matchingEntry.contains('+' + currentIdentifier)
                                && !matchingEntry.contains('-' + currentIdentifier)) {
                            missingTokens = join(missingTokens, '-' + currentIdentifier);
                        }
                    }
                    if (missingTokens.length() > 0) {
                        String message = NLS.bind(
                                MDECoreMessages.BuildErrorReporter_ProjectSpecificJavaComplianceDifferentToken,
                                PROPERTY_JAVAC_ERRORS_PREFIX + libName);
                        prepareError(PROPERTY_JAVAC_ERRORS_PREFIX + libName, missingTokens, message,
                                MDEMarkerFactory.B_JAVA_ADDDITION, fJavaComplianceSeverity,
                                MDEMarkerFactory.CAT_EE);
                    }
                }
            }
        }
    }
}

From source file:com.siteview.mde.internal.core.ClasspathComputer.java

License:Open Source License

/**
 * Checks if the current value stored in the map is less severe than the given minimum value. If
 * the minimum value is higher, the map will be updated with the minimum. If the minimum value
 * is <code>null</code>, the existing value remains.
 * /* w  w  w  .j  ava  2 s.c  o  m*/
 * @param map the map to check the value in
 * @param key the key to get the current value out of the map
 * @param minimumValue the minimum value allowed or <code>null</code>
 * @param override whether an existing value in the map should be replaced
 */
private static void setMinimumCompliance(Map map, String key, String minimumValue, boolean override) {
    if (minimumValue != null && (override || !map.containsKey(key))) {
        if (fSeverityTable == null) {
            fSeverityTable = new HashMap(3);
            fSeverityTable.put(JavaCore.IGNORE, new Integer(SEVERITY_IGNORE));
            fSeverityTable.put(JavaCore.WARNING, new Integer(SEVERITY_WARNING));
            fSeverityTable.put(JavaCore.ERROR, new Integer(SEVERITY_ERROR));
        }
        String currentValue = (String) map.get(key);
        int current = currentValue != null && fSeverityTable.containsKey(currentValue)
                ? ((Integer) fSeverityTable.get(currentValue)).intValue()
                : 0;
        int minimum = minimumValue != null && fSeverityTable.containsKey(minimumValue)
                ? ((Integer) fSeverityTable.get(minimumValue)).intValue()
                : 0;
        if (current < minimum) {
            map.put(key, minimumValue);
        }
    }
}

From source file:io.sarl.tests.api.WorkbenchTestHelper.java

License:Apache License

/** Make the given project compliant for the given version.
 *
 * @param javaProject the project./*from  ww  w .  j  a  v a2 s . c  o m*/
 * @param javaVersion the Java version.
 */
public static void makeCompliantFor(IJavaProject javaProject, JavaVersion javaVersion) {
    Map<String, String> options = javaProject.getOptions(false);
    String jreLevel;
    switch (javaVersion) {
    case JAVA8:
        jreLevel = JavaCore.VERSION_1_8;
        break;
    case JAVA6:
        jreLevel = JavaCore.VERSION_1_6;
        break;
    case JAVA5:
        jreLevel = JavaCore.VERSION_1_5;
        break;
    case JAVA7:
    default:
        jreLevel = JavaCore.VERSION_1_7;
    }
    options.put(JavaCore.COMPILER_COMPLIANCE, jreLevel);
    options.put(JavaCore.COMPILER_SOURCE, jreLevel);
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, jreLevel);
    options.put(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaCore.ERROR);
    options.put(JavaCore.COMPILER_PB_ENUM_IDENTIFIER, JavaCore.ERROR);
    options.put(JavaCore.COMPILER_CODEGEN_INLINE_JSR_BYTECODE, JavaCore.ENABLED);
    options.put(JavaCore.COMPILER_LOCAL_VARIABLE_ATTR, JavaCore.GENERATE);
    options.put(JavaCore.COMPILER_LINE_NUMBER_ATTR, JavaCore.GENERATE);
    options.put(JavaCore.COMPILER_SOURCE_FILE_ATTR, JavaCore.GENERATE);
    options.put(JavaCore.COMPILER_CODEGEN_UNUSED_LOCAL, JavaCore.PRESERVE);
    javaProject.setOptions(options);
}

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

License:Open Source License

public void acceptResult(CompilationResult result) {
    // In Batch mode, we write out the class files, hold onto the dependency info
    // & additional types and report problems.

    // In Incremental mode, when writing out a class file we need to compare it
    // against the previous file, remembering if structural changes occured.
    // Before reporting the new problems, we need to update the problem count &
    // remove the old problems. Plus delete additional class files that no longer exist.

    SourceFile compilationUnit = (SourceFile) result.getCompilationUnit(); // go directly back to the sourceFile
    if (!this.workQueue.isCompiled(compilationUnit)) {
        this.workQueue.finished(compilationUnit);

        try {//from   ww w .j  a v  a 2s. c  om
            updateProblemsFor(compilationUnit, result); // record compilation problems before potentially adding duplicate errors
            updateTasksFor(compilationUnit, result); // record tasks
        } catch (CoreException e) {
            throw internalException(e);
        }

        if (result.hasInconsistentToplevelHierarchies)
            // ensure that this file is always retrieved from source for the rest of the build
            if (!this.problemSourceFiles.contains(compilationUnit))
                this.problemSourceFiles.add(compilationUnit);

        IType mainType = null;
        String mainTypeName = null;
        String typeLocator = compilationUnit.typeLocator();
        ClassFile[] classFiles = result.getClassFiles();
        int length = classFiles.length;
        ArrayList duplicateTypeNames = null;
        ArrayList definedTypeNames = new ArrayList(length);
        for (int i = 0; i < length; i++) {
            ClassFile classFile = classFiles[i];

            char[][] compoundName = classFile.getCompoundName();
            char[] typeName = compoundName[compoundName.length - 1];
            boolean isNestedType = classFile.isNestedType;

            // Look for a possible collision, if one exists, report an error but do not write the class file
            if (isNestedType) {
                String qualifiedTypeName = new String(classFile.outerMostEnclosingClassFile().fileName());
                if (this.newState.isDuplicateLocator(qualifiedTypeName, typeLocator))
                    continue;
            } else {
                String qualifiedTypeName = new String(classFile.fileName()); // the qualified type name "p1/p2/A"
                if (this.newState.isDuplicateLocator(qualifiedTypeName, typeLocator)) {
                    if (duplicateTypeNames == null)
                        duplicateTypeNames = new ArrayList();
                    duplicateTypeNames.add(compoundName);
                    if (mainType == null) {
                        try {
                            mainTypeName = compilationUnit.initialTypeName; // slash separated qualified name "p1/p1/A"
                            mainType = this.javaBuilder.javaProject.findType(mainTypeName.replace('/', '.'));
                        } catch (JavaModelException e) {
                            // ignore
                        }
                    }
                    IType type;
                    if (qualifiedTypeName.equals(mainTypeName)) {
                        type = mainType;
                    } else {
                        String simpleName = qualifiedTypeName.substring(qualifiedTypeName.lastIndexOf('/') + 1);
                        type = mainType == null ? null : mainType.getCompilationUnit().getType(simpleName);
                    }
                    createProblemFor(compilationUnit.resource, type,
                            Messages.bind(Messages.build_duplicateClassFile, new String(typeName)),
                            JavaCore.ERROR);
                    continue;
                }
                this.newState.recordLocatorForType(qualifiedTypeName, typeLocator);
                if (result.checkSecondaryTypes && !qualifiedTypeName.equals(compilationUnit.initialTypeName))
                    acceptSecondaryType(classFile);
            }
            try {
                definedTypeNames.add(writeClassFile(classFile, compilationUnit, !isNestedType));
            } catch (CoreException e) {
                Util.log(e, "JavaBuilder handling CoreException"); //$NON-NLS-1$
                if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS)
                    createProblemFor(compilationUnit.resource, null,
                            Messages.bind(Messages.build_classFileCollision, e.getMessage()), JavaCore.ERROR);
                else
                    createProblemFor(compilationUnit.resource, null, Messages.build_inconsistentClassFile,
                            JavaCore.ERROR);
            }
        }
        if (result.hasAnnotations && this.filesWithAnnotations != null) // only initialized if an annotation processor is attached
            this.filesWithAnnotations.add(compilationUnit);

        this.compiler.lookupEnvironment.releaseClassFiles(classFiles);
        finishedWith(typeLocator, result, compilationUnit.getMainTypeName(), definedTypeNames,
                duplicateTypeNames);
        this.notifier.compiled(compilationUnit);
    }
}

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

License:Open Source License

/**
 * Creates a marker from each problem and adds it to the resource.
 * The marker is as follows://from w w w  . j a va 2  s .com
 *   - its type is T_PROBLEM
 *   - its plugin ID is the JavaBuilder's plugin ID
 *    - its message is the problem's message
 *    - its priority reflects the severity of the problem
 *    - its range is the problem's range
 *    - it has an extra attribute "ID" which holds the problem's id
 *   - it's {@link IMarker#SOURCE_ID} attribute is positioned to {@link JavaBuilder#SOURCE_ID} if
 *     the problem was generated by JDT; else the {@link IMarker#SOURCE_ID} attribute is
 *     carried from the problem to the marker in extra attributes, if present.
 */
protected void storeProblemsFor(SourceFile sourceFile, CategorizedProblem[] problems) throws CoreException {
    if (sourceFile == null || problems == null || problems.length == 0)
        return;
    // once a classpath error is found, ignore all other problems for this project so the user can see the main error
    // but still try to compile as many source files as possible to help the case when the base libraries are in source
    if (!this.keepStoringProblemMarkers)
        return; // only want the one error recorded on this source file

    HashSet managedMarkerTypes = JavaModelManager.getJavaModelManager().compilationParticipants
            .managedMarkerTypes();
    problems: for (int i = 0, l = problems.length; i < l; i++) {
        CategorizedProblem problem = problems[i];
        int id = problem.getID();
        // we may use a different resource for certain problems such as IProblem.MissingNonNullByDefaultAnnotationOnPackage
        // but at the start of the next problem we should reset it to the source file's resource
        IResource resource = sourceFile.resource;

        // handle missing classfile situation
        if (id == IProblem.IsClassPathCorrect) {
            String missingClassfileName = problem.getArguments()[0];
            if (JavaBuilder.DEBUG)
                System.out.println(Messages.bind(Messages.build_incompleteClassPath, missingClassfileName));
            boolean isInvalidClasspathError = JavaCore.ERROR
                    .equals(this.javaBuilder.javaProject.getOption(JavaCore.CORE_INCOMPLETE_CLASSPATH, true));
            // insert extra classpath problem, and make it the only problem for this project (optional)
            if (isInvalidClasspathError && JavaCore.ABORT.equals(
                    this.javaBuilder.javaProject.getOption(JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, true))) {
                JavaBuilder.removeProblemsAndTasksFor(this.javaBuilder.currentProject); // make this the only problem for this project
                this.keepStoringProblemMarkers = false;
            }
            IMarker marker = this.javaBuilder.currentProject
                    .createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER);
            marker.setAttributes(
                    new String[] { IMarker.MESSAGE, IMarker.SEVERITY, IJavaModelMarker.CATEGORY_ID,
                            IMarker.SOURCE_ID },
                    new Object[] { Messages.bind(Messages.build_incompleteClassPath, missingClassfileName),
                            new Integer(isInvalidClasspathError ? IMarker.SEVERITY_ERROR
                                    : IMarker.SEVERITY_WARNING),
                            new Integer(CategorizedProblem.CAT_BUILDPATH), JavaBuilder.SOURCE_ID });
            // even if we're not keeping more markers, still fall through rest of the problem reporting, so that offending
            // IsClassPathCorrect problem gets recorded since it may help locate the offending reference
        }

        String markerType = problem.getMarkerType();
        boolean managedProblem = false;
        if (IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER.equals(markerType)
                || (managedProblem = managedMarkerTypes.contains(markerType))) {
            if (id == IProblem.MissingNonNullByDefaultAnnotationOnPackage
                    && !(CharOperation.equals(sourceFile.getMainTypeName(), TypeConstants.PACKAGE_INFO_NAME))) {
                // for this kind of problem, marker needs to be created on the package instead of on the source file
                // see bug 372012
                char[] fileName = sourceFile.getFileName();
                int pkgEnd = CharOperation.lastIndexOf('/', fileName);
                if (pkgEnd == -1)
                    pkgEnd = CharOperation.lastIndexOf(File.separatorChar, fileName);
                PackageFragment pkg = null;
                if (pkgEnd != -1)
                    pkg = (PackageFragment) Util.getPackageFragment(sourceFile.getFileName(), pkgEnd,
                            -1 /*no jar separator for java files*/);

                if (pkg != null) {
                    try {
                        IMarker[] existingMarkers = pkg.resource().findMarkers(
                                IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_ZERO);
                        int len = existingMarkers.length;
                        for (int j = 0; j < len; j++) {
                            if (((Integer) existingMarkers[j].getAttribute(IJavaModelMarker.ID))
                                    .intValue() == IProblem.MissingNonNullByDefaultAnnotationOnPackage) {
                                continue problems; // marker already present
                            }
                        }
                    } catch (CoreException e) {
                        // marker retrieval failed, cannot do much
                        if (JavaModelManager.VERBOSE) {
                            e.printStackTrace();
                        }
                    }
                    IResource tempRes = pkg.resource();
                    if (tempRes != null) {
                        resource = tempRes;
                    }
                }
            }
            IMarker marker = resource.createMarker(markerType);

            String[] attributeNames = JAVA_PROBLEM_MARKER_ATTRIBUTE_NAMES;
            int standardLength = attributeNames.length;
            String[] allNames = attributeNames;
            int managedLength = managedProblem ? 0 : 1;
            String[] extraAttributeNames = problem.getExtraMarkerAttributeNames();
            int extraLength = extraAttributeNames == null ? 0 : extraAttributeNames.length;
            if (managedLength > 0 || extraLength > 0) {
                allNames = new String[standardLength + managedLength + extraLength];
                System.arraycopy(attributeNames, 0, allNames, 0, standardLength);
                if (managedLength > 0)
                    allNames[standardLength] = IMarker.SOURCE_ID;
                System.arraycopy(extraAttributeNames, 0, allNames, standardLength + managedLength, extraLength);
            }

            Object[] allValues = new Object[allNames.length];
            // standard attributes
            int index = 0;
            allValues[index++] = problem.getMessage(); // message
            allValues[index++] = problem.isError() ? S_ERROR : S_WARNING; // severity
            allValues[index++] = new Integer(id); // ID
            allValues[index++] = new Integer(problem.getSourceStart()); // start
            allValues[index++] = new Integer(problem.getSourceEnd() + 1); // end
            allValues[index++] = new Integer(problem.getSourceLineNumber()); // line
            allValues[index++] = Util.getProblemArgumentsForMarker(problem.getArguments()); // arguments
            allValues[index++] = new Integer(problem.getCategoryID()); // category ID
            // SOURCE_ID attribute for JDT problems
            if (managedLength > 0)
                allValues[index++] = JavaBuilder.SOURCE_ID;
            // optional extra attributes
            if (extraLength > 0)
                System.arraycopy(problem.getExtraMarkerAttributeValues(), 0, allValues, index, extraLength);

            marker.setAttributes(allNames, allValues);

            if (!this.keepStoringProblemMarkers)
                return; // only want the one error recorded on this source file
        }
    }
}

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  .  ja v  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);
                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.eclipse.ajdt.internal.core.builder.BuildClasspathResolver.java

License:Open Source License

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

    /* Update cycle marker */
    IMarker cycleMarker = javaProject.getCycleMarker();
    if (cycleMarker != null) {
        int severity = JavaCore.ERROR.equals(javaProject.getOption(JavaCore.CORE_CIRCULAR_CLASSPATH, true))
                ? IMarker.SEVERITY_ERROR
                : IMarker.SEVERITY_WARNING;
        if (severity != ((Integer) cycleMarker.getAttribute(IMarker.SEVERITY)).intValue())
            cycleMarker.setAttribute(IMarker.SEVERITY, severity);
    }//from w  w  w . j a v  a2s .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.ui.tests.preferences.AJCompilerPreferencePageTest.java

License:Open Source License

public void testNewXlintOptions() throws Exception {
    IPreferenceStore preferenceStore = AspectJUIPlugin.getDefault().getPreferenceStore();
    try {/*from   www . j a  va  2  s  . c o m*/
        // Use a logger to which we have access
        TestLogger testLog = new TestLogger();
        AspectJPlugin.getDefault().setAJLogger(testLog);

        /*
         * These projects are only used for this test, so it seems
         * misleading and pointless to initialise them in setup.
         */
        createPredefinedProject("ThirdPartyLibrary"); //$NON-NLS-1$
        IProject userLibraryProject = createPredefinedProject("UserLibrary"); //$NON-NLS-1$
        createPredefinedProject("UserLibraryAspects"); //$NON-NLS-1$

        // 1. Check for expected error marker - default
        checkProjectForExpectedMarker(userLibraryProject, IMarker.SEVERITY_ERROR, "[Xlint:cantFindType]"); //$NON-NLS-1$

        /*
         * 2. Change AspectJ Compiler Preferences Change them in the store
         * as this is what the code does - I guess we really want to change
         * the preferences via the GUI, but that's on the 'To Do' list...
         * -spyoung
         */
        preferenceStore.setValue(AspectJPreferences.OPTION_cantFindType, JavaCore.WARNING);
        AJCompilerPreferencePage.initDefaults(preferenceStore);

        // Re-build from clean
        IWorkspace workspace = AspectJPlugin.getWorkspace();
        workspace.build(IncrementalProjectBuilder.CLEAN_BUILD, null);

        waitForJobsToComplete();

        // 3. Check for expected warning marker, post preferences change
        checkProjectForExpectedMarker(userLibraryProject, IMarker.SEVERITY_WARNING, "[Xlint:cantFindType]"); //$NON-NLS-1$

    } finally {
        // 4. Tidy up state
        preferenceStore.setValue(AspectJPreferences.OPTION_cantFindType, JavaCore.ERROR);
        AJCompilerPreferencePage.initDefaults(preferenceStore);
        AspectJPlugin.getDefault().setAJLogger(null);
    }
}

From source file:org.eclipse.che.ide.ext.java.ReconcileTest.java

License:Open Source License

@Test
public void testWarnings() throws Exception {
    project.setOption(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
    project.setOption(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR);
    setWorkingCopyContents(/*from   w  w w. j a  v a  2  s  .  c o  m*/
            "package p1;\n" + "public class X {\n" + "  public void foo() {\n" + "     int i = 0;\n"
                    + "     String b = new String();\n" + "     System.out.println(b);\n" + "  }\n" + "}");
    ReconcileResult reconcile = reconciler.reconcile(project, "p1.X");
    assertThat(reconcile.getProblems()).onProperty("error").containsSequence(true);
}