Example usage for org.eclipse.jdt.core.dom.rewrite ASTRewrite rewriteAST

List of usage examples for org.eclipse.jdt.core.dom.rewrite ASTRewrite rewriteAST

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom.rewrite ASTRewrite rewriteAST.

Prototype

public TextEdit rewriteAST() throws JavaModelException, IllegalArgumentException 

Source Link

Document

Converts all modifications recorded by this rewriter into an object representing the the corresponding text edits to the source of a ITypeRoot from which the AST was created from.

Usage

From source file:com.android.ide.eclipse.adt.internal.refactorings.extractstring.ExtractStringRefactoring.java

License:Open Source License

/**
 * Computes the changes to be made to Java file(s) and returns a list of {@link Change}.
 * <p/>/*from  w  w w . j av  a  2 s.c om*/
 * This function scans a Java compilation unit using {@link ReplaceStringsVisitor}, looking
 * for a string literal equals to <code>tokenString</code>.
 * If found, a change is made to replace each occurrence of <code>tokenString</code> by
 * a piece of Java code that somehow accesses R.string.<code>xmlStringId</code>.
 *
 * @param unit The compilated unit to process. Must not be null.
 * @param tokenString The string to find. Must not be null or empty.
 * @param status Status used to report fatal errors.
 * @param monitor Used to log progress.
 */
private List<Change> computeJavaChanges(ICompilationUnit unit, String xmlStringId, String tokenString,
        RefactoringStatus status, SubMonitor monitor) {

    // We shouldn't be trying to replace a null or empty string.
    assert tokenString != null && tokenString.length() > 0;
    if (tokenString == null || tokenString.length() == 0) {
        return null;
    }

    // Get the Android package name from the Android Manifest. We need it to create
    // the FQCN of the R class.
    String packageName = null;
    String error = null;
    IResource manifestFile = mProject.findMember(SdkConstants.FN_ANDROID_MANIFEST_XML);
    if (manifestFile == null || manifestFile.getType() != IResource.FILE) {
        error = "File not found";
    } else {
        ManifestData manifestData = AndroidManifestHelper.parseForData((IFile) manifestFile);
        if (manifestData == null) {
            error = "Invalid content";
        } else {
            packageName = manifestData.getPackage();
            if (packageName == null) {
                error = "Missing package definition";
            }
        }
    }

    if (error != null) {
        status.addFatalError(String.format("Failed to parse file %1$s: %2$s.",
                manifestFile == null ? "" : manifestFile.getFullPath(), //$NON-NLS-1$
                error));
        return null;
    }

    // Right now the changes array will contain one TextFileChange at most.
    ArrayList<Change> changes = new ArrayList<Change>();

    // This is the unit that will be modified.
    TextFileChange change = new TextFileChange(getName(), (IFile) unit.getResource());
    change.setTextType("java"); //$NON-NLS-1$

    // Create an AST for this compilation unit
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setProject(unit.getJavaProject());
    parser.setSource(unit);
    parser.setResolveBindings(true);
    ASTNode node = parser.createAST(monitor.newChild(1));

    // The ASTNode must be a CompilationUnit, by design
    if (!(node instanceof CompilationUnit)) {
        status.addFatalError(String.format("Internal error: ASTNode class %s", //$NON-NLS-1$
                node.getClass()));
        return null;
    }

    // ImportRewrite will allow us to add the new type to the imports and will resolve
    // what the Java source must reference, e.g. the FQCN or just the simple name.
    ImportRewrite importRewrite = ImportRewrite.create((CompilationUnit) node, true);
    String Rqualifier = packageName + ".R"; //$NON-NLS-1$
    Rqualifier = importRewrite.addImport(Rqualifier);

    // Rewrite the AST itself via an ASTVisitor
    AST ast = node.getAST();
    ASTRewrite astRewrite = ASTRewrite.create(ast);
    ArrayList<TextEditGroup> astEditGroups = new ArrayList<TextEditGroup>();
    ReplaceStringsVisitor visitor = new ReplaceStringsVisitor(ast, astRewrite, astEditGroups, tokenString,
            Rqualifier, xmlStringId);
    node.accept(visitor);

    // Finally prepare the change set
    try {
        MultiTextEdit edit = new MultiTextEdit();

        // Create the edit to change the imports, only if anything changed
        TextEdit subEdit = importRewrite.rewriteImports(monitor.newChild(1));
        if (subEdit.hasChildren()) {
            edit.addChild(subEdit);
        }

        // Create the edit to change the Java source, only if anything changed
        subEdit = astRewrite.rewriteAST();
        if (subEdit.hasChildren()) {
            edit.addChild(subEdit);
        }

        // Only create a change set if any edit was collected
        if (edit.hasChildren()) {
            change.setEdit(edit);

            // Create TextEditChangeGroups which let the user turn changes on or off
            // individually. This must be done after the change.setEdit() call above.
            for (TextEditGroup editGroup : astEditGroups) {
                TextEditChangeGroup group = new TextEditChangeGroup(change, editGroup);
                if (editGroup instanceof EnabledTextEditGroup) {
                    group.setEnabled(((EnabledTextEditGroup) editGroup).isEnabled());
                }
                change.addTextEditChangeGroup(group);
            }

            changes.add(change);
        }

        monitor.worked(1);

        if (changes.size() > 0) {
            return changes;
        }

    } catch (CoreException e) {
        // ImportRewrite.rewriteImports failed.
        status.addFatalError(e.getMessage());
    }
    return null;
}

From source file:com.android.ide.eclipse.adt.refactorings.extractstring.ExtractStringRefactoring.java

License:Open Source License

/**
 * Computes the changes to be made to Java file(s) and returns a list of {@link Change}.
 *//*  ww  w .j  a v  a  2  s .  c  om*/
private List<Change> computeJavaChanges(ICompilationUnit unit, String xmlStringId, String tokenString,
        RefactoringStatus status, SubMonitor subMonitor) {

    // Get the Android package name from the Android Manifest. We need it to create
    // the FQCN of the R class.
    String packageName = null;
    String error = null;
    IResource manifestFile = mProject.findMember(AndroidConstants.FN_ANDROID_MANIFEST);
    if (manifestFile == null || manifestFile.getType() != IResource.FILE) {
        error = "File not found";
    } else {
        try {
            AndroidManifestParser manifest = AndroidManifestParser.parseForData((IFile) manifestFile);
            if (manifest == null) {
                error = "Invalid content";
            } else {
                packageName = manifest.getPackage();
                if (packageName == null) {
                    error = "Missing package definition";
                }
            }
        } catch (CoreException e) {
            error = e.getLocalizedMessage();
        }
    }

    if (error != null) {
        status.addFatalError(
                String.format("Failed to parse file %1$s: %2$s.", manifestFile.getFullPath(), error));
        return null;
    }

    // TODO in a future version we might want to collect various Java files that
    // need to be updated in the same project and process them all together.
    // To do that we need to use an ASTRequestor and parser.createASTs, kind of
    // like this:
    //
    // ASTRequestor requestor = new ASTRequestor() {
    //    @Override
    //    public void acceptAST(ICompilationUnit sourceUnit, CompilationUnit astNode) {
    //        super.acceptAST(sourceUnit, astNode);
    //        // TODO process astNode
    //    }  
    // };
    // ...
    // parser.createASTs(compilationUnits, bindingKeys, requestor, monitor)
    // 
    // and then add multiple TextFileChange to the changes arraylist.

    // Right now the changes array will contain one TextFileChange at most.
    ArrayList<Change> changes = new ArrayList<Change>();

    // This is the unit that will be modified.
    TextFileChange change = new TextFileChange(getName(), (IFile) unit.getResource());
    change.setTextType("java"); //$NON-NLS-1$

    // Create an AST for this compilation unit
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setProject(unit.getJavaProject());
    parser.setSource(unit);
    parser.setResolveBindings(true);
    ASTNode node = parser.createAST(subMonitor.newChild(1));

    // The ASTNode must be a CompilationUnit, by design
    if (!(node instanceof CompilationUnit)) {
        status.addFatalError(String.format("Internal error: ASTNode class %s", //$NON-NLS-1$
                node.getClass()));
        return null;
    }

    // ImportRewrite will allow us to add the new type to the imports and will resolve
    // what the Java source must reference, e.g. the FQCN or just the simple name.
    ImportRewrite importRewrite = ImportRewrite.create((CompilationUnit) node, true);
    String Rqualifier = packageName + ".R"; //$NON-NLS-1$
    Rqualifier = importRewrite.addImport(Rqualifier);

    // Rewrite the AST itself via an ASTVisitor
    AST ast = node.getAST();
    ASTRewrite astRewrite = ASTRewrite.create(ast);
    ArrayList<TextEditGroup> astEditGroups = new ArrayList<TextEditGroup>();
    ReplaceStringsVisitor visitor = new ReplaceStringsVisitor(ast, astRewrite, astEditGroups, tokenString,
            Rqualifier, xmlStringId);
    node.accept(visitor);

    // Finally prepare the change set
    try {
        MultiTextEdit edit = new MultiTextEdit();

        // Create the edit to change the imports, only if anything changed
        TextEdit subEdit = importRewrite.rewriteImports(subMonitor.newChild(1));
        if (subEdit.hasChildren()) {
            edit.addChild(subEdit);
        }

        // Create the edit to change the Java source, only if anything changed
        subEdit = astRewrite.rewriteAST();
        if (subEdit.hasChildren()) {
            edit.addChild(subEdit);
        }

        // Only create a change set if any edit was collected
        if (edit.hasChildren()) {
            change.setEdit(edit);

            // Create TextEditChangeGroups which let the user turn changes on or off
            // individually. This must be done after the change.setEdit() call above.
            for (TextEditGroup editGroup : astEditGroups) {
                change.addTextEditChangeGroup(new TextEditChangeGroup(change, editGroup));
            }

            changes.add(change);
        }

        // TODO to modify another Java source, loop back to the creation of the
        // TextFileChange and accumulate in changes. Right now only one source is
        // modified.

        if (changes.size() > 0) {
            return changes;
        }

        subMonitor.worked(1);

    } catch (CoreException e) {
        // ImportRewrite.rewriteImports failed.
        status.addFatalError(e.getMessage());
    }
    return null;
}

From source file:de.ovgu.cide.configuration.jdt.DeleteHiddenNodesVisitor.java

License:Open Source License

public static String hideCode(String buffer, CompilationUnit ast, JDTColorManagerBridge nodeColors,
        Collection<IFeature> visibleColors) throws JavaModelException, IllegalArgumentException {
    Set<IFeature> compUnitColors = nodeColors.getColors(ast);
    for (IFeature color : compUnitColors)
        if (!visibleColors.contains(color))
            return "";

    ASTRewrite rewrite = ASTRewrite.create(ast.getAST());
    ast.accept(new DeleteHiddenNodesVisitor(rewrite, nodeColors, visibleColors));
    TextEdit r = rewrite.rewriteAST();

    Document document = new Document(buffer);
    try {/*w ww.j  a  v a2s. c om*/
        r.apply(document);
    } catch (MalformedTreeException e) {
        e.printStackTrace();
    } catch (BadLocationException e) {
        e.printStackTrace();
    }
    return document.get();
}

From source file:edu.illinois.compositerefactorings.refactorings.NewClassCreator.java

License:Open Source License

public List<ResourceChange> createTopLevelParameterObject() throws CoreException {
    List<ResourceChange> changes = new ArrayList<ResourceChange>();
    ICompilationUnit unit = getPackageFragment()
            .getCompilationUnit(getClassName() + JavaModelUtil.DEFAULT_CU_SUFFIX);
    Assert.isTrue(!unit.exists());/*  ww w .  j  av  a2s.co m*/
    IJavaProject javaProject = unit.getJavaProject();
    ICompilationUnit workingCopy = unit.getWorkingCopy(null);

    try {
        // create stub with comments and dummy type
        String lineDelimiter = StubUtility.getLineDelimiterUsed(javaProject);
        String fileComment = getFileComment(workingCopy, lineDelimiter);
        String typeComment = getTypeComment(workingCopy, lineDelimiter);
        String content = CodeGeneration.getCompilationUnitContent(workingCopy, fileComment, typeComment,
                "class " + getClassName() + "{}", lineDelimiter); //$NON-NLS-1$ //$NON-NLS-2$
        workingCopy.getBuffer().setContents(content);

        CompilationUnitRewrite cuRewrite = new CompilationUnitRewrite(workingCopy);
        ASTRewrite rewriter = cuRewrite.getASTRewrite();
        CompilationUnit root = cuRewrite.getRoot();
        AST ast = cuRewrite.getAST();
        ImportRewrite importRewrite = cuRewrite.getImportRewrite();

        if (fSuperclassType != null) {
            importRewrite.addImport(fSuperclassType.resolveBinding());
        }

        // retrieve&replace dummy type with real class
        ListRewrite types = rewriter.getListRewrite(root, CompilationUnit.TYPES_PROPERTY);
        ASTNode dummyType = (ASTNode) types.getOriginalList().get(0);
        TypeDeclaration classDeclaration = createClassDeclaration(getClassName(), cuRewrite);
        classDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
        Javadoc javadoc = (Javadoc) dummyType.getStructuralProperty(TypeDeclaration.JAVADOC_PROPERTY);
        rewriter.set(classDeclaration, TypeDeclaration.JAVADOC_PROPERTY, javadoc, null);
        types.replace(dummyType, classDeclaration, null);

        // Apply rewrites and discard workingcopy
        // Using CompilationUnitRewrite.createChange() leads to strange
        // results
        String charset = ResourceUtil.getFile(unit).getCharset(false);
        Document document = new Document(content);
        try {
            rewriter.rewriteAST().apply(document);
            TextEdit rewriteImports = importRewrite.rewriteImports(null);
            rewriteImports.apply(document);
        } catch (BadLocationException e) {
            throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(),
                    RefactoringCoreMessages.IntroduceParameterObjectRefactoring_parameter_object_creation_error,
                    e));
        }
        String docContent = document.get();
        CreateCompilationUnitChange compilationUnitChange = new CreateCompilationUnitChange(unit, docContent,
                charset);
        changes.add(compilationUnitChange);
    } finally {
        workingCopy.discardWorkingCopy();
    }
    return changes;
}

From source file:nz.ac.massey.cs.care.refactoring.executers.IntroduceFactoryRefactoring.java

License:Open Source License

/**
 * Add all changes necessary on the <code>ICompilationUnit</code> in the given
 * <code>SearchResultGroup</code> to implement the refactoring transformation
 * to the given <code>CompilationUnitChange</code>.
 * @param rg the <code>SearchResultGroup</code> for which changes should be created
 * @param unitHandle/*from   w w w .  j av  a2  s.  c o  m*/
 * @param unitChange the CompilationUnitChange object for the compilation unit in question
 * @return <code>true</code> iff a change has been added
 * @throws CoreException
 */
private boolean addAllChangesFor(SearchResultGroup rg, ICompilationUnit unitHandle,
        CompilationUnitChange unitChange) throws CoreException {
    //      ICompilationUnit   unitHandle= rg.getCompilationUnit();
    Assert.isTrue(rg == null || rg.getCompilationUnit() == unitHandle);
    CompilationUnit unit = getASTFor(unitHandle);
    ASTRewrite unitRewriter = ASTRewrite.create(unit.getAST());
    MultiTextEdit root = new MultiTextEdit();
    boolean someChange = false;

    unitChange.setEdit(root);
    fImportRewriter = StubUtility.createImportRewrite(unit, true);

    // First create the factory method
    if (unitHandle.equals(fFactoryUnitHandle)) {
        TextEditGroup factoryGD = new TextEditGroup(RefactoringCoreMessages.IntroduceFactory_addFactoryMethod);

        createFactoryChange(unitRewriter, unit, factoryGD);
        unitChange.addTextEditGroup(factoryGD);
        someChange = true;
    }

    // Now rewrite all the constructor calls to use the factory method
    if (rg != null)
        if (replaceConstructorCalls(rg, unit, unitRewriter, unitChange))
            someChange = true;

    // Finally, make the constructor private, if requested.
    if (shouldProtectConstructor() && isConstructorUnit(unitHandle)) {
        TextEditGroup declGD = new TextEditGroup(RefactoringCoreMessages.IntroduceFactory_protectConstructor);

        if (protectConstructor(unit, unitRewriter, declGD)) {
            unitChange.addTextEditGroup(declGD);
            someChange = true;
        }
    }

    if (someChange) {
        root.addChild(unitRewriter.rewriteAST());
        root.addChild(fImportRewriter.rewriteImports(null));
    }

    return someChange;
}

From source file:org.eclipse.ajdt.internal.ui.refactoring.PushInRefactoring.java

License:Open Source License

/**
 * Adds the specified new parents to the type.
 * Need to determine if the new paretns are extends or implements
 * /*from   ww  w  .  j  ava 2 s.  c  o  m*/
 * FIXADE will not handle generic types
 * @param targetType
 * @param astUnit
 * @param newParents
 * @param holder
 * @throws JavaModelException 
 */
@SuppressWarnings("unchecked")
private void rewriteDeclareParents(IType targetType, CompilationUnit astUnit, Set<String> newParents,
        ICompilationUnit unit) throws JavaModelException {

    // find the Type declaration in the ast
    TypeDeclaration typeDecl = findType(astUnit, targetType.getElementName());
    if (typeDecl == null) {
        createJavaModelException(
                "Couldn't find type " + targetType.getElementName() + " in " + unit.getElementName());
    }

    // convert all parents to simple names
    List<String> simpleParents = new ArrayList<String>(newParents.size());
    for (String qual : newParents) {
        simpleParents.add(convertToSimple(qual));
    }

    // now remove any possible duplicates
    Type superclassType = typeDecl.getSuperclassType();
    Type supr = superclassType;
    if (supr != null && supr.isSimpleType()) {
        simpleParents.remove(((SimpleType) supr).getName().getFullyQualifiedName());
    }
    for (Type iface : (Iterable<Type>) typeDecl.superInterfaceTypes()) {
        if (iface.isSimpleType()) {
            simpleParents.remove(((SimpleType) iface).getName().getFullyQualifiedName());
        }
    }

    // Find the super class if exists
    // make assumption that there is at most one super class defined.
    // if this weren't the case, then there would be a compile error
    // and it would not be possible to invoke refactoring
    String newSuper = null;
    for (String parent : newParents) {
        if (isClass(parent, targetType)) {
            newSuper = convertToSimple(parent);
            simpleParents.remove(newSuper);
        }
    }

    // do the rewrite.  Only need to add simple names since imports are already taken care of
    // in the holder
    ASTRewrite rewriter = ASTRewrite.create(astUnit.getAST());
    AST ast = typeDecl.getAST();
    if (newSuper != null) {
        Type newSuperType = createTypeAST(newSuper, ast);
        if (superclassType == null) {
            rewriter.set(typeDecl, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY, newSuperType, null);
        } else {
            rewriter.replace(superclassType, newSuperType, null);
        }
    }
    if (simpleParents.size() > 0) {
        ListRewrite listRewrite = rewriter.getListRewrite(typeDecl,
                TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY);
        for (String simpleParent : simpleParents) {
            listRewrite.insertLast(createTypeAST(simpleParent, ast), null);
        }
    }
    // finally, add the new change
    TextEdit edit = rewriter.rewriteAST();
    if (!isEmptyEdit(edit)) {
        TextFileChange change = (TextFileChange) allChanges.get(unit);
        if (change == null) {
            change = new TextFileChange(unit.getElementName(), (IFile) unit.getResource());
            change.setTextType("java");
            change.setEdit(new MultiTextEdit());
            allChanges.put(unit, change);
        }
        change.getEdit().addChild(edit);
    }
}

From source file:org.eclipse.babel.tapiji.tools.java.ui.refactoring.Cal10nEnumRefactoringVisitor.java

License:Open Source License

/**
 * Modifies the enum file. It replaces the old key with the new one.
 *//*  w w w .  j a  v a 2  s.c o  m*/
@Override
public boolean visit(EnumConstantDeclaration node) {

    if (node.resolveVariable().getName().equals(oldKey)) {

        // ASTRewrite
        AST ast = enumCu.getAST();
        ASTRewrite rewriter = ASTRewrite.create(ast);

        EnumConstantDeclaration newDeclaration = ast.newEnumConstantDeclaration();

        SimpleName newSimpleName = ast.newSimpleName(newKey);
        newDeclaration.setName(newSimpleName);

        rewriter.replace(node, newDeclaration, null);

        try {
            TextEdit textEdit = rewriter.rewriteAST();
            if (textEdit.hasChildren()) { // if the compilation unit has
                                          // been
                                          // changed
                ICompilationUnit icu = (ICompilationUnit) enumCu.getJavaElement();
                icu.applyTextEdit(textEdit, null);
                icu.getBuffer().save(null, true);

                // protocol
                int startPos = node.getStartPosition();
                changeSet.add(icu.getPath().toPortableString() + ": line " + enumCu.getLineNumber(startPos));
            }
        } catch (Exception e) {
            Logger.logError(e);
        }
    }

    return false;
}

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/*from www .  ja  v  a2  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);
    }
}

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

License:Open Source License

/**
 * Updates the content of <code>cu</code>, modifying the type name and/or package
 * declaration as necessary./* w w w  .  ja v  a 2 s . co m*/
 *
 * @return an AST rewrite or null if no rewrite needed
 */
private TextEdit updateContent(ICompilationUnit cu, PackageFragment dest, String newName)
        throws JavaModelException {
    String[] currPackageName = ((PackageFragment) cu.getParent()).names;
    String[] destPackageName = dest.names;
    if (Util.equalArraysOrNull(currPackageName, destPackageName) && newName == null) {
        return null; //nothing to change
    } else {
        // ensure cu is consistent (noop if already consistent)
        cu.makeConsistent(this.progressMonitor);

        // GROOVY start
        // don't use the ASTParser if not a Java compilation unit
        if (LanguageSupportFactory.isInterestingSourceFile(cu.getElementName())) {
            return updateNonJavaContent(cu, destPackageName, currPackageName, newName);
        }
        // GROOVY end

        this.parser.setSource(cu);
        CompilationUnit astCU = (CompilationUnit) this.parser.createAST(this.progressMonitor);
        AST ast = astCU.getAST();
        ASTRewrite rewrite = ASTRewrite.create(ast);
        updateTypeName(cu, astCU, cu.getElementName(), newName, rewrite);
        updatePackageStatement(astCU, destPackageName, rewrite, cu);
        return rewrite.rewriteAST();
    }
}

From source file:org.eclipse.pde.api.tools.ui.internal.markers.RemoveUnsupportedAnnotationOperation.java

License:Open Source License

@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
    SubMonitor localMonitor = SubMonitor.convert(monitor,
            MarkerMessages.RemoveUnsupportedTagOperation_removeing_unsupported_tag, fMarkers.length + 6);
    HashMap<ICompilationUnit, Boolean> seen = new HashMap<ICompilationUnit, Boolean>();
    for (int i = 0; i < fMarkers.length; i++) {
        // retrieve the AST node compilation unit
        IResource resource = fMarkers[i].getResource();
        IJavaElement javaElement = JavaCore.create(resource);
        try {//from   w  w w  .  j  av a2s .  c o  m
            if (javaElement != null && javaElement.getElementType() == IJavaElement.COMPILATION_UNIT) {
                ICompilationUnit compilationUnit = (ICompilationUnit) javaElement;
                if (!seen.containsKey(compilationUnit)) {
                    seen.put(compilationUnit, Boolean.valueOf(compilationUnit.hasUnsavedChanges()));
                }
                if (!compilationUnit.isWorkingCopy()) {
                    // open an editor of the corresponding unit to "show"
                    // the quick-fix change
                    JavaUI.openInEditor(compilationUnit);
                }
                if (!compilationUnit.isConsistent()) {
                    compilationUnit.reconcile(ICompilationUnit.NO_AST, false, null, null);
                    Util.updateMonitor(localMonitor, 1);
                }
                Util.updateMonitor(localMonitor, 1);
                ASTParser parser = ASTParser.newParser(AST.JLS8);
                parser.setSource(compilationUnit);
                Integer charStartAttribute = null;
                charStartAttribute = (Integer) fMarkers[i].getAttribute(IMarker.CHAR_START);
                int intValue = charStartAttribute.intValue();
                parser.setFocalPosition(intValue);
                final CompilationUnit unit = (CompilationUnit) parser.createAST(new NullProgressMonitor());
                AnnotationFinder finder = new AnnotationFinder(intValue);
                unit.accept(finder);
                Util.updateMonitor(localMonitor, 1);
                if (finder.fNode != null) {
                    unit.recordModifications();
                    AST ast = unit.getAST();
                    ASTRewrite rewrite = ASTRewrite.create(ast);
                    TextEditGroup group = new TextEditGroup("Removing API tools annotations"); //$NON-NLS-1$
                    rewrite.remove(finder.fNode, group);
                    Util.updateMonitor(localMonitor, 1);
                    TextEdit edit = rewrite.rewriteAST();
                    compilationUnit.applyTextEdit(edit, monitor);
                    Util.updateMonitor(localMonitor, 1);
                }
            }
        } catch (JavaModelException jme) {
        } catch (PartInitException e) {
        } catch (CoreException e) {
        }
    }
    // try saving the compilation units if they were in a saved state when
    // the quick-fix started
    for (Entry<ICompilationUnit, Boolean> entry : seen.entrySet()) {
        if (!entry.getValue().booleanValue()) {
            try {
                entry.getKey().commitWorkingCopy(true, null);
            } catch (JavaModelException jme) {
            }
        }
    }
    return Status.OK_STATUS;
}