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

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

Introduction

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

Prototype

public final void replace(ASTNode node, ASTNode replacement, TextEditGroup editGroup) 

Source Link

Document

Replaces the given node in this rewriter.

Usage

From source file:com.android.icu4j.srcgen.ReplaceIcuTags.java

License:Apache License

@Override
protected boolean visitTagElement(Reporter reporter, ASTRewrite rewrite, TagElement tag) {
    String tagName = tag.getTagName();
    if (tagName != null) {
        AST ast = tag.getAST();//from ww w  .ja  v  a  2  s  . c o  m
        List<IDocElement> fragments = tag.fragments();
        if (tagName.equalsIgnoreCase("@icu")) {
            // ICU replaces {@icu __usage__} with "Methods, fields, and other functionality specific to
            // ICU are labeled '[icu]'"
            // ICU replaces {@icu} with [icu]
            if (fragments.size() == 0) {
                rewrite.replace(tag, createIcuMarker(ast), null /* editGroup */);
            } else {
                IDocElement element = fragments.get(0);
                if (element.toString().trim().equalsIgnoreCase("_usage_")) {
                    rewrite.replace(tag, createIcuUsageText(ast), null /* editGroup */);
                } else {
                    throw new AssertionError("Unknown Javadoc tag: " + tag);
                }
            }
            return false;
        } else if (tagName.equalsIgnoreCase("@icuenhanced")) {
            // ICU replaces {@icuenhanced <classname>} with "[icu enhancement] ICU's replacement for
            // <classname>"
            IDocElement element = fragments.get(0);
            rewrite.replace(tag, createIcuEnhancementText(ast, element), null /* editGroup */);
            return false;
        } else if (tagName.equalsIgnoreCase("@icunote")) {
            // ICU replaces {@icunote} with "[icu] Note:"
            rewrite.replace(tag, createIcuNoteText(ast), null /* editGroup */);
            return false;
        } else if (tagName.equalsIgnoreCase("@discouraged")) {
            // ICU replaces {@discouraged} with "Discouraged:"
            IDocElement element = fragments.get(0);
            rewrite.replace(tag, createDiscouragedText(ast, element), null /* editGroup */);
            return false;
        }
    }
    return true;
}

From source file:com.google.currysrc.processors.ModifyQualifiedNames.java

License:Apache License

@Override
public void process(Context context, CompilationUnit cu) {
    final ASTRewrite rewrite = context.rewrite();
    ASTVisitor visitor = new ASTVisitor(true /* visitDocTags */) {
        @Override//w w w  . ja v a 2  s  .  c o m
        public boolean visit(QualifiedName node) {
            Name qualifier = node.getQualifier();
            if (qualifier != null) {
                String fullyQualifiedName = qualifier.getFullyQualifiedName();
                if (fullyQualifiedName.startsWith(oldPrefix)) {
                    String newQualifierString = newPrefix + fullyQualifiedName.substring(oldPrefix.length());
                    Name newQualifier = node.getAST().newName(newQualifierString);
                    rewrite.replace(qualifier, newQualifier, null /* editGroup */);
                }
            }
            return false;
        }
    };
    cu.accept(visitor);
}

From source file:com.google.currysrc.processors.ModifyStringLiterals.java

License:Apache License

@Override
public void process(Context context, CompilationUnit cu) {
    final ASTRewrite rewrite = context.rewrite();
    ASTVisitor visitor = new ASTVisitor(false /* visitDocTags */) {
        @Override//from   w  w  w.  j a  v  a  2  s  .c o m
        public boolean visit(StringLiteral node) {
            String literalValue = node.getLiteralValue();
            // TODO Replace with Pattern
            if (literalValue.contains(oldString)) {
                String newLiteralValue = literalValue.replace(oldString, newString);
                StringLiteral newLiteral = node.getAST().newStringLiteral();
                newLiteral.setLiteralValue(newLiteralValue);
                rewrite.replace(node, newLiteral, null /* editGorup */);
            }
            return false;
        }
    };
    cu.accept(visitor);
}

From source file:com.google.currysrc.processors.RenamePackage.java

License:Apache License

@Override
public void process(Context context, CompilationUnit cu) {
    PackageDeclaration packageDeclaration = cu.getPackage();
    if (packageDeclaration == null) {
        return;/*from  www. j  a v a2  s  .  c o  m*/
    }
    String fqn = packageDeclaration.getName().getFullyQualifiedName();
    if (!fqn.startsWith(toMatch)) {
        return;
    }
    String newFqn = replacement + fqn.substring(toMatch.length());
    Name newName = cu.getAST().newName(newFqn);
    ASTRewrite rewrite = context.rewrite();
    rewrite.replace(packageDeclaration.getName(), newName, null /* editGroup */);
}

From source file:com.google.gwt.eclipse.core.markers.quickfixes.AbstractUpdateSignatureProposal.java

License:Open Source License

@Override
protected ASTRewrite getRewrite() {
    MethodDeclaration dstMethod = findBestUpdateMatch(rpcPair);

    CompilationUnit astRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
    createImportRewrite(astRoot);/*w ww. ja va 2 s .  c o  m*/

    ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());

    MethodDeclaration rewriterDstMethod = JavaASTUtils.findMethodDeclaration(astRoot,
            dstMethod.resolveBinding().getKey());
    if (rewriterDstMethod == null) {
        return null;
    }

    MethodDeclaration newSignature = computeMethodSignature(rewrite.getAST(), rpcPair, rewriterDstMethod);

    rewrite.replace(rewriterDstMethod, newSignature, null);

    return rewrite;
}

From source file:com.google.gwt.eclipse.core.markers.quickfixes.ChangeAsyncMethodReturnTypeProposal.java

License:Open Source License

@Override
protected ASTRewrite getRewrite() throws CoreException {
    CompilationUnit targetAstRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
    AST ast = targetAstRoot.getAST();//from   w w w. jav a 2 s  .  c o  m
    createImportRewrite(targetAstRoot);

    ASTRewrite rewrite = ASTRewrite.create(targetAstRoot.getAST());

    // Find the method declaration in the AST we just generated (the one that
    // the AST rewriter is hooked up to).
    MethodDeclaration rewriterAstMethodDecl = JavaASTUtils.findMethodDeclaration(targetAstRoot,
            methodDecl.resolveBinding().getKey());
    if (rewriterAstMethodDecl == null) {
        return null;
    }

    // Set up the list of valid return types
    List<ITypeBinding> validReturnTypeBindings = new ArrayList<ITypeBinding>();
    validReturnTypeBindings.add(ast.resolveWellKnownType("void"));

    IJavaProject javaProject = getCompilationUnit().getJavaProject();
    ITypeBinding requestBinding = JavaASTUtils.resolveType(javaProject, "com.google.gwt.http.client.Request");
    if (requestBinding != null) {
        validReturnTypeBindings.add(requestBinding);
    }
    ITypeBinding requestBuilderBinding = JavaASTUtils.resolveType(javaProject,
            "com.google.gwt.http.client.RequestBuilder");
    if (requestBuilderBinding != null) {
        validReturnTypeBindings.add(requestBuilderBinding);
    }

    // Set default proposal return type
    Type newReturnType = getImportRewrite().addImport(validReturnTypeBindings.get(0), ast);
    rewrite.replace(rewriterAstMethodDecl.getReturnType2(), newReturnType, null);

    // Use linked mode to choose from one of the other valid return types
    String key = "return_type";
    addLinkedPosition(rewrite.track(newReturnType), true, key);
    for (ITypeBinding binding : validReturnTypeBindings) {
        addLinkedPositionProposal(key, binding);
    }

    return rewrite;
}

From source file:com.gowan.plugin.handlers.JUnit3Handler.java

License:Open Source License

/**
 * //from   www .  j  a v  a 2 s .com
 * @param unit
 * @throws JavaModelException
 */
private void createAST(ICompilationUnit unit) throws JavaModelException {
    CompilationUnit parse = parse(unit);
    JUnit3Visitor visitor = new JUnit3Visitor();
    parse.accept(visitor);

    IDocument doc = new Document(unit.getSource());
    AST ast = parse.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    JUnit3 junit = visitor.getJUnit3();

    TypeDeclaration td = (TypeDeclaration) parse.types().get(0);
    ITrackedNodePosition tdLocation = rewrite.track(td);

    if (junit.getKlass() != null) {
        rewrite.replace(td.getSuperclassType(), null, null);
    } else {
        return; // Skip if the class does not extend junit.framework.TestCase
    }

    //         imports
    ImportDeclaration afterImport = ast.newImportDeclaration();
    afterImport.setName(ast.newName(AFTER));
    ImportDeclaration beforeImport = ast.newImportDeclaration();
    beforeImport.setName(ast.newName(BEFORE));
    ImportDeclaration testImport = ast.newImportDeclaration();
    testImport.setName(ast.newName(TEST));

    ListRewrite lrw = rewrite.getListRewrite(parse, CompilationUnit.IMPORTS_PROPERTY);
    if (junit.getTestCaseImport() != null) {
        lrw.remove(junit.getTestCaseImport(), null);

        lrw.insertLast(afterImport, null);
        lrw.insertLast(beforeImport, null);
        lrw.insertLast(testImport, null);
    }

    if (junit.getSetUp() != null) {
        transformSetUp(ast, rewrite, junit);
    }
    if (junit.getTearDown() != null) {
        transformTearDown(ast, rewrite, junit);
    }
    if (junit.getTest() != null && !junit.getTest().isEmpty()) {
        transformTest(ast, rewrite, junit);
    }

    TextEdit edits = rewrite.rewriteAST(doc, null);

    unit.applyTextEdit(edits, null);

}

From source file:com.halware.nakedide.eclipse.ext.annot.utils.AstUtils.java

License:Open Source License

/**
 * Provided as a slight performance optimization when an ASTParser is already available
 * to do the refactoring./*from   ww  w  .j ava 2s  .  c  o m*/
 *  
 * @param parser - must have the compilationUnit as its source, per {@link ASTParser#setSource(ICompilationUnit)}.
 * @param compilationUnit
 * @param originals - to be replaced with the (single) replacement node.
 * @param replacement - the (single) replacement node; may be null meaning the originals are simply removed completely.
 * 
 * @throws JavaModelException
 * @throws MalformedTreeException
 * @throws BadLocationException
 */
public static void rewriteReplace(ASTParser parser, ICompilationUnit compilationUnit, List<ASTNode> originals,
        ASTNode replacement) throws JavaModelException, MalformedTreeException, BadLocationException {

    String source = compilationUnit.getBuffer().getContents();
    Document document = new Document(source);

    ASTNode firstOriginal = originals.get(0);
    ASTRewrite rewrite = ASTRewrite.create(firstOriginal.getAST());

    TextEditGroup editGroup = new TextEditGroup("Replacing nodes");
    for (ASTNode original : originals) {
        if (original == firstOriginal) {
            rewrite.replace(original, replacement, editGroup);
        } else {
            rewrite.replace(original, null, editGroup);
        }
    }

    TextEdit edits = rewrite.rewriteAST(document, compilationUnit.getJavaProject().getOptions(true));

    // computation of the new source code
    edits.apply(document);
    String newSource = document.get();

    // update of the compilation unit
    compilationUnit.getBuffer().setContents(newSource);
}

From source file:edu.illinois.keshmesh.transformer.core.LCK03JFixer.java

License:Open Source License

/**
 * FIXME://from  w w  w.  ja  va  2 s  .  co  m
 * 
 * Break the method into smaller ones.
 * 
 * Rethrow the exception as CoreException
 * 
 * Preserve comments.
 * 
 * Preserve formatting.
 * 
 */
@Override
public Change createChange(IProgressMonitor progressMonitor) throws CoreException, OperationCanceledException {
    ITextFileBufferManager textFileBufferManager = null;
    try {
        //Retrieving the Document out of IPath
        textFileBufferManager = FileBuffers.getTextFileBufferManager();
        textFileBufferManager.connect(bugPosition.getSourcePath(), LocationKind.LOCATION, progressMonitor);
        ITextFileBuffer textFileBuffer = textFileBufferManager.getTextFileBuffer(bugPosition.getSourcePath(),
                LocationKind.IFILE);
        IDocument document = textFileBuffer.getDocument();
        try {
            Logger.log(document.get(bugPosition.getFirstOffset(), bugPosition.getLength()));
        } catch (BadLocationException e1) {
            e1.printStackTrace();
        }
        // Parsing the Document
        ASTParser parser = ASTParser.newParser(AST.JLS3);
        parser.setKind(ASTParser.K_COMPILATION_UNIT);
        parser.setSource(document.get().toCharArray());
        parser.setResolveBindings(true);
        CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(progressMonitor);

        // Retrieving the begin and end indexes of synchronized command
        int bugLineOffset = document.getLineInformation(bugPosition.getFirstLine() - 1).getOffset();
        int bugLineLength = document.getLineInformation(bugPosition.getFirstLine() - 1).getLength();
        String bugLine = document.get(bugLineOffset, bugLineLength);
        int syncCommandBeginIndex = getSynchronizedCommandBeginIndex(bugLine);
        int syncCommandLastIndex = getSynchronizedCommandLastIndex(bugLine, syncCommandBeginIndex);

        // Extracting the synchronized command expression
        String bugLineAfterSync = bugLine.substring(syncCommandBeginIndex + SYNC_COMMAND.length());
        int openParenthesisIndex = bugLineAfterSync.indexOf('(') + syncCommandBeginIndex
                + SYNC_COMMAND.length();
        String synchExpression = bugLine.substring(openParenthesisIndex + 1, syncCommandLastIndex);

        // Computing the begin and end offset of the synchronized command
        int syncCommandBeginOffset = bugLineOffset + syncCommandBeginIndex;
        int syncCommandLastOffset = bugLineOffset + syncCommandLastIndex;
        // Getting the synchronized command AST node 
        ASTNode monitorNode = NodeFinder.perform(compilationUnit, syncCommandBeginOffset,
                syncCommandLastOffset - syncCommandBeginOffset + 1);
        SynchronizedStatement synchronizedStatement = (SynchronizedStatement) monitorNode;
        List synchBodyStatements = synchronizedStatement.getBody().statements();

        // Creating a "local variable assignment" statement and a try/catch/final block to be replaced at monitor node place
        //AST ast = synchronizedStatement.getAST();
        ASTRewrite rewriter = ASTRewrite.create(compilationUnit.getAST());
        String localVarNameForLock = "tempLock";
        String localVarAssignment = LCK03JBugPattern.LOCK + " " + localVarNameForLock + " = " + synchExpression
                + ";\n";
        String tryFinalBlockStatements = "try {\n" + localVarNameForLock + ".lock();\n";
        for (Object statement : synchBodyStatements) {
            tryFinalBlockStatements += statement;
        }
        tryFinalBlockStatements += "} finally {\n" + localVarNameForLock + ".unlock();\n}";

        // Rewriting the monitor node
        ASTNode astNode = rewriter.createStringPlaceholder(localVarAssignment + tryFinalBlockStatements,
                TryStatement.TRY_STATEMENT);
        rewriter.replace(synchronizedStatement, astNode, null);
        TextEdit textEdit = rewriter.rewriteAST(document, null);
        UndoEdit undoEdit = textEdit.apply(document);

        //Committing changes to the source file
        textFileBuffer.commit(progressMonitor, true);
    } catch (BadLocationException e) {
        throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Failed to fix LCK03J.", e));
    } finally {
        textFileBufferManager.disconnect(bugPosition.getSourcePath(), LocationKind.LOCATION, progressMonitor);
    }
    return null;
}

From source file:edu.umd.cs.findbugs.plugin.eclipse.quickfix.CorrectOddnessCheckResolution.java

License:Open Source License

@Override
protected void repairBug(ASTRewrite rewrite, CompilationUnit workingUnit, BugInstance bug)
        throws BugResolutionException {
    Assert.isNotNull(rewrite);//from   w w  w.ja v  a 2  s. c  om
    Assert.isNotNull(workingUnit);
    Assert.isNotNull(bug);

    InfixExpression oddnessCheck = findOddnessCheck(
            getASTNode(workingUnit, bug.getPrimarySourceLineAnnotation()));
    if (oddnessCheck == null) {
        throw new BugResolutionException("No matching oddness check found at the specified source line.");
    }
    Expression numberExpression = findNumberExpression(oddnessCheck);
    if (numberExpression == null) {
        throw new BugResolutionException();
    }
    InfixExpression correctOddnessCheck = createCorrectOddnessCheck(rewrite, numberExpression);
    rewrite.replace(oddnessCheck, correctOddnessCheck, null);
}