Example usage for org.eclipse.jdt.core.dom AST newCastExpression

List of usage examples for org.eclipse.jdt.core.dom AST newCastExpression

Introduction

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

Prototype

public CastExpression newCastExpression() 

Source Link

Document

Creates and returns a new unparented cast expression node owned by this AST.

Usage

From source file:com.google.devtools.j2cpp.translate.DeadCodeEliminator.java

License:Open Source License

/**
 * Adds a nullary constructor that invokes a superclass constructor with
 * default arguments.// ww  w .jav  a2 s .c om
 */
@SuppressWarnings("unchecked")
private void generateConstructor(TypeDeclaration node) {
    ITypeBinding clazz = node.resolveBinding();
    IMethodBinding superConstructor = getVisible(getConstructors(clazz.getSuperclass())).next();

    // Add an explicit constructor that calls super with suitable default arguments.
    AST ast = node.getAST();
    MethodDeclaration constructor = ast.newMethodDeclaration();
    constructor.setConstructor(true);
    constructor.setName(ast.newSimpleName(node.getName().getIdentifier()));
    constructor.modifiers().add(ast.newModifier(ModifierKeyword.PROTECTED_KEYWORD));
    node.bodyDeclarations().add(constructor);

    Block block = ast.newBlock();
    constructor.setBody(block);
    SuperConstructorInvocation invocation = ast.newSuperConstructorInvocation();
    block.statements().add(invocation);
    addAssertionError(block);

    for (ITypeBinding type : superConstructor.getParameterTypes()) {
        Expression value = getDefaultValue(ast, type);
        CastExpression cast = ast.newCastExpression();
        cast.setExpression(value);
        cast.setType(createType(ast, clazz, type));
        invocation.arguments().add(cast);
    }
}

From source file:com.google.devtools.j2objc.translate.ASTFactory.java

License:Apache License

public static CastExpression newCastExpression(AST ast, Expression expr, ITypeBinding type) {
    CastExpression cast = ast.newCastExpression();
    cast.setExpression(expr);/*  w  w  w. j a va2 s  .com*/
    cast.setType(newType(ast, type));
    Types.addBinding(cast, type);
    return cast;
}

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);//w w w.  jav  a  2 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  ww w .j av a 2 s.c o 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.idega.eclipse.ejbwizards.IDOEntityCreator.java

License:Open Source License

private Statement getDataCollectingStatement(AST ast, String returnType, String variableName, String methodName,
        String[] parameterNames) {
    VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment();
    vdf.setName(ast.newSimpleName(variableName));
    VariableDeclarationStatement vds = ast.newVariableDeclarationStatement(vdf);
    vds.setType(getType(ast, returnType));

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

    ParenthesizedExpression pe = ast.newParenthesizedExpression();
    pe.setExpression(ce);//from   w  ww  .  j a v  a2  s.c  o  m
    MethodInvocation mi = ast.newMethodInvocation();
    mi.setExpression(pe);
    mi.setName(ast.newSimpleName(methodName));
    vdf.setInitializer(mi);

    for (int i = 0; i < parameterNames.length; i++) {
        mi.arguments().add(ast.newSimpleName(parameterNames[i]));
    }

    return vds;
}

From source file:de.ovgu.cide.export.physical.ahead.ReturnExtractionHelper.java

License:Open Source License

/**
 * surround method body with try catch block.
 * //from   w w  w  .j  a  va2s .  c o  m
 * if the last statement in the body is not a return statement (can happen
 * e.g., when the last statement is a hook method), then also a dummy return
 * statement is introduced that should never occur though.
 * 
 * @param method
 */
private void surroundBodyWithTryCatch(MethodDeclaration method) {
    AST ast = method.getAST();
    Block oldBody = method.getBody();
    boolean lastStatementIsReturn = oldBody.statements()
            .get(oldBody.statements().size() - 1) instanceof ReturnStatement;

    Block newBody = ast.newBlock();
    method.setBody(newBody);

    TryStatement tryStatement = ast.newTryStatement();
    newBody.statements().add(tryStatement);
    tryStatement.setBody(oldBody);

    if (!lastStatementIsReturn && !RefactoringUtils.isVoid(method.getReturnType2())) {
        addDummyReturnStatementHack(method, oldBody);
    }

    CatchClause catchClause = ast.newCatchClause();
    SingleVariableDeclaration exceptionDeclaration = ast.newSingleVariableDeclaration();
    exceptionDeclaration.setName(ast.newSimpleName("r"));
    exceptionDeclaration.setType(createExceptionType(method));

    catchClause.setException(exceptionDeclaration);
    catchClause.setBody(ast.newBlock());
    ReturnStatement returnStatement = ast.newReturnStatement();
    FieldAccess fieldAccess = ast.newFieldAccess();
    fieldAccess.setName(ast.newSimpleName("value"));
    fieldAccess.setExpression(ast.newSimpleName("r"));
    if (RefactoringUtils.isVoid(method.getReturnType2())) {
    } else if (method.getReturnType2().isPrimitiveType()) {
        returnStatement.setExpression(fieldAccess);
    } else {
        CastExpression cast = ast.newCastExpression();
        cast.setExpression(fieldAccess);
        cast.setType((Type) ASTNode.copySubtree(ast, method.getReturnType2()));
        returnStatement.setExpression(cast);
    }
    catchClause.getBody().statements().add(returnStatement);

    tryStatement.catchClauses().add(catchClause);
}

From source file:net.sf.fast.ibatis.build.dao.DAOCustomBuilder.java

License:Apache License

/**
 * <p>//w w  w.j  a  v a  2 s.c o m
 * create the code block with user specified return type.
 * </p>
 * @param ast the ast tree.
 *         fc the configuration.
 */
@SuppressWarnings("unchecked")
public Block createBlock(AST ast, FastIbatisConfig fc) {
    Block block = ast.newBlock();
    MethodInvocation methodInvocation = ast.newMethodInvocation();
    MethodInvocation m1 = ast.newMethodInvocation();
    m1.setName(ast.newSimpleName("getSqlMapClientTemplate"));
    methodInvocation.setExpression(m1);
    methodInvocation.setName(ast.newSimpleName("queryForObject"));
    ast.newSimpleName("param");
    StringLiteral literal = ast.newStringLiteral();
    literal.setLiteralValue(Utils.stripFileExtension(fc.getXmlFileName()) + "." + fc.getMethodName());
    methodInvocation.arguments().add(literal);
    methodInvocation.arguments().add(ast.newSimpleName("param"));
    ReturnStatement rs = ast.newReturnStatement();
    CastExpression ce = ast.newCastExpression();
    ce.setExpression(methodInvocation);
    ce.setType(ast.newSimpleType(ast.newSimpleName(fc.getReturnType())));
    rs.setExpression(ce);
    block.statements().add(rs);
    return block;
}

From source file:net.sf.fast.ibatis.build.dao.DAOIntegerBuilder.java

License:Apache License

/**
 * <p>/*  www. ja v  a2  s  . c  o m*/
 * create the integer return code block.
 * mainly used to get record count from specific table.
 * </p>
 * @param ast the ast tree.
 *         fc the configuration.
 */
@SuppressWarnings("unchecked")
public Block createBlock(AST ast, FastIbatisConfig fc) {
    Block block = ast.newBlock();
    MethodInvocation methodInvocation = ast.newMethodInvocation();
    MethodInvocation m1 = ast.newMethodInvocation();
    m1.setName(ast.newSimpleName("getSqlMapClientTemplate"));
    CastExpression castExpression = ast.newCastExpression();
    castExpression.setType(ast.newSimpleType(ast.newSimpleName("Integer")));
    castExpression.setExpression(m1);

    methodInvocation.setExpression(castExpression);
    methodInvocation.setName(ast.newSimpleName("queryForObject"));
    StringLiteral literal = ast.newStringLiteral();
    literal.setLiteralValue(Utils.stripFileExtension(fc.getXmlFileName()) + "." + fc.getMethodName());
    methodInvocation.arguments().add(literal);
    methodInvocation.arguments().add(ast.newSimpleName("param"));
    ReturnStatement rs = ast.newReturnStatement();
    rs.setExpression(methodInvocation);
    block.statements().add(rs);
    return block;
}

From source file:org.eclipse.ajdt.internal.ui.editor.quickfix.UnresolvedElementsSubProcessor.java

License:Open Source License

private static boolean useExistingParentCastProposal(ICompilationUnit cu, CastExpression expression,
        Expression accessExpression, SimpleName accessSelector, ITypeBinding[] paramTypes,
        Collection proposals) {/*from  www  .j av a  2  s. com*/
    ITypeBinding castType = expression.getType().resolveBinding();
    if (castType == null) {
        return false;
    }
    if (paramTypes != null) {
        if (Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes) == null) {
            return false;
        }
    } else if (Bindings.findFieldInHierarchy(castType, accessSelector.getIdentifier()) == null) {
        return false;
    }
    ITypeBinding bindingToCast = accessExpression.resolveTypeBinding();
    if (bindingToCast != null && !bindingToCast.isCastCompatible(castType)) {
        return false;
    }

    IMethodBinding res = Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes);
    if (res != null) {
        AST ast = expression.getAST();
        ASTRewrite rewrite = ASTRewrite.create(ast);
        CastExpression newCast = ast.newCastExpression();
        newCast.setType((Type) ASTNode.copySubtree(ast, expression.getType()));
        newCast.setExpression((Expression) rewrite.createCopyTarget(accessExpression));
        ParenthesizedExpression parents = ast.newParenthesizedExpression();
        parents.setExpression(newCast);

        ASTNode node = rewrite.createCopyTarget(expression.getExpression());
        rewrite.replace(expression, node, null);
        rewrite.replace(accessExpression, parents, null);

        String label = CorrectionMessages.UnresolvedElementsSubProcessor_missingcastbrackets_description;
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CAST);
        ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, 8, image);
        proposals.add(proposal);
        return true;
    }
    return false;
}

From source file:org.evosuite.testcarver.codegen.CodeGenerator.java

License:Open Source License

@SuppressWarnings("unchecked")
private void createMethodCallStmt(final String packageName, final int logRecNo, final boolean postprocessing,
        final Block methodBlock, final AST ast) {
    // assumption: all necessary statements are created and there is one variable for reach referenced object
    final int oid = this.log.objectIds.get(logRecNo);
    final Object[] methodArgs = this.log.params.get(logRecNo);
    final String methodName = this.log.methodNames.get(logRecNo);

    final String methodDesc = this.log.descList.get(logRecNo);
    final org.objectweb.asm.Type[] methodParamTypes = org.objectweb.asm.Type.getArgumentTypes(methodDesc);

    final Class<?>[] methodParamTypeClasses = new Class[methodParamTypes.length];
    for (int i = 0; i < methodParamTypes.length; i++) {
        methodParamTypeClasses[i] = getClassForName(methodParamTypes[i].getClassName());
    }/*from  ww w .  j a v a  2 s .  co  m*/

    final String typeName = this.log.oidClassNames.get(this.log.oidRecMapping.get(oid));
    Class<?> type = getClassForName(typeName);

    //      Class<?> type;
    //      try {
    //         type = Class.forName(typeName);
    //      } catch (ClassNotFoundException e) {
    //         throw new RuntimeException(e);
    //      }

    final boolean haveSamePackage = type.getPackage().getName().equals(packageName); // TODO might be nicer...

    final Statement finalStmt;

    @SuppressWarnings("rawtypes")
    final List arguments;
    if (CaptureLog.OBSERVED_INIT.equals(methodName)) {
        /*
         * Person var0 = null;
         * {
         *    var0 = new Person();
         * }
         * catch(Throwable t)
         * {
         *    org.uni.saarland.sw.prototype.capture.PostProcessor.captureException(<logRecNo>);
         * }
         */

        // e.g. Person var0 = null;
        final String varName = this.createNewVarName(oid, typeName);
        VariableDeclarationFragment vd = ast.newVariableDeclarationFragment();
        vd.setName(ast.newSimpleName(varName));
        VariableDeclarationStatement stmt = ast.newVariableDeclarationStatement(vd);
        stmt.setType(this.createAstType(typeName, ast));
        vd.setInitializer(ast.newNullLiteral());
        methodBlock.statements().add(stmt);

        try {
            this.getConstructorModifiers(type, methodParamTypeClasses);
        } catch (Exception e) {
            e.printStackTrace();
        }

        final int constructorTypeModifiers = this.getConstructorModifiers(type, methodParamTypeClasses);
        final boolean isPublic = java.lang.reflect.Modifier.isPublic(constructorTypeModifiers);
        final boolean isReflectionAccessNeeded = !isPublic && !haveSamePackage;

        if (isReflectionAccessNeeded) {
            this.isNewInstanceMethodNeeded = true;
            final MethodInvocation mi = this.createCallMethodOrNewInstanceCallStmt(true, ast, varName, typeName,
                    methodName, methodArgs, methodParamTypes);
            arguments = null;

            final Assignment assignment = ast.newAssignment();
            assignment.setLeftHandSide(ast.newSimpleName(varName));
            assignment.setOperator(Operator.ASSIGN);

            final CastExpression cast = ast.newCastExpression();
            cast.setType(this.createAstType(typeName, ast));
            cast.setExpression(mi);
            assignment.setRightHandSide(cast);

            finalStmt = ast.newExpressionStatement(assignment);
        } else {
            // e.g. var0 = new Person();
            final ClassInstanceCreation ci = ast.newClassInstanceCreation();
            ci.setType(this.createAstType(typeName, ast));

            final Assignment assignment = ast.newAssignment();
            assignment.setLeftHandSide(ast.newSimpleName(varName));
            assignment.setOperator(Operator.ASSIGN);
            assignment.setRightHandSide(ci);

            finalStmt = ast.newExpressionStatement(assignment);
            arguments = ci.arguments();
        }
    } else //------------------ handling for ordinary method calls e.g. var1 = var0.doSth();
    {
        String returnVarName = null;

        final String desc = this.log.descList.get(logRecNo);
        final String returnType = org.objectweb.asm.Type.getReturnType(desc).getClassName();

        final Object returnValue = this.log.returnValues.get(logRecNo);
        if (!CaptureLog.RETURN_TYPE_VOID.equals(returnValue)) {
            Integer returnValueOID = (Integer) returnValue;

            // e.g. Person var0 = null;
            returnVarName = this.createNewVarName(returnValueOID, returnType);

            VariableDeclarationFragment vd = ast.newVariableDeclarationFragment();
            vd.setName(ast.newSimpleName(returnVarName));
            VariableDeclarationStatement stmt = ast.newVariableDeclarationStatement(vd);
            stmt.setType(this.createAstType(returnType, ast));
            vd.setInitializer(ast.newNullLiteral());
            methodBlock.statements().add(stmt);
        }

        final String varName = this.oidToVarMapping.get(oid);

        final int methodTypeModifiers = this.getMethodModifiers(type, methodName, methodParamTypeClasses);
        final boolean isPublic = java.lang.reflect.Modifier.isPublic(methodTypeModifiers);
        final boolean isReflectionAccessNeeded = !isPublic && !haveSamePackage;

        // e.g. Person var0 = var1.getPerson("Ben");

        final MethodInvocation mi;

        if (isReflectionAccessNeeded) {
            this.isCallMethodMethodNeeded = true;
            mi = this.createCallMethodOrNewInstanceCallStmt(false, ast, varName, typeName, methodName,
                    methodArgs, methodParamTypes);
            arguments = null;

            if (returnVarName != null) {
                final Assignment assignment = ast.newAssignment();
                assignment.setLeftHandSide(ast.newSimpleName(returnVarName));
                assignment.setOperator(Operator.ASSIGN);

                final CastExpression cast = ast.newCastExpression();
                cast.setType(this.createAstType(returnType, ast));
                cast.setExpression(mi);
                assignment.setRightHandSide(cast);

                finalStmt = ast.newExpressionStatement(assignment);
            } else {
                finalStmt = ast.newExpressionStatement(mi);
            }
        } else {
            mi = ast.newMethodInvocation();

            if (this.log.isStaticCallList.get(logRecNo)) {
                // can only happen, if this is a static method call (because constructor statement has been reported)
                final String tmpType = this.log.oidClassNames.get(this.log.oidRecMapping.get(oid));
                mi.setExpression(ast.newName(tmpType.split("\\.")));
            } else {
                mi.setExpression(ast.newSimpleName(varName));
            }

            mi.setName(ast.newSimpleName(methodName));

            arguments = mi.arguments();

            if (returnVarName != null) {
                final Assignment assignment = ast.newAssignment();
                assignment.setLeftHandSide(ast.newSimpleName(returnVarName));
                assignment.setOperator(Operator.ASSIGN);
                assignment.setRightHandSide(mi);

                finalStmt = ast.newExpressionStatement(assignment);
            } else {
                finalStmt = ast.newExpressionStatement(mi);
            }
        }
    }

    if (postprocessing) {
        final TryStatement tryStmt = this.createTryStatementForPostProcessing(ast, finalStmt, logRecNo);
        methodBlock.statements().add(tryStmt);
    } else {
        if (this.failedRecords.contains(logRecNo)) {
            // we just need an empty catch block to preserve program flow
            final TryStatement tryStmt = this.createTryStmtWithEmptyCatch(ast, finalStmt);
            methodBlock.statements().add(tryStmt);
        } else {
            methodBlock.statements().add(finalStmt);
        }
    }

    if (arguments != null) {
        //         final  String                   methodDesc       = this.log.descList.get(logRecNo);
        //         final  org.objectweb.asm.Type[] methodParamTypes = org.objectweb.asm.Type.getArgumentTypes(methodDesc);

        Class<?> methodParamType;
        Class<?> argType;

        Integer arg; // is either an oid or null
        for (int i = 0; i < methodArgs.length; i++) {
            arg = (Integer) methodArgs[i];
            if (arg == null) {
                arguments.add(ast.newNullLiteral());
            } else {
                methodParamType = CaptureUtil.getClassFromDesc(methodParamTypes[i].getDescriptor());
                argType = this.oidToTypeMapping.get(arg);

                if (methodParamType.isAssignableFrom(argType)) {
                    arguments.add(ast.newSimpleName(this.oidToVarMapping.get(arg)));
                } else {
                    // we need an up-cast
                    final CastExpression cast = ast.newCastExpression();
                    cast.setType(ast.newSimpleType(ast.newName(methodParamType.getName())));
                    cast.setExpression(ast.newSimpleName(this.oidToVarMapping.get(arg)));
                    arguments.add(cast);
                }
            }
        }
    }
}