Example usage for org.eclipse.jdt.core.dom Block STATEMENTS_PROPERTY

List of usage examples for org.eclipse.jdt.core.dom Block STATEMENTS_PROPERTY

Introduction

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

Prototype

ChildListPropertyDescriptor STATEMENTS_PROPERTY

To view the source code for org.eclipse.jdt.core.dom Block STATEMENTS_PROPERTY.

Click Source Link

Document

The "statements" structural property of this node type (element type: Statement ).

Usage

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

License:Open Source License

private List<ASTNode> resolveBlock(ASTNode replacement) {
    if (replacement instanceof Block) {
        ListRewrite rewrittenBlock = getRewriteList(replacement, Block.STATEMENTS_PROPERTY);
        List l = rewrittenBlock.getRewrittenList();
        if (replacement.getStartPosition() == -1)
            return new ArrayList<ASTNode>();// TODO debugging only
        return l;

    }//from  w  w  w .  j a  va2 s. c  om
    return Collections.singletonList(replacement);
}

From source file:edu.illinois.jflow.core.transformations.code.ExtractClosureRefactoring.java

License:Open Source License

private void insertPrologueStatements(TextEditGroup replaceOriginalWithDataflowDesc) {
    Statement statement = locateEnclosingLoopStatement();
    ListRewrite loopRewriter = null;//from www  .j a  v a 2  s.  com
    Statement body = null;

    // TODO: Handle other kinds of loops
    if (statement instanceof ForStatement) {
        ForStatement forStatement = (ForStatement) statement;
        body = forStatement.getBody();
    } else if (statement instanceof EnhancedForStatement) {
        EnhancedForStatement enhancedForStatement = (EnhancedForStatement) statement;
        body = enhancedForStatement.getBody();
    }

    if (body != null) {
        loopRewriter = fRewriter.getListRewrite(body, Block.STATEMENTS_PROPERTY);
        if (loopRewriter != null) {
            PrologueCreator pc = new PrologueCreator(stages.values());
            List<Statement> statements = pc.createInitializationStatements();
            // We have to insert in reverse other since we are using the 0 position (that is what insertFirst) does
            // as the anchor point
            for (int index = statements.size() - 1; index >= 0; index--) {
                loopRewriter.insertFirst(statements.get(index), replaceOriginalWithDataflowDesc);
            }
        }
    }
}

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

License:Open Source License

@Override
protected void repairBug(ASTRewrite rewrite, CompilationUnit workingUnit, BugInstance bug)
        throws BugResolutionException {
    Assert.isNotNull(rewrite);//  w w w . j av a  2s.  c  o  m
    Assert.isNotNull(workingUnit);
    Assert.isNotNull(bug);

    TypeDeclaration type = getTypeDeclaration(workingUnit, bug.getPrimaryClass());
    MethodDeclaration method = getMethodDeclaration(type, bug.getPrimaryMethod());

    AST ast = rewrite.getAST();

    SuperMethodInvocation superCall = createSuperMethodInvocation(rewrite, method);
    ExpressionStatement statement = ast.newExpressionStatement(superCall);
    Block methodBody = method.getBody();
    ListRewrite listRewrite = rewrite.getListRewrite(methodBody, Block.STATEMENTS_PROPERTY);
    if (isInsertFirst()) {
        listRewrite.insertFirst(statement, null);
    } else {
        listRewrite.insertLast(statement, null);
    }
}

From source file:edu.umd.cs.findbugs.quickfix.resolution.CreateSuperCallResolution.java

License:Open Source License

@Override
protected void repairBug(ASTRewrite rewrite, CompilationUnit workingUnit, BugInstance bug)
        throws BugResolutionException {
    assert rewrite != null;
    assert workingUnit != null;
    assert bug != null;

    TypeDeclaration type = getTypeDeclaration(workingUnit, bug.getPrimaryClass());
    MethodDeclaration method = getMethodDeclaration(type, bug.getPrimaryMethod());

    AST ast = rewrite.getAST();/*  w  w w . ja  va  2s.  c om*/

    SuperMethodInvocation superCall = createSuperMethodInvocation(rewrite, method);
    ExpressionStatement statement = ast.newExpressionStatement(superCall);
    Block methodBody = method.getBody();
    ListRewrite listRewrite = rewrite.getListRewrite(methodBody, Block.STATEMENTS_PROPERTY);
    if (isInsertFirst()) {
        listRewrite.insertFirst(statement, null);
    } else {
        listRewrite.insertLast(statement, null);
    }
}

From source file:org.autorefactor.refactoring.rules.AndroidViewHolderRefactoring.java

License:Open Source License

@Override
public boolean visit(MethodDeclaration node) {
    Block body = node.getBody();// w ww. j av  a2 s  . c o m
    if (body != null && isMethod(node, "android.widget.Adapter", "getView", "int", "android.view.View",
            "android.view.ViewGroup")) {
        final GetViewVariableVisitor visitor = new GetViewVariableVisitor();
        body.accept(visitor);
        if (visitor.canApplyRefactoring()) {
            final ASTBuilder b = this.ctx.getASTBuilder();
            final Refactorings r = this.ctx.getRefactorings();
            final TypeNameDecider typeNameDecider = new TypeNameDecider(visitor.viewVariableName);

            // Transform tree

            // Create If statement
            final SingleVariableDeclaration viewArg = parameters(node).get(1);
            final Variable convertViewVar = new Variable(viewArg.getName().getIdentifier(), b);
            final InfixExpression condition = b.infixExpr(convertViewVar.varName(), EQUALS, b.null0());
            final Block thenBlock = b.block();
            final IfStatement ifStmt = b.if0(condition, thenBlock);
            r.insertBefore(ifStmt, visitor.viewAssignmentStmt);
            final List<Statement> thenStmts = statements(thenBlock);

            thenStmts.add(
                    b.toStmt(b.assign(convertViewVar.varName(), ASSIGN, b.copy(visitor.getInflateExpr()))));

            // assign to local view variable when necessary
            if (!"convertView".equals(visitor.viewVariableName.getIdentifier())) {
                Statement assignConvertViewToView = null;
                if (visitor.viewVariableDeclFragment != null) {
                    assignConvertViewToView = b.declareStmt(
                            b.copyType(visitor.viewVariableName, typeNameDecider),
                            b.copy(visitor.viewVariableName), convertViewVar.varName());
                } else if (visitor.viewVariableAssignment != null) {
                    assignConvertViewToView = b.toStmt(
                            b.assign(b.copy(visitor.viewVariableName), ASSIGN, convertViewVar.varName()));
                }
                if (assignConvertViewToView != null) {
                    r.insertBefore(assignConvertViewToView, visitor.viewAssignmentStmt);
                }
            }

            // make sure method returns the view to be reused
            if (visitor.returnStmt != null) {
                r.insertAfter(b.return0(b.copy(visitor.viewVariableName)), visitor.returnStmt);
                r.remove(visitor.returnStmt);
            }

            // Optimize findViewById calls
            final FindViewByIdVisitor findViewByIdVisitor = new FindViewByIdVisitor(visitor.viewVariableName);
            body.accept(findViewByIdVisitor);
            if (!findViewByIdVisitor.items.isEmpty()) {
                // TODO JNR name conflict? Use VariableNameDecider
                Variable viewHolderItemVar = new Variable("ViewHolderItem", "viewHolderItem", b);

                // create ViewHolderItem class
                r.insertBefore(createViewHolderItemClass(findViewByIdVisitor, viewHolderItemVar.typeName(),
                        typeNameDecider), node);

                // declare viewhHolderItem object
                r.insertFirst(body, Block.STATEMENTS_PROPERTY, viewHolderItemVar.declareStmt());
                // initialize viewHolderItem
                thenStmts.add(b.toStmt(
                        b.assign(viewHolderItemVar.varName(), ASSIGN, b.new0(viewHolderItemVar.type()))));
                // Assign findViewById to ViewHolderItem
                for (FindViewByIdVisitor.FindViewByIdItem item : findViewByIdVisitor.items) {
                    // ensure we are accessing convertView object
                    FieldAccess fieldAccess = b.fieldAccess(viewHolderItemVar.varName(),
                            b.simpleName(item.variable.getIdentifier()));
                    // FIXME This does not work: not sure why??
                    // r.set(item.findViewByIdInvocation,
                    // MethodInvocation.EXPRESSION_PROPERTY, convertViewVar.varName());
                    item.findViewByIdInvocation.setExpression(convertViewVar.varName());
                    // FIXME For some reason b.copy() does not do what we would like
                    thenStmts
                            .add(b.toStmt(b.assign(fieldAccess, ASSIGN, b.copySubtree(item.findViewByIdExpr))));

                    // replace previous findViewById with accesses to viewHolderItem
                    r.replace(item.findViewByIdExpr, b.copy(fieldAccess));
                }
                // store viewHolderItem in convertView
                thenStmts.add(b.toStmt(b.invoke("convertView", "setTag", viewHolderItemVar.varName())));

                // retrieve viewHolderItem from convertView
                ifStmt.setElseStatement(b.block(b.toStmt(b.assign(viewHolderItemVar.varName(), ASSIGN,
                        b.cast(viewHolderItemVar.type(), b.invoke("convertView", "getTag"))))));
            }
            r.remove(visitor.viewAssignmentStmt);
            return DO_NOT_VISIT_SUBTREE;
        }
    }
    return VISIT_SUBTREE;
}

From source file:org.autorefactor.refactoring.rules.AndroidWakeLockRefactoring.java

License:Open Source License

@Override
public boolean visit(MethodInvocation node) {
    if (isMethod(node, "android.os.PowerManager.WakeLock", "release")) {
        // check whether it is being called in onDestroy()
        MethodDeclaration enclosingMethod = getAncestor(node, MethodDeclaration.class);
        if (isMethod(enclosingMethod, "android.app.Activity", "onDestroy")) {
            final Refactorings r = ctx.getRefactorings();
            TypeDeclaration typeDeclaration = getAncestor(enclosingMethod, TypeDeclaration.class);
            MethodDeclaration onPauseMethod = findMethod(typeDeclaration, "onPause");
            if (onPauseMethod != null && node.getParent().getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
                r.remove(node.getParent());
                r.insertLast(onPauseMethod.getBody(), Block.STATEMENTS_PROPERTY,
                        createWakelockReleaseStmt(node));
            } else {
                // Add the missing onPause() method to the class.
                r.insertAfter(createOnPauseMethodDeclaration(), enclosingMethod);
            }// w  ww .j  a va 2  s.c  om
            return DO_NOT_VISIT_SUBTREE;
        }
    } else if (isMethod(node, "android.os.PowerManager.WakeLock", "acquire")) {
        final Refactorings r = ctx.getRefactorings();
        TypeDeclaration typeDeclaration = getAncestor(node, TypeDeclaration.class);
        ReleasePresenceChecker releasePresenceChecker = new ReleasePresenceChecker();
        if (!releasePresenceChecker.findOrDefault(typeDeclaration, false)) {
            MethodDeclaration onPauseMethod = findMethod(typeDeclaration, "onPause");
            if (onPauseMethod != null && node.getParent().getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
                r.insertLast(onPauseMethod.getBody(), Block.STATEMENTS_PROPERTY,
                        createWakelockReleaseStmt(node));
            } else {
                r.insertLast(typeDeclaration, typeDeclaration.getBodyDeclarationsProperty(),
                        createOnPauseMethodDeclaration());
            }
            return DO_NOT_VISIT_SUBTREE;
        }
    }
    return VISIT_SUBTREE;
}

From source file:org.autorefactor.refactoring.rules.EntrySetRatherThanKeySetAndValueSearchRefactoring.java

License:Open Source License

private void replaceEntryIterationByKeyIteration(EnhancedForStatement enhancedFor,
        final Expression mapExpression, final SingleVariableDeclaration parameter,
        final List<MethodInvocation> getValueMis) {
    final ASTBuilder b = ctx.getASTBuilder();
    final Refactorings r = ctx.getRefactorings();

    final VariableDefinitionsUsesVisitor keyUseVisitor = new VariableDefinitionsUsesVisitor(parameter);
    enhancedFor.getBody().accept(keyUseVisitor);
    int keyUses = keyUseVisitor.getUses().size();

    final int insertionPoint = asList(enhancedFor.getBody()).get(0).getStartPosition() - 1;
    final Variable entryVar = new Variable(
            new VariableNameDecider(enhancedFor.getBody(), insertionPoint).suggest("entry", "mapEntry"), b);
    final TypeNameDecider typeNameDecider = new TypeNameDecider(parameter);

    final MethodInvocation getValueMi0 = getValueMis.get(0);
    final ITypeBinding typeBinding = getValueMi0.getExpression().resolveTypeBinding();
    if (typeBinding != null && typeBinding.isRawType()) {
        // for (Object key : map.keySet()) => for (Object key : map.entrySet())
        r.set(enhancedFor, EXPRESSION_PROPERTY, b.invoke(b.move(mapExpression), "entrySet"));
        final Type objectType = b.type(typeNameDecider.useSimplestPossibleName("java.lang.Object"));
        final Variable objectVar = new Variable(
                new VariableNameDecider(enhancedFor.getBody(), insertionPoint).suggest("obj"), b);
        r.set(enhancedFor, PARAMETER_PROPERTY, b.declareSingleVariable(objectVar.varNameRaw(), objectType));

        // for (Map.Entry<K, V> mapEntry : map.entrySet()) {
        //     Map.Entry mapEntry = (Map.Entry) obj; // <--- add this statement
        //     Object key = mapEntry.getKey(); // <--- add this statement

        final Type mapKeyType = b.copy(parameter.getType());
        final VariableDeclarationStatement newKeyDecl = b.declareStmt(mapKeyType, b.move(parameter.getName()),
                b.invoke(entryVar.varName(), "getKey"));

        r.insertFirst(enhancedFor.getBody(), Block.STATEMENTS_PROPERTY, newKeyDecl);

        if (keyUses > getValueMis.size()) {
            String mapEntryTypeName = typeNameDecider.useSimplestPossibleName("java.util.Map.Entry");

            final VariableDeclarationStatement newEntryDecl = b.declareStmt(b.type(mapEntryTypeName),
                    entryVar.varName(), b.cast(b.type(mapEntryTypeName), objectVar.varName()));
            r.insertFirst(enhancedFor.getBody(), Block.STATEMENTS_PROPERTY, newEntryDecl);
        }//w  ww  . j a  v  a 2s.c  o m
    } else {
        // for (K key : map.keySet()) => for (K key : map.entrySet())
        r.set(enhancedFor, EXPRESSION_PROPERTY, b.invoke(b.move(mapExpression), "entrySet"));
        // for (K key : map.entrySet()) => for (Map.Entry<K, V> mapEntry : map.entrySet())
        final Type mapEntryType = createMapEntryType(parameter, getValueMi0, typeNameDecider);
        r.set(enhancedFor, PARAMETER_PROPERTY, b.declareSingleVariable(entryVar.varNameRaw(), mapEntryType));

        if (keyUses > getValueMis.size()) {
            // for (Map.Entry<K, V> mapEntry : map.entrySet()) {
            //     K key = mapEntry.getKey(); // <--- add this statement
            final Type mapKeyType = b.copy(parameter.getType());

            final VariableDeclarationStatement newKeyDeclaration = b.declareStmt(mapKeyType,
                    b.move(parameter.getName()), b.invoke(entryVar.varName(), "getKey"));
            r.insertFirst(enhancedFor.getBody(), Block.STATEMENTS_PROPERTY, newKeyDeclaration);
        }
    }

    // Replace all occurrences of map.get(key) => mapEntry.getValue()
    for (MethodInvocation getValueMi : getValueMis) {
        r.replace(getValueMi, b.invoke(entryVar.varName(), "getValue"));
    }
}

From source file:org.autorefactor.refactoring.rules.ViewHolderRefactoring.java

License:Open Source License

@Override
public boolean visit(MethodDeclaration node) {
    final ASTBuilder b = this.ctx.getASTBuilder();
    final Refactorings r = this.ctx.getRefactorings();
    IMethodBinding methodBinding = node.resolveBinding();

    if (methodBinding != null && isMethod(methodBinding, "android.widget.Adapter", "getView", "int",
            "android.view.View", "android.view.ViewGroup")) {
        GetViewVisitor visitor = new GetViewVisitor();
        Block body = node.getBody();/* w ww.  j  a  v a  2 s  .  com*/
        if (body != null) {
            body.accept(visitor);
            if (!visitor.usesConvertView && visitor.viewVariable != null && !visitor.isInflateInsideIf()) {
                // Transform tree

                //Create If statement
                IfStatement ifStatement = b.getAST().newIfStatement();
                // test-clause
                InfixExpression infixExpression = b.getAST().newInfixExpression();
                infixExpression.setOperator(InfixExpression.Operator.EQUALS);
                infixExpression.setLeftOperand(b.simpleName("convertView"));
                infixExpression.setRightOperand(b.getAST().newNullLiteral());
                ifStatement.setExpression(infixExpression);
                //then
                Assignment assignment = b.assign(b.simpleName("convertView"), Assignment.Operator.ASSIGN,
                        b.copy(visitor.getInflateExpression()));
                Block thenBlock = b.block(b.getAST().newExpressionStatement(assignment));
                ifStatement.setThenStatement(thenBlock);
                r.insertBefore(ifStatement, visitor.viewAssignmentStatement);

                // assign to local view variable when necessary
                if (!"convertView".equals(visitor.viewVariable.getIdentifier())) {
                    Statement assignConvertViewToView = null;
                    if (visitor.viewVariableDeclarationFragment != null) {
                        assignConvertViewToView = b.declare(visitor.viewVariable.resolveTypeBinding().getName(),
                                b.copy(visitor.viewVariable), b.simpleName("convertView"));
                    } else if (visitor.viewVariableAssignment != null) {
                        assignConvertViewToView = b.getAST()
                                .newExpressionStatement(b.assign(b.copy(visitor.viewVariable),
                                        Assignment.Operator.ASSIGN, b.simpleName("convertView")));
                    }
                    if (assignConvertViewToView != null) {
                        r.insertBefore(assignConvertViewToView, visitor.viewAssignmentStatement);
                    }
                }

                // make sure method returns the view to be reused DELETEME
                if (visitor.returnStatement != null) {
                    r.insertAfter(b.return0(b.copy(visitor.viewVariable)), visitor.returnStatement);
                    r.remove(visitor.returnStatement);
                }

                //Optimize findViewById calls
                FindViewByIdVisitor findViewByIdVisitor = new FindViewByIdVisitor();
                body.accept(findViewByIdVisitor);
                if (findViewByIdVisitor.items.size() > 0) {
                    //create ViewHolderItem class
                    TypeDeclaration viewHolderItemDeclaration = b.getAST().newTypeDeclaration();
                    viewHolderItemDeclaration.setName(b.simpleName("ViewHolderItem"));
                    List<ASTNode> viewItemsDeclarations = viewHolderItemDeclaration.bodyDeclarations();
                    for (FindViewByIdVisitor.FindViewByIdItem item : findViewByIdVisitor.items) {

                        VariableDeclarationFragment declarationFragment = b.getAST()
                                .newVariableDeclarationFragment();
                        SimpleName simpleName = b.simpleName(item.variable.getIdentifier());
                        declarationFragment.setName(simpleName);
                        FieldDeclaration fieldDeclaration = b.getAST().newFieldDeclaration(declarationFragment);
                        fieldDeclaration.setType(b.getAST()
                                .newSimpleType(b.simpleName(item.variable.resolveTypeBinding().getName())));
                        viewItemsDeclarations.add(fieldDeclaration);
                    }
                    viewHolderItemDeclaration.modifiers()
                            .add(b.getAST().newModifier(ModifierKeyword.STATIC_KEYWORD));
                    r.insertBefore(viewHolderItemDeclaration, node);
                    // create viewhHolderItem object
                    VariableDeclarationStatement viewHolderItemVariableDeclaration = b.declare("ViewHolderItem",
                            b.simpleName("viewHolderItem"), null);
                    r.insertAt(viewHolderItemVariableDeclaration, 0, Block.STATEMENTS_PROPERTY, body);
                    //initialize viewHolderItem
                    Assignment viewHolderItemInitialization = b.assign(b.simpleName("viewHolderItem"),
                            Assignment.Operator.ASSIGN, b.new0("ViewHolderItem"));
                    thenBlock.statements().add(b.getAST().newExpressionStatement(viewHolderItemInitialization));
                    //  Assign findViewById to ViewHolderItem
                    for (FindViewByIdVisitor.FindViewByIdItem item : findViewByIdVisitor.items) {
                        //ensure we are accessing to convertView object
                        QualifiedName qualifiedName = b.getAST().newQualifiedName(b.name("viewHolderItem"),
                                b.simpleName(item.variable.getIdentifier()));
                        item.findViewByIdInvocation.setExpression(b.simpleName("convertView"));
                        Assignment itemAssignment = b.assign(qualifiedName, Assignment.Operator.ASSIGN,
                                (Expression) ASTNode.copySubtree(b.getAST(), item.findViewByIdExpression));

                        thenBlock.statements().add(b.getAST().newExpressionStatement(itemAssignment));

                        //replace previous fidnviewbyid with accesses to viewHolderItem
                        QualifiedName viewHolderItemFieldAccessQualifiedName = b.getAST().newQualifiedName(
                                b.name("viewHolderItem"), b.simpleName(item.variable.getIdentifier()));
                        r.replace(item.findViewByIdExpression, b.copy(qualifiedName));
                    }
                    //store viewHolderItem in convertView
                    MethodInvocation setTagInvocation = b.invoke("convertView", "setTag",
                            b.simpleName("viewHolderItem"));
                    thenBlock.statements().add(b.getAST().newExpressionStatement(setTagInvocation));

                    //retrieve viewHolderItem from convertView
                    ifStatement
                            .setElseStatement(b.block(b.getAST()
                                    .newExpressionStatement(b.assign(b.simpleName("viewHolderItem"),
                                            Assignment.Operator.ASSIGN,
                                            b.cast("ViewHolderItem", b.invoke("convertView", "getTag"))))));

                }
                r.remove(visitor.viewAssignmentStatement);
                return DO_NOT_VISIT_SUBTREE;
            }
        }
    }
    return VISIT_SUBTREE;
}

From source file:org.autorefactor.refactoring.rules.WakeLockRefactoring.java

License:Open Source License

@Override
public boolean visit(MethodInvocation node) {
    if (isMethod(node, "android.os.PowerManager.WakeLock", "release")) {
        // check whether it is being called in onDestroy
        final Refactorings r = this.ctx.getRefactorings();
        final ASTBuilder b = this.ctx.getASTBuilder();
        MethodDeclaration enclosingMethod = (MethodDeclaration) ASTNodes.getParent(node,
                ASTNode.METHOD_DECLARATION);
        if (isMethod(enclosingMethod.resolveBinding(), "android.app.Activity", "onDestroy")) {
            TypeDeclaration typeDeclaration = (TypeDeclaration) ASTNodes.getParent(enclosingMethod,
                    TypeDeclaration.class);
            MethodDeclaration onPauseMethod = findMethodOfType("onPause", typeDeclaration);
            if (onPauseMethod != null && node.getParent().getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
                Statement releaseNode = createWakelockReleaseNode(node);
                r.remove(node.getParent());
                r.insertAt(releaseNode, onPauseMethod.getBody().statements().size(), Block.STATEMENTS_PROPERTY,
                        onPauseMethod.getBody());
                return DO_NOT_VISIT_SUBTREE;
            }/*from   ww  w.  j a  v  a 2 s  .c om*/
            /* If it reaches this part of the code, it
             * means it did not find onPause method in the class.
             */
            MethodDeclaration onPauseDeclaration = createOnPauseDeclaration();

            // add onPause declaration to the Activity
            r.insertAfter(onPauseDeclaration, enclosingMethod);
            return DO_NOT_VISIT_SUBTREE;

        }
    } else if (isMethod(node, "android.os.PowerManager.WakeLock", "acquire")) {
        final Refactorings r = this.ctx.getRefactorings();
        final ASTBuilder b = this.ctx.getASTBuilder();
        TypeDeclaration typeDeclaration = (TypeDeclaration) ASTNodes.getParent(node, ASTNode.TYPE_DECLARATION);
        ReleasePresenceChecker releasePresenceChecker = new ReleasePresenceChecker();
        typeDeclaration.accept(releasePresenceChecker);
        if (!releasePresenceChecker.releasePresent) {
            Statement releaseNode = createWakelockReleaseNode(node);
            MethodDeclaration onPauseMethod = findMethodOfType("onPause", typeDeclaration);
            if (onPauseMethod != null && node.getParent().getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
                r.insertAt(releaseNode, onPauseMethod.getBody().statements().size(), Block.STATEMENTS_PROPERTY,
                        onPauseMethod.getBody());
                return DO_NOT_VISIT_SUBTREE;
            } else {
                MethodDeclaration onPauseDeclaration = createOnPauseDeclaration();
                /* TODO @JnRouvignac, instead of using insertAt, calling 
                 * typeDeclaration.bodyDeclarations().add(onPauseDeclaration);
                 * would be more intuitive.
                 */
                r.insertAt(onPauseDeclaration, typeDeclaration.bodyDeclarations().size(),
                        typeDeclaration.getBodyDeclarationsProperty(), typeDeclaration);
                return DO_NOT_VISIT_SUBTREE;
            }
        }
    }
    return VISIT_SUBTREE;
}

From source file:org.eclipse.andmore.android.model.java.ActivityClass.java

License:Apache License

@Override
protected void addComments() throws AndroidException {
    ASTNode todoComment;/*from   w ww. j av  a 2s .  com*/

    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(document.get().toCharArray());

    compUnit = (CompilationUnit) parser.createAST(null);
    ast = compUnit.getAST();
    rewrite = ASTRewrite.create(ast);

    todoComment = rewrite.createStringPlaceholder(CodeUtilsNLS.MODEL_Common_ToDoPutYourCodeHere,
            ASTNode.EMPTY_STATEMENT);

    TypeDeclaration activityClass = (TypeDeclaration) compUnit.types().get(0);
    MethodDeclaration method;
    Block block;

    // Adds the Override annotation and ToDo comment to all overridden
    // methods
    for (int i = 0; i < activityClass.bodyDeclarations().size(); i++) {
        method = (MethodDeclaration) activityClass.bodyDeclarations().get(i);

        // Adds the Override annotation
        rewrite.getListRewrite(method, method.getModifiersProperty()).insertFirst(OVERRIDE_ANNOTATION, null);

        // Adds the ToDo comment
        block = method.getBody();
        rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY).insertLast(todoComment, null);
    }

    try {
        // Writes the modifications
        TextEdit modifications = rewrite.rewriteAST(document, null);
        modifications.apply(document);
    } catch (IllegalArgumentException e) {
        String errMsg = NLS.bind(CodeUtilsNLS.EXC_JavaClass_ErrorApplyingCommentsToCode, className);

        AndmoreLogger.error(ActivityClass.class, errMsg, e);
        throw new AndroidException(errMsg);
    } catch (MalformedTreeException e) {
        String errMsg = NLS.bind(CodeUtilsNLS.EXC_JavaClass_ErrorApplyingCommentsToCode, className);

        AndmoreLogger.error(ActivityClass.class, errMsg, e);
        throw new AndroidException(errMsg);
    } catch (BadLocationException e) {
        String errMsg = NLS.bind(CodeUtilsNLS.EXC_JavaClass_ErrorApplyingCommentsToCode, className);

        AndmoreLogger.error(ActivityClass.class, errMsg, e);
        throw new AndroidException(errMsg);
    }
}