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

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

Introduction

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

Prototype

ASTNode.NodeList statements

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

Click Source Link

Document

The list of statements (element type: Statement ).

Usage

From source file:com.google.googlejavaformat.java.JavaInputAstVisitor.java

License:Apache License

/**
 * Helper method for {@link Block}s, {@link CatchClause}s, {@link Statement}s,
 * {@link TryStatement}s, and {@link WhileStatement}s.
 *//*  w  w w . j  a v  a2s. c  o  m*/
private void visitBlock(Block node, CollapseEmptyOrNot collapseEmptyOrNot,
        AllowLeadingBlankLine allowLeadingBlankLine, AllowTrailingBlankLine allowTrailingBlankLine) {
    sync(node);
    if (collapseEmptyOrNot.isYes() && node.statements().isEmpty()) {
        tokenBreakTrailingComment("{", plusTwo);
        builder.blankLineWanted(BlankLineWanted.NO);
        token("}", plusTwo);
    } else {
        builder.open(ZERO);
        builder.open(plusTwo);
        tokenBreakTrailingComment("{", plusTwo);
        if (allowLeadingBlankLine == AllowLeadingBlankLine.NO) {
            builder.blankLineWanted(BlankLineWanted.NO);
        } else {
            builder.blankLineWanted(BlankLineWanted.PRESERVE);
        }
        boolean first = true;
        for (Statement statement : (List<Statement>) node.statements()) {
            builder.forcedBreak();
            if (!first) {
                builder.blankLineWanted(BlankLineWanted.PRESERVE);
            }
            first = false;
            markForPartialFormat();
            statement.accept(this);
        }
        builder.close();
        builder.forcedBreak();
        builder.close();
        if (allowTrailingBlankLine == AllowTrailingBlankLine.NO) {
            builder.blankLineWanted(BlankLineWanted.NO);
        } else {
            builder.blankLineWanted(BlankLineWanted.PRESERVE);
        }
        markForPartialFormat();
        token("}", plusTwo);
    }
}

From source file:com.ibm.wala.cast.java.translator.jdt.JDTJava2CAstTranslator.java

License:Open Source License

/**
 * Visit all the statements in the block and return an arraylist of the statements. Some statements
 * (VariableDeclarationStatements) may expand to more than one CAstNode.
 *///from  www. j ava2  s . co m
private ArrayList<CAstNode> createBlock(Block n, WalkContext context) {
    ArrayList<CAstNode> stmtNodes = new ArrayList<CAstNode>();
    for (Object s : n.statements())
        visitNodeOrNodes((ASTNode) s, context, stmtNodes);
    return stmtNodes;
}

From source file:com.idega.eclipse.ejbwizards.IBOEntityCreator.java

License:Open Source License

private void createHomeImplementation(IProgressMonitor monitor, ICompilationUnit iUnit, String typePackage,
        String name) throws JavaModelException, MalformedTreeException, BadLocationException {
    iUnit.getBuffer().setContents("");
    String source = iUnit.getBuffer().getContents();
    Document document = new Document(source);

    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(iUnit);/*from w  w  w  . j  a  v a2  s  .c  o  m*/

    CompilationUnit unit = (CompilationUnit) parser.createAST(monitor);
    unit.recordModifications();

    AST ast = unit.getAST();

    // Package statement
    PackageDeclaration packageDeclaration = ast.newPackageDeclaration();
    unit.setPackage(packageDeclaration);
    packageDeclaration.setName(ast.newName(typePackage));

    // class declaration
    TypeDeclaration classType = getTypeDeclaration(ast, name + "HomeImpl", false, "IBOHomeImpl", null,
            getHomeImplImports());
    classType.superInterfaceTypes().add(ast.newSimpleType(ast.newSimpleName(name + "Home")));
    addHomeImplImport("com.idega.business.IBOHomeImpl");
    unit.types().add(classType);

    // create() method
    MethodDeclaration methodConstructor = ast.newMethodDeclaration();
    methodConstructor.setConstructor(false);
    if (this.isJDK1_5) {
        MarkerAnnotation annotation = ast.newMarkerAnnotation();
        annotation.setTypeName(ast.newSimpleName("Override"));
        methodConstructor.modifiers().add(annotation);
    }
    methodConstructor.modifiers().addAll(ast.newModifiers(Modifier.PUBLIC));
    if (this.isJDK1_5) {
        ParameterizedType returnType = ast.newParameterizedType(ast.newSimpleType(ast.newSimpleName("Class")));
        returnType.typeArguments().add(ast.newSimpleType(ast.newSimpleName(name)));
        methodConstructor.setReturnType2(returnType);
    } else {
        methodConstructor.setReturnType2(ast.newSimpleType(ast.newSimpleName("Class")));
    }
    methodConstructor.setName(ast.newSimpleName("getBeanInterfaceClass"));

    classType.bodyDeclarations().add(methodConstructor);

    Block constructorBlock = ast.newBlock();
    methodConstructor.setBody(constructorBlock);

    TypeLiteral typeLiteral = ast.newTypeLiteral();
    typeLiteral.setType(ast.newSimpleType(ast.newSimpleName(name)));

    ReturnStatement returnStatement = ast.newReturnStatement();
    returnStatement.setExpression(typeLiteral);
    constructorBlock.statements().add(returnStatement);

    // create() method
    methodConstructor = ast.newMethodDeclaration();
    methodConstructor.setConstructor(false);
    methodConstructor.modifiers().addAll(ast.newModifiers(Modifier.PUBLIC));
    methodConstructor.setReturnType2(ast.newSimpleType(ast.newSimpleName(name)));
    methodConstructor.setName(ast.newSimpleName("create"));
    methodConstructor.thrownExceptions().add(ast.newName("CreateException"));
    addHomeImplImport("javax.ejb.CreateException");
    classType.bodyDeclarations().add(methodConstructor);

    constructorBlock = ast.newBlock();
    methodConstructor.setBody(constructorBlock);

    SuperMethodInvocation superMethodInvocation = ast.newSuperMethodInvocation();
    superMethodInvocation.setName(ast.newSimpleName("createIBO"));

    CastExpression ce = ast.newCastExpression();
    ce.setType(ast.newSimpleType(ast.newSimpleName(name)));
    ce.setExpression(superMethodInvocation);

    returnStatement = ast.newReturnStatement();
    returnStatement.setExpression(ce);
    constructorBlock.statements().add(returnStatement);

    writeImports(ast, unit, getHomeImplImports());
    commitChanges(iUnit, unit, document);
}

From source file:com.idega.eclipse.ejbwizards.IDOEntityCreator.java

License:Open Source License

private void createHomeImplementation(IProgressMonitor monitor, ICompilationUnit iUnit, String typePackage,
        String name) throws JavaModelException, MalformedTreeException, BadLocationException {
    iUnit.getBuffer().setContents("");
    String source = iUnit.getBuffer().getContents();
    Document document = new Document(source);

    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(iUnit);/*from  w  w w.j  a v a 2 s  .  co  m*/

    CompilationUnit unit = (CompilationUnit) parser.createAST(monitor);
    unit.recordModifications();

    AST ast = unit.getAST();

    // Package statement
    unit.setPackage(getPackageDeclaration(ast, typePackage));

    // class declaration
    TypeDeclaration classType = getTypeDeclaration(ast, name + "HomeImpl", false, "IDOFactory", null,
            getHomeImplImports());
    classType.superInterfaceTypes().add(ast.newSimpleType(ast.newSimpleName(name + "Home")));
    addHomeImplImport("com.idega.data.IDOFactory");
    unit.types().add(classType);

    // create() method
    MethodDeclaration methodConstructor = ast.newMethodDeclaration();
    methodConstructor.setConstructor(false);
    if (this.isJDK1_5) {
        MarkerAnnotation annotation = ast.newMarkerAnnotation();
        annotation.setTypeName(ast.newSimpleName("Override"));
        methodConstructor.modifiers().add(annotation);
    }
    methodConstructor.modifiers().addAll(ast.newModifiers(Modifier.PUBLIC));
    if (this.isJDK1_5) {
        ParameterizedType returnType = ast.newParameterizedType(ast.newSimpleType(ast.newSimpleName("Class")));
        returnType.typeArguments().add(ast.newSimpleType(ast.newSimpleName(name + "Home")));
        methodConstructor.setReturnType2(returnType);
    } else {
        methodConstructor.setReturnType2(ast.newSimpleType(ast.newSimpleName("Class")));
    }
    methodConstructor.setName(ast.newSimpleName("getEntityInterfaceClass"));

    classType.bodyDeclarations().add(methodConstructor);

    Block constructorBlock = ast.newBlock();
    methodConstructor.setBody(constructorBlock);

    TypeLiteral typeLiteral = ast.newTypeLiteral();
    typeLiteral.setType(ast.newSimpleType(ast.newSimpleName(name)));

    ReturnStatement returnStatement = ast.newReturnStatement();
    returnStatement.setExpression(typeLiteral);
    constructorBlock.statements().add(returnStatement);

    // create() method
    methodConstructor = ast.newMethodDeclaration();
    methodConstructor.setConstructor(false);
    methodConstructor.modifiers().addAll(ast.newModifiers(Modifier.PUBLIC));
    methodConstructor.setReturnType2(ast.newSimpleType(ast.newSimpleName(name)));
    methodConstructor.setName(ast.newSimpleName("create"));
    methodConstructor.thrownExceptions().add(ast.newName("CreateException"));
    addHomeImplImport("javax.ejb.CreateException");
    classType.bodyDeclarations().add(methodConstructor);

    constructorBlock = ast.newBlock();
    methodConstructor.setBody(constructorBlock);

    SuperMethodInvocation superMethodInvocation = ast.newSuperMethodInvocation();
    superMethodInvocation.setName(ast.newSimpleName("createIDO"));

    CastExpression ce = ast.newCastExpression();
    ce.setType(ast.newSimpleType(ast.newSimpleName(name)));
    ce.setExpression(superMethodInvocation);

    returnStatement = ast.newReturnStatement();
    returnStatement.setExpression(ce);
    constructorBlock.statements().add(returnStatement);

    // findByPrimarKey(Object) method
    methodConstructor = ast.newMethodDeclaration();
    methodConstructor.setConstructor(false);
    methodConstructor.modifiers().addAll(ast.newModifiers(Modifier.PUBLIC));
    methodConstructor.setReturnType2(ast.newSimpleType(ast.newSimpleName(name)));
    methodConstructor.setName(ast.newSimpleName("findByPrimaryKey"));
    methodConstructor.thrownExceptions().add(ast.newName("FinderException"));
    addHomeImplImport("javax.ejb.FinderException");
    classType.bodyDeclarations().add(methodConstructor);

    SingleVariableDeclaration variableDeclaration = ast.newSingleVariableDeclaration();
    variableDeclaration.modifiers().addAll(ast.newModifiers(Modifier.NONE));
    variableDeclaration.setType(ast.newSimpleType(ast.newSimpleName("Object")));
    variableDeclaration.setName(ast.newSimpleName("pk"));
    methodConstructor.parameters().add(variableDeclaration);

    constructorBlock = ast.newBlock();
    methodConstructor.setBody(constructorBlock);

    superMethodInvocation = ast.newSuperMethodInvocation();
    superMethodInvocation.setName(ast.newSimpleName("findByPrimaryKeyIDO"));
    superMethodInvocation.arguments().add(ast.newSimpleName("pk"));

    ce = ast.newCastExpression();
    ce.setType(ast.newSimpleType(ast.newSimpleName(name)));
    ce.setExpression(superMethodInvocation);

    returnStatement = ast.newReturnStatement();
    returnStatement.setExpression(ce);
    constructorBlock.statements().add(returnStatement);

    if (this.isLegacyEntity) {
        // createLegacy() method
        methodConstructor = ast.newMethodDeclaration();
        methodConstructor.setConstructor(false);
        methodConstructor.modifiers().addAll(ast.newModifiers(Modifier.PUBLIC));
        methodConstructor.setReturnType2(ast.newSimpleType(ast.newSimpleName(name)));
        methodConstructor.setName(ast.newSimpleName("createLegacy"));
        classType.bodyDeclarations().add(methodConstructor);

        constructorBlock = ast.newBlock();
        methodConstructor.setBody(constructorBlock);

        TryStatement tryStatement = ast.newTryStatement();
        constructorBlock.statements().add(tryStatement);
        Block tryBlock = ast.newBlock();
        tryStatement.setBody(tryBlock);

        MethodInvocation mi = ast.newMethodInvocation();
        mi.setName(ast.newSimpleName("create"));

        returnStatement = ast.newReturnStatement();
        returnStatement.setExpression(mi);
        tryBlock.statements().add(returnStatement);

        CatchClause catchClause = ast.newCatchClause();
        tryStatement.catchClauses().add(catchClause);
        variableDeclaration = ast.newSingleVariableDeclaration();
        variableDeclaration.modifiers().addAll(ast.newModifiers(Modifier.NONE));
        variableDeclaration.setType(ast.newSimpleType(ast.newSimpleName(("CreateException"))));
        variableDeclaration.setName(ast.newSimpleName("ce"));
        catchClause.setException(variableDeclaration);
        Block catchBlock = ast.newBlock();
        catchClause.setBody(catchBlock);

        ClassInstanceCreation cc = ast.newClassInstanceCreation();
        cc.setType(ast.newSimpleType(ast.newSimpleName("RuntimeException")));
        mi = ast.newMethodInvocation();
        mi.setExpression(ast.newSimpleName("ce"));
        mi.setName(ast.newSimpleName("getMessage"));
        cc.arguments().add(mi);

        ThrowStatement throwStatement = ast.newThrowStatement();
        throwStatement.setExpression(cc);
        catchBlock.statements().add(throwStatement);

        // findByPrimarKey(int) method
        methodConstructor = ast.newMethodDeclaration();
        methodConstructor.setConstructor(false);
        methodConstructor.modifiers().addAll(ast.newModifiers(Modifier.PUBLIC));
        methodConstructor.setReturnType2(ast.newSimpleType(ast.newSimpleName(name)));
        methodConstructor.setName(ast.newSimpleName("findByPrimaryKey"));
        methodConstructor.thrownExceptions().add(ast.newName("FinderException"));
        classType.bodyDeclarations().add(methodConstructor);

        variableDeclaration = ast.newSingleVariableDeclaration();
        variableDeclaration.modifiers().addAll(ast.newModifiers(Modifier.NONE));
        variableDeclaration.setType(ast.newPrimitiveType(PrimitiveType.INT));
        variableDeclaration.setName(ast.newSimpleName("id"));
        methodConstructor.parameters().add(variableDeclaration);

        constructorBlock = ast.newBlock();
        methodConstructor.setBody(constructorBlock);

        superMethodInvocation = ast.newSuperMethodInvocation();
        superMethodInvocation.setName(ast.newSimpleName("findByPrimaryKeyIDO"));
        superMethodInvocation.arguments().add(ast.newSimpleName("id"));

        ce = ast.newCastExpression();
        ce.setType(ast.newSimpleType(ast.newSimpleName(name)));
        ce.setExpression(superMethodInvocation);

        returnStatement = ast.newReturnStatement();
        returnStatement.setExpression(ce);
        constructorBlock.statements().add(returnStatement);

        // findByPrimarKeyLegacy(int) method
        methodConstructor = ast.newMethodDeclaration();
        methodConstructor.setConstructor(false);
        methodConstructor.modifiers().addAll(ast.newModifiers(Modifier.PUBLIC));
        methodConstructor.setReturnType2(ast.newSimpleType(ast.newSimpleName(name)));
        methodConstructor.setName(ast.newSimpleName("findByPrimaryKeyLegacy"));
        methodConstructor.thrownExceptions().add(ast.newName("SQLException"));
        addHomeImplImport("java.sql.SQLException");
        classType.bodyDeclarations().add(methodConstructor);

        variableDeclaration = ast.newSingleVariableDeclaration();
        variableDeclaration.modifiers().addAll(ast.newModifiers(Modifier.NONE));
        variableDeclaration.setType(ast.newPrimitiveType(PrimitiveType.INT));
        variableDeclaration.setName(ast.newSimpleName("id"));
        methodConstructor.parameters().add(variableDeclaration);

        constructorBlock = ast.newBlock();
        methodConstructor.setBody(constructorBlock);

        tryStatement = ast.newTryStatement();
        constructorBlock.statements().add(tryStatement);
        tryBlock = ast.newBlock();
        tryStatement.setBody(tryBlock);

        mi = ast.newMethodInvocation();
        mi.setName(ast.newSimpleName("findByPrimaryKey"));
        mi.arguments().add(ast.newSimpleName("id"));

        returnStatement = ast.newReturnStatement();
        returnStatement.setExpression(mi);
        tryBlock.statements().add(returnStatement);

        catchClause = ast.newCatchClause();
        tryStatement.catchClauses().add(catchClause);
        variableDeclaration = ast.newSingleVariableDeclaration();
        variableDeclaration.modifiers().addAll(ast.newModifiers(Modifier.NONE));
        variableDeclaration.setType(ast.newSimpleType(ast.newSimpleName(("FinderException"))));
        variableDeclaration.setName(ast.newSimpleName("fe"));
        catchClause.setException(variableDeclaration);
        catchBlock = ast.newBlock();
        catchClause.setBody(catchBlock);

        cc = ast.newClassInstanceCreation();
        cc.setType(ast.newSimpleType(ast.newSimpleName("SQLException")));
        mi = ast.newMethodInvocation();
        mi.setExpression(ast.newSimpleName("fe"));
        mi.setName(ast.newSimpleName("getMessage"));
        cc.arguments().add(mi);

        throwStatement = ast.newThrowStatement();
        throwStatement.setExpression(cc);
        catchBlock.statements().add(throwStatement);
    }

    MethodFilter[] validFilter = { new MethodFilter(WizardConstants.EJB_CREATE_START, MethodFilter.TYPE_PREFIX),
            new MethodFilter(WizardConstants.EJB_HOME_START, MethodFilter.TYPE_PREFIX),
            new MethodFilter(WizardConstants.EJB_FIND_START, MethodFilter.TYPE_PREFIX) };
    List methods = filterMethods(getType().getMethods(), validFilter, null);
    for (Iterator iter = methods.iterator(); iter.hasNext();) {
        IMethod method = (IMethod) iter.next();
        String fullMethodName = method.getElementName();
        String methodName = cutAwayEJBSuffix(fullMethodName);
        String[] parameterNames = method.getParameterNames();

        String returnType = method.getReturnType();
        if (fullMethodName.startsWith(WizardConstants.EJB_FIND_START)
                || fullMethodName.startsWith(WizardConstants.EJB_CREATE_START)) {
            if (!(Signature.getSimpleName(Signature.toString(method.getReturnType()))
                    .indexOf(Signature.getSimpleName("java.util.Collection")) != -1)
                    && !(Signature.getSimpleName(Signature.toString(method.getReturnType()))
                            .indexOf(Signature.getSimpleName("java.util.Set")) != -1)) {
                returnType = name;
            }
        }
        if (!returnType.equals(name)) {
            returnType = getReturnType(returnType);
        }

        methodConstructor = getMethodDeclaration(ast, method, methodName, returnType, getHomeImplImports(),
                false);
        classType.bodyDeclarations().add(methodConstructor);

        constructorBlock = ast.newBlock();
        methodConstructor.setBody(constructorBlock);

        constructorBlock.statements().add(getIDOCheckOutStatement(ast, getHomeImplImports()));

        if (fullMethodName.startsWith(WizardConstants.EJB_FIND_START)) {
            if (Signature.getSimpleName(Signature.toString(method.getReturnType()))
                    .indexOf(Signature.getSimpleName("java.util.Collection")) != -1) {
                constructorBlock.statements().add(
                        getDataCollectingStatement(ast, returnType, "ids", fullMethodName, parameterNames));
                constructorBlock.statements().add(getIDOCheckInStatement(ast));
                constructorBlock.statements()
                        .add(getObjectReturnStatement(ast, "getEntityCollectionForPrimaryKeys", "ids"));
            } else if (Signature.getSimpleName(Signature.toString(method.getReturnType()))
                    .indexOf(Signature.getSimpleName("java.util.Set")) != -1) {
                constructorBlock.statements().add(
                        getDataCollectingStatement(ast, returnType, "ids", fullMethodName, parameterNames));
                constructorBlock.statements().add(getIDOCheckInStatement(ast));
                constructorBlock.statements()
                        .add(getObjectReturnStatement(ast, "getEntitySetForPrimaryKeys", "ids"));
            } else {
                constructorBlock.statements()
                        .add(getDataCollectingStatement(ast, "Object", "pk", fullMethodName, parameterNames));
                constructorBlock.statements().add(getIDOCheckInStatement(ast));
                constructorBlock.statements().add(getObjectReturnStatement(ast, "findByPrimaryKey", "pk"));
            }
        } else if (fullMethodName.startsWith(WizardConstants.EJB_HOME_START)) {
            constructorBlock.statements().add(
                    getDataCollectingStatement(ast, returnType, "theReturn", fullMethodName, parameterNames));
            constructorBlock.statements().add(getIDOCheckInStatement(ast));
            constructorBlock.statements().add(getPrimitiveReturnStatement(ast, "theReturn"));
        } else if (fullMethodName.startsWith(WizardConstants.EJB_CREATE_START)) {
            constructorBlock.statements()
                    .add(getDataCollectingStatement(ast, "Object", "pk", fullMethodName, parameterNames));

            ce = ast.newCastExpression();
            ce.setType(ast.newSimpleType(ast.newSimpleName(getType().getTypeQualifiedName())));
            ce.setExpression(ast.newSimpleName("entity"));

            ParenthesizedExpression pe = ast.newParenthesizedExpression();
            pe.setExpression(ce);
            MethodInvocation mi = ast.newMethodInvocation();
            mi.setExpression(pe);
            mi.setName(ast.newSimpleName("ejbPostCreate"));
            constructorBlock.statements().add(ast.newExpressionStatement(mi));

            constructorBlock.statements().add(getIDOCheckInStatement(ast));

            TryStatement tryStatement = ast.newTryStatement();
            constructorBlock.statements().add(tryStatement);
            Block tryBlock = ast.newBlock();
            tryStatement.setBody(tryBlock);

            mi = ast.newMethodInvocation();
            mi.setName(ast.newSimpleName("findByPrimaryKey"));
            mi.arguments().add(ast.newSimpleName("pk"));

            returnStatement = ast.newReturnStatement();
            returnStatement.setExpression(mi);
            tryBlock.statements().add(returnStatement);

            CatchClause catchClause = ast.newCatchClause();
            tryStatement.catchClauses().add(catchClause);
            variableDeclaration = ast.newSingleVariableDeclaration();
            variableDeclaration.modifiers().addAll(ast.newModifiers(Modifier.NONE));
            variableDeclaration.setType(ast.newSimpleType(ast.newSimpleName(("FinderException"))));
            variableDeclaration.setName(ast.newSimpleName("fe"));
            catchClause.setException(variableDeclaration);
            Block catchBlock = ast.newBlock();
            catchClause.setBody(catchBlock);

            ClassInstanceCreation cc = ast.newClassInstanceCreation();
            cc.setType(ast.newSimpleType(ast.newSimpleName("IDOCreateException")));
            addHomeImplImport("com.idega.data.IDOCreateException");
            cc.arguments().add(ast.newSimpleName(("fe")));

            ThrowStatement throwStatement = ast.newThrowStatement();
            throwStatement.setExpression(cc);
            catchBlock.statements().add(throwStatement);

            catchClause = ast.newCatchClause();
            tryStatement.catchClauses().add(catchClause);
            variableDeclaration = ast.newSingleVariableDeclaration();
            variableDeclaration.modifiers().addAll(ast.newModifiers(Modifier.NONE));
            variableDeclaration.setType(ast.newSimpleType(ast.newSimpleName(("Exception"))));
            variableDeclaration.setName(ast.newSimpleName("e"));
            catchClause.setException(variableDeclaration);
            catchBlock = ast.newBlock();
            catchClause.setBody(catchBlock);

            cc = ast.newClassInstanceCreation();
            cc.setType(ast.newSimpleType(ast.newSimpleName("IDOCreateException")));
            cc.arguments().add(ast.newSimpleName(("e")));

            throwStatement = ast.newThrowStatement();
            throwStatement.setExpression(cc);
            catchBlock.statements().add(throwStatement);
        }
    }

    writeImports(ast, unit, getHomeImplImports());
    commitChanges(iUnit, unit, document);
}

From source file:com.motorola.studio.android.generatecode.AbstractCodeGenerator.java

License:Apache License

/**
 * Adds a statement into block if the statement is not already declared.
 * If the last statement is a {@link ReturnStatement}, it inserts before it, otherwise it inserts as the last statement in the block   
 * @param block// w  ww .j  a va2  s .  com
 * @param declarationStatement
 * @param sameClass true, it will compare if there is the same statement class in the body of the methodDeclaration (but the content may be different), false it will ignore the class and it will compare if the content is the same (given by toString.equals())
 */
@SuppressWarnings("unchecked")
protected void addStatementIfNotFound(Block block, Statement declarationStatement, boolean sameClass) {
    boolean alreadyDeclared = false;
    List<Statement> statements = block.statements();
    alreadyDeclared = isStatementAlreadyDeclared(declarationStatement, sameClass, statements);
    if (!alreadyDeclared) {
        Statement statement = block.statements().size() > 0
                ? (Statement) block.statements().get(block.statements().size() - 1)
                : null;
        if ((statement instanceof ReturnStatement) && !(declarationStatement instanceof ReturnStatement)) {
            //need to insert before return
            block.statements().add(block.statements().size() - 1, declarationStatement);
        } else {
            block.statements().add(declarationStatement);
        }
    }
}

From source file:com.motorola.studio.android.generatemenucode.model.codegenerators.CodeGeneratorBasedOnMenuVisitor.java

License:Apache License

/**
 * Visit method body from onCreateOptionsMenu declaration to the inflated menu
 * @param node //from   w ww  . j ava 2  s.  c  o m
 */
protected void visitMethodBodyToIdentifyMenu(MethodDeclaration node) {
    //Navigate through statements...

    Block body = node.getBody();

    if (body != null) {

        List<?> statements = body.statements();
        if (statements != null) {
            for (Object statement : statements) {

                if ((statement != null) && (statement instanceof ExpressionStatement)) {
                    Expression argumentExpression = ((ExpressionStatement) statement).getExpression();
                    if ((argumentExpression != null) && (argumentExpression instanceof MethodInvocation)) {
                        String methodSimpleName = ((MethodInvocation) argumentExpression).getName().toString();
                        if ((methodSimpleName != null) && (methodSimpleName.equals(INFLATE_METHOD))) {
                            if ((((MethodInvocation) argumentExpression).arguments() != null)
                                    && (((MethodInvocation) argumentExpression).arguments().size() > 0)) {
                                String menuBeingInflated = ((MethodInvocation) argumentExpression).arguments()
                                        .get(0).toString();
                                if ((menuBeingInflated != null) && (menuBeingInflated.indexOf('.') > 0)) {
                                    setInflatedMenuName(
                                            menuBeingInflated.substring(menuBeingInflated.lastIndexOf('.') + 1,
                                                    menuBeingInflated.length()));
                                }
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:com.motorola.studio.android.generatemenucode.model.codegenerators.MenuHandlerCodeGenerator.java

License:Apache License

/**
 * Creates method with handle for menu items (if android:onClick) is not defined on menu.xml
 * <code>public boolean onOptionsItemSelected(MenuItem item)</code>
 *//*ww  w  .  ja  v  a 2s.c  o m*/
@SuppressWarnings("unchecked")
private IfStatement createOnOptionsItemSelectedForMenuItems(MenuItemNode node) {
    IfStatement ifSt;
    //declare method
    MethodDeclaration methodDeclaration = addMethodDeclaration(ModifierKeyword.PUBLIC_KEYWORD,
            CodeGeneratorBasedOnMenuConstants.ON_OPTIONS_ITEM_SELECTED, PrimitiveType.BOOLEAN,
            CodeGeneratorBasedOnMenuConstants.MENU_ITEM, CodeGeneratorBasedOnMenuConstants.ITEM);
    MethodDeclaration foundMethod = isMethodAlreadyDeclared(methodDeclaration,
            ON_OPTIONS_ITEM_SELECTED_MENU_ITEM_METHODBINDING);
    Block block = null;
    if (foundMethod != null) {
        //method onOptionsItemSelected is already created => use the found method instead of the new created one
        methodDeclaration = foundMethod;
        block = methodDeclaration.getBody();
    } else {
        //method onOptionsItemSelected not found => create block to insert statements
        block = typeDeclaration.getAST().newBlock();
        methodDeclaration.setBody(block);
    }
    //create if and else-if's
    ifSt = createElseIfForEachMenuItemId(node);
    IfStatement foundIfStatement = (IfStatement) findIfStatementAlreadyDeclared(ifSt, true, block.statements());
    if (foundIfStatement != null) {
        ifSt = foundIfStatement;
    } else {
        //if not existent yet then:
        //1-add else
        addingElseExpression(ifSt, methodDeclaration);
        //2-add if statement only if there is not another one 
        addStatementIfNotFound(block, ifSt, true);
    }
    createReturnStatement(methodDeclaration);
    if (foundMethod == null) {
        //method onOptionsItemSelected was not yet declared
        typeDeclaration.bodyDeclarations().add(methodDeclaration);
    }
    return ifSt;
}

From source file:com.motorola.studio.android.generateviewbylayout.codegenerators.RadioButtonCodeGenerator.java

License:Apache License

/**
 * Creates field with an anonymous class declaration for radio buttons
 *//*from w w w. ja  va 2 s .  c  om*/
@SuppressWarnings("unchecked")
private IfStatement createOnClickListenerForRadioButtons(LayoutNode node) {
    IfStatement ifSt;
    Modifier privateMod = typeDeclaration.getAST().newModifier(ModifierKeyword.PRIVATE_KEYWORD);
    SimpleType listenerType = getListenerSimpleType(JavaViewBasedOnLayoutModifierConstants.VIEW_CLASS,
            JavaViewBasedOnLayoutModifierConstants.METHOD_ON_CLICK_LISTENER);

    VariableDeclarationFragment variableFragment = typeDeclaration.getAST().newVariableDeclarationFragment();
    SimpleName varName = variableFragment.getAST()
            .newSimpleName(JavaViewBasedOnLayoutModifierConstants.HANDLER_ONCLICK_LISTENER);
    variableFragment.setName(varName);
    FieldDeclaration declaration = typeDeclaration.getAST().newFieldDeclaration(variableFragment);
    declaration.modifiers().add(privateMod);
    declaration.setType(listenerType);

    ClassInstanceCreation classInstanceCreation = typeDeclaration.getAST().newClassInstanceCreation();

    SimpleType listenerType2 = getListenerSimpleType(JavaViewBasedOnLayoutModifierConstants.VIEW_CLASS,
            JavaViewBasedOnLayoutModifierConstants.METHOD_ON_CLICK_LISTENER);

    classInstanceCreation.setType(listenerType2);
    AnonymousClassDeclaration classDeclaration = typeDeclaration.getAST().newAnonymousClassDeclaration();
    MethodDeclaration methodDeclaration = addMethodDeclaration(ModifierKeyword.PUBLIC_KEYWORD,
            JavaViewBasedOnLayoutModifierConstants.METHOD_NAME_ON_CLICK, PrimitiveType.VOID,
            JavaViewBasedOnLayoutModifierConstants.VIEW_CLASS,
            JavaViewBasedOnLayoutModifierConstants.VIEW_VARIABLE_NAME);
    Block block = typeDeclaration.getAST().newBlock();
    ifSt = createElseIfForEachRadioButtonId(node);
    block.statements().add(ifSt);
    methodDeclaration.setBody(block);
    classDeclaration.bodyDeclarations().add(methodDeclaration);
    classInstanceCreation.setAnonymousClassDeclaration(classDeclaration);
    variableFragment.setInitializer(classInstanceCreation);
    typeDeclaration.bodyDeclarations().add(declaration);
    return ifSt;
}

From source file:com.motorola.studio.android.model.java.JavaClass.java

License:Apache License

/**
 * Adds an empty block to a method declaration
 * //  w  w  w  .j  av  a2 s  .c o  m
 * @param method The method declaration
 * @param returnType The method return type. If the method does not have one, use null
 */
@SuppressWarnings("unchecked")
protected void addEmptyBlock(MethodDeclaration method) {
    Expression expression = null;
    Block emptyBlock = ast.newBlock();
    ReturnStatement returnStatement = ast.newReturnStatement();
    Type returnType = method.getReturnType2();

    if (returnType instanceof PrimitiveType) {
        PrimitiveType pType = (PrimitiveType) returnType;
        if (pType.getPrimitiveTypeCode() == PrimitiveType.BOOLEAN) {
            expression = ast.newBooleanLiteral(false);
        } else if (pType.getPrimitiveTypeCode() != PrimitiveType.VOID) {
            expression = ast.newNumberLiteral("0");
        }
    } else {
        expression = ast.newNullLiteral();
    }

    if (expression != null) {
        returnStatement.setExpression(expression);
        emptyBlock.statements().add(returnStatement);
    }

    method.setBody(emptyBlock);
}

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  www .j  av  a  2 s  . c  o m*/
    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);
    }
}