Example usage for org.eclipse.jdt.internal.core PackageFragment resource

List of usage examples for org.eclipse.jdt.internal.core PackageFragment resource

Introduction

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

Prototype

@Override
    public IResource resource() 

Source Link

Usage

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 ava  2 s .  c  om*/
 *   - 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:org.eclipse.jdt.internal.core.CopyResourceElementsOperation.java

License:Open Source License

/**
 * Copies/moves a package fragment with the name <code>newName</code>
 * to the destination package.<br>
 *
 * @exception JavaModelException if the operation is unable to
 * complete/*  www .j  a va 2  s  . c  o  m*/
 */
private void processPackageFragmentResource(PackageFragment source, PackageFragmentRoot root, String newName)
        throws JavaModelException {
    try {
        String[] newFragName = (newName == null) ? source.names : Util.getTrimmedSimpleNames(newName);
        PackageFragment newFrag = root.getPackageFragment(newFragName);
        IResource[] resources = collectResourcesOfInterest(source);

        // if isMove() can we move the folder itself ? (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=22458)
        boolean shouldMoveFolder = isMove() && !newFrag.resource().exists(); // if new pkg fragment exists, it is an override
        IFolder srcFolder = (IFolder) source.resource();
        IPath destPath = newFrag.getPath();
        if (shouldMoveFolder) {
            // check if destination is not included in source
            if (srcFolder.getFullPath().isPrefixOf(destPath)) {
                shouldMoveFolder = false;
            } else {
                // check if there are no sub-packages
                IResource[] members = srcFolder.members();
                for (int i = 0; i < members.length; i++) {
                    if (members[i] instanceof IFolder) {
                        shouldMoveFolder = false;
                        break;
                    }
                }
            }
        }
        boolean containsReadOnlySubPackageFragments = createNeededPackageFragments(
                (IContainer) source.parent.resource(), root, newFragName, shouldMoveFolder);
        boolean sourceIsReadOnly = Util.isReadOnly(srcFolder);

        // Process resources
        if (shouldMoveFolder) {
            // move underlying resource
            // TODO Revisit once bug 43044 is fixed
            if (sourceIsReadOnly) {
                Util.setReadOnly(srcFolder, false);
            }
            srcFolder.move(destPath, this.force, true /* keep history */, getSubProgressMonitor(1));
            if (sourceIsReadOnly) {
                Util.setReadOnly(srcFolder, true);
            }
            setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
        } else {
            // process the leaf resources
            if (resources.length > 0) {
                if (isRename()) {
                    if (!destPath.equals(source.getPath())) {
                        moveResources(resources, destPath);
                    }
                } else if (isMove()) {
                    // we need to delete this resource if this operation wants to override existing resources
                    for (int i = 0, max = resources.length; i < max; i++) {
                        IResource destinationResource = ResourcesPlugin.getWorkspace().getRoot()
                                .findMember(destPath.append(resources[i].getName()));
                        if (destinationResource != null) {
                            if (this.force) {
                                deleteResource(destinationResource, IResource.KEEP_HISTORY);
                            } else {
                                throw new JavaModelException(
                                        new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION,
                                                Messages.bind(Messages.status_nameCollision,
                                                        destinationResource.getFullPath().toString())));
                            }
                        }
                    }
                    moveResources(resources, destPath);
                } else {
                    // we need to delete this resource if this operation wants to override existing resources
                    for (int i = 0, max = resources.length; i < max; i++) {
                        IResource destinationResource = ResourcesPlugin.getWorkspace().getRoot()
                                .findMember(destPath.append(resources[i].getName()));
                        if (destinationResource != null) {
                            if (this.force) {
                                // we need to delete this resource if this operation wants to override existing resources
                                deleteResource(destinationResource, IResource.KEEP_HISTORY);
                            } else {
                                throw new JavaModelException(
                                        new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION,
                                                Messages.bind(Messages.status_nameCollision,
                                                        destinationResource.getFullPath().toString())));
                            }
                        }
                    }
                    copyResources(resources, destPath);
                }
            }
        }

        // Update package statement in compilation unit if needed
        if (!Util.equalArraysOrNull(newFragName, source.names)) { // if package has been renamed, update the compilation units
            char[][] inclusionPatterns = root.fullInclusionPatternChars();
            char[][] exclusionPatterns = root.fullExclusionPatternChars();
            for (int i = 0; i < resources.length; i++) {
                String resourceName = resources[i].getName();
                if (Util.isJavaLikeFileName(resourceName)) {
                    // we only consider potential compilation units
                    ICompilationUnit cu = newFrag.getCompilationUnit(resourceName);
                    if (Util.isExcluded(cu.getPath(), inclusionPatterns, exclusionPatterns,
                            false/*not a folder*/))
                        continue;
                    this.parser.setSource(cu);
                    CompilationUnit astCU = (CompilationUnit) this.parser.createAST(this.progressMonitor);
                    AST ast = astCU.getAST();
                    ASTRewrite rewrite = ASTRewrite.create(ast);
                    updatePackageStatement(astCU, newFragName, rewrite, cu);
                    TextEdit edits = rewrite.rewriteAST();
                    applyTextEdit(cu, edits);
                    cu.save(null, false);
                }
            }
        }

        // Discard empty old package (if still empty after the rename)
        boolean isEmpty = true;
        if (isMove()) {
            // delete remaining files in this package (.class file in the case where Proj=src=bin)
            // in case of a copy
            updateReadOnlyPackageFragmentsForMove((IContainer) source.parent.resource(), root, newFragName,
                    sourceIsReadOnly);
            if (srcFolder.exists()) {
                IResource[] remaining = srcFolder.members();
                for (int i = 0, length = remaining.length; i < length; i++) {
                    IResource file = remaining[i];
                    if (file instanceof IFile) {
                        if (Util.isReadOnly(file)) {
                            Util.setReadOnly(file, false);
                        }
                        deleteResource(file, IResource.FORCE | IResource.KEEP_HISTORY);
                    } else {
                        isEmpty = false;
                    }
                }
            }
            if (isEmpty) {
                IResource rootResource;
                // check if source is included in destination
                if (destPath.isPrefixOf(srcFolder.getFullPath())) {
                    rootResource = newFrag.resource();
                } else {
                    rootResource = source.parent.resource();
                }

                // delete recursively empty folders
                deleteEmptyPackageFragment(source, false, rootResource);
            }
        } else if (containsReadOnlySubPackageFragments) {
            // in case of a copy
            updateReadOnlyPackageFragmentsForCopy((IContainer) source.parent.resource(), root, newFragName);
        }
        // workaround for bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=24505
        if (isEmpty && isMove() && !(Util.isExcluded(source) || Util.isExcluded(newFrag))) {
            IJavaProject sourceProject = source.getJavaProject();
            getDeltaFor(sourceProject).movedFrom(source, newFrag);
            IJavaProject destProject = newFrag.getJavaProject();
            getDeltaFor(destProject).movedTo(newFrag, source);
        }
    } catch (JavaModelException e) {
        throw e;
    } catch (CoreException ce) {
        throw new JavaModelException(ce);
    }
}