Example usage for org.eclipse.jdt.core.dom ASTNode delete

List of usage examples for org.eclipse.jdt.core.dom ASTNode delete

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom ASTNode delete.

Prototype

public final void delete() 

Source Link

Document

Removes this node from its parent.

Usage

From source file:ch.acanda.eclipse.pmd.java.resolution.ASTUtil.java

License:Open Source License

/**
 * Replaces a node in an AST with another node. If the replacement is successful the original node is deleted.
 *
 * @param node The node to replace./*from  w  w w . j  a  va2 s. co  m*/
 * @param replacement The replacement node.
 * @return <code>true</code> if the node was successfully replaced.
 */
public static boolean replace(final ASTNode node, final ASTNode replacement) {
    final ASTNode parent = node.getParent();
    final StructuralPropertyDescriptor descriptor = node.getLocationInParent();
    if (descriptor != null) {
        if (descriptor.isChildProperty()) {
            parent.setStructuralProperty(descriptor, replacement);
            node.delete();
            return true;
        } else if (descriptor.isChildListProperty()) {
            @SuppressWarnings("unchecked")
            final List<ASTNode> children = (List<ASTNode>) parent.getStructuralProperty(descriptor);
            children.set(children.indexOf(node), replacement);
            node.delete();
            return true;
        }
    }
    return false;
}

From source file:ch.acanda.eclipse.pmd.java.resolution.ASTUtil.java

License:Open Source License

/**
 * Replaces a node in an AST with other nodes. If the replacement is successful the original node is deleted.
 *
 * @param node The node to replace./*from   w  ww  .  j  a v  a2  s.  c o m*/
 * @param replacement The replacement nodes.
 * @return <code>true</code> if the node was successfully replaced.
 */
public static boolean replace(final ASTNode node, final List<? extends ASTNode> replacement) {
    final ASTNode parent = node.getParent();
    final StructuralPropertyDescriptor descriptor = node.getLocationInParent();
    if (descriptor != null && descriptor.isChildListProperty()) {
        @SuppressWarnings("unchecked")
        final List<ASTNode> children = (List<ASTNode>) parent.getStructuralProperty(descriptor);
        children.addAll(children.indexOf(node), replacement);
        node.delete();
        return true;
    }
    return false;
}

From source file:com.motorolamobility.preflighting.samplechecker.findviewbyid.quickfix.FindViewByIdMarkerResolution.java

License:Apache License

public void run(IMarker marker) {
    IResource resource = marker.getResource();
    final ICompilationUnit iCompilationUnit = JavaCore.createCompilationUnitFrom((IFile) resource);

    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setProject(JavaCore.create(resource.getProject()));
    parser.setResolveBindings(true);//from   ww w.j  av  a 2 s .  com
    parser.setSource(iCompilationUnit);
    parser.setStatementsRecovery(true);
    parser.setBindingsRecovery(true);
    final CompilationUnit compUnit = (CompilationUnit) parser.createAST(null);

    try {
        final int lineNumber = marker.getAttribute(IMarker.LINE_NUMBER, -1);
        MethodInvocation invokedMethod = null;

        //Look for the invokedMethod that shall be moved
        invokedMethod = getMethodInvocation(compUnit, lineNumber, invokedMethod);

        IEditorPart editor = openEditor(iCompilationUnit);

        ASTNode loopNode = getLoopNode(invokedMethod);

        //Retrieve block parent for the loop statement.
        Block targetBlock = (Block) loopNode.getParent();
        List<Statement> statements = targetBlock.statements();
        int i = getLoopStatementIndex(loopNode, statements);

        //Add the node before the loop.
        compUnit.recordModifications();
        ASTNode invokedMethodStatement = getInvokedStatement(invokedMethod);
        final VariableDeclarationStatement varDeclarationStatement[] = new VariableDeclarationStatement[1];

        //Verify if the invoke statement contains a variable attribution
        if (invokedMethodStatement instanceof ExpressionStatement) {
            ExpressionStatement expressionStatement = (ExpressionStatement) invokedMethodStatement;
            Expression expression = expressionStatement.getExpression();
            if (expression instanceof Assignment) {
                Expression leftHandSide = ((Assignment) expression).getLeftHandSide();
                if (leftHandSide instanceof SimpleName) //Search for the variable declaration
                {
                    SimpleName simpleName = (SimpleName) leftHandSide;
                    final String varName = simpleName.getIdentifier();

                    loopNode.accept(new ASTVisitor() {
                        @Override
                        public boolean visit(VariableDeclarationStatement node) //Visit all variable declarations inside the loop looking for the variable which receives the findViewById result
                        {
                            List<VariableDeclarationFragment> fragments = node.fragments();
                            for (VariableDeclarationFragment fragment : fragments) {
                                if (fragment.getName().getIdentifier().equals(varName)) {
                                    varDeclarationStatement[0] = node;
                                    break;
                                }
                            }
                            return super.visit(node);
                        }
                    });
                }
            }
        }

        //Variable is declared inside the loop, now let's move the variable declaration if needed
        if (varDeclarationStatement[0] != null) {
            ASTNode varDeclarationSubTree = ASTNode.copySubtree(targetBlock.getAST(),
                    varDeclarationStatement[0]);
            statements.add(i, (Statement) varDeclarationSubTree.getRoot());

            //Delete the node inside loop.
            varDeclarationStatement[0].delete();
            i++;
        }
        ASTNode copySubtree = ASTNode.copySubtree(targetBlock.getAST(), invokedMethodStatement);
        statements.add(i, (Statement) copySubtree.getRoot());

        //Delete the node inside loop.
        invokedMethodStatement.delete();

        // apply changes to file
        final Map<?, ?> mapOptions = JavaCore.create(resource.getProject()).getOptions(true);
        final IDocument document = ((AbstractTextEditor) editor).getDocumentProvider()
                .getDocument(editor.getEditorInput());
        PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {

            public void run() {
                try {
                    TextEdit edit = compUnit.rewrite(document, mapOptions);
                    iCompilationUnit.applyTextEdit(edit, new NullProgressMonitor());
                } catch (JavaModelException e) {
                    EclipseUtils.showErrorDialog(MessagesNLS.FindViewByIdMarkerResolution_Error_Msg_Title,
                            MessagesNLS.FindViewByIdMarkerResolution_Error_Aplying_Changes + e.getMessage());
                }

            }
        });

        marker.delete();

    } catch (Exception e) {
        EclipseUtils.showErrorDialog(MessagesNLS.FindViewByIdMarkerResolution_Error_Msg_Title,
                MessagesNLS.FindViewByIdMarkerResolution_Error_Could_Not_Fix_Code);
    }
}

From source file:net.sf.eclipsecs.ui.quickfixes.AbstractASTResolution.java

License:Open Source License

/**
 * Replaces a node in an AST with another node. If the replacement is successful the original node is deleted.
 *
 * @param node//w  ww .  j a v  a  2s.  c  o m
 *            The node to replace.
 * @param replacement
 *            The replacement node.
 * @return <code>true</code> if the node was successfully replaced.
 */
protected boolean replace(final ASTNode node, final ASTNode replacement) {
    final ASTNode parent = node.getParent();
    final StructuralPropertyDescriptor descriptor = node.getLocationInParent();
    if (descriptor != null) {
        if (descriptor.isChildProperty()) {
            parent.setStructuralProperty(descriptor, replacement);
            node.delete();
            return true;
        } else if (descriptor.isChildListProperty()) {
            @SuppressWarnings("unchecked")
            final List<ASTNode> children = (List<ASTNode>) parent.getStructuralProperty(descriptor);
            children.set(children.indexOf(node), replacement);
            node.delete();
            return true;
        }
    }
    return false;
}