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

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

Introduction

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

Prototype

public ReturnStatement newReturnStatement() 

Source Link

Document

Creates a new unparented return statement node owned by this AST.

Usage

From source file:cn.ieclipse.adt.ext.jdt.SourceGenerator.java

License:Apache License

private static void merge(CompilationUnit unit, String pkgName, String typeName, String auth, String dbName,
        List<String> tableCreators) {
    unit.recordModifications();//from   www .ja  va2  s . c o  m
    AST ast = unit.getAST();
    TypeDeclaration type = (TypeDeclaration) unit.types().get(0);
    ImportDeclaration id = ast.newImportDeclaration();
    id.setName(ast.newName("cn.ieclipse.aorm.Session"));
    unit.imports().add(id);

    id = ast.newImportDeclaration();
    id.setName(ast.newName("android.content.UriMatcher"));
    unit.imports().add(id);

    id = ast.newImportDeclaration();
    id.setName(ast.newName("android.database.sqlite.SQLiteDatabase"));
    unit.imports().add(id);

    id = ast.newImportDeclaration();
    id.setName(ast.newName("android.database.sqlite.SQLiteOpenHelper"));
    unit.imports().add(id);

    id = ast.newImportDeclaration();
    id.setName(ast.newName("java.net.Uri"));
    unit.imports().add(id);

    id = ast.newImportDeclaration();
    id.setName(ast.newName("android.content.ContentValue"));
    unit.imports().add(id);

    VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment();
    vdf.setName(ast.newSimpleName("AUTH"));
    StringLiteral sl = ast.newStringLiteral();
    sl.setLiteralValue(auth);
    vdf.setInitializer(sl);

    FieldDeclaration fd = ast.newFieldDeclaration(vdf);
    fd.modifiers().addAll(ast.newModifiers((Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL)));
    fd.setType(ast.newSimpleType(ast.newSimpleName("String")));

    int i = 0;
    type.bodyDeclarations().add(i++, fd);

    // URI = Uri.parse("content://" + AUTH);
    vdf = ast.newVariableDeclarationFragment();
    vdf.setName(ast.newSimpleName("URI"));

    MethodInvocation mi = ast.newMethodInvocation();
    mi.setExpression(ast.newSimpleName("Uri"));
    mi.setName(ast.newSimpleName("parse"));

    InfixExpression fix = ast.newInfixExpression();
    fix.setOperator(InfixExpression.Operator.PLUS);
    sl = ast.newStringLiteral();
    sl.setLiteralValue("content://");
    fix.setLeftOperand(sl);
    fix.setRightOperand(ast.newSimpleName("AUTH"));

    mi.arguments().add(fix);

    vdf.setInitializer(mi);
    fd = ast.newFieldDeclaration(vdf);
    fd.modifiers().addAll(ast.newModifiers((Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL)));
    fd.setType(ast.newSimpleType(ast.newSimpleName("Uri")));

    type.bodyDeclarations().add(i++, fd);

    // private mOpenHelper;
    vdf = ast.newVariableDeclarationFragment();
    vdf.setName(ast.newSimpleName("mOpenHelper"));

    fd = ast.newFieldDeclaration(vdf);
    fd.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD));
    fd.setType(ast.newSimpleType(ast.newName("SQLiteOpenHelper")));
    type.bodyDeclarations().add(i++, fd);

    // private static session;
    vdf = ast.newVariableDeclarationFragment();
    vdf.setName(ast.newSimpleName("session"));

    fd = ast.newFieldDeclaration(vdf);
    fd.modifiers().addAll(ast.newModifiers((Modifier.PRIVATE | Modifier.STATIC)));
    fd.setType(ast.newSimpleType(ast.newName("Session")));
    type.bodyDeclarations().add(i++, fd);

    // public static Session getSession(){
    // return session;
    // }

    MethodDeclaration md = ast.newMethodDeclaration();
    md.modifiers().addAll(ast.newModifiers((Modifier.PUBLIC | Modifier.STATIC)));
    md.setReturnType2(ast.newSimpleType(ast.newName("Session")));
    md.setName(ast.newSimpleName("getSession"));

    Block methodBlock = ast.newBlock();
    ReturnStatement returnStmt = ast.newReturnStatement();
    returnStmt.setExpression(ast.newSimpleName("session"));
    methodBlock.statements().add(returnStmt);
    md.setBody(methodBlock);
    type.bodyDeclarations().add(i, md);

    // modify onCreate
    rewriteOnCreate(unit, dbName, tableCreators);
}

From source file:cn.ieclipse.adt.ext.jdt.SourceGenerator.java

License:Apache License

private static void rewriteOnCreate(CompilationUnit unit, String dbName, List<String> tableCreators) {
    AST ast = unit.getAST();
    TypeDeclaration type = (TypeDeclaration) unit.types().get(0);
    MethodDeclaration onCreate = getMethod(type, ("onCreate"), null);
    if (onCreate != null) {
        Block methodBlock = ast.newBlock();

        // mOpenHelper = new
        // InlineOpenHelper(this.getContext(),"person.db",null,1);
        Assignment a = ast.newAssignment();
        a.setOperator(Assignment.Operator.ASSIGN);

        a.setLeftHandSide(ast.newSimpleName("mOpenHelper"));

        ClassInstanceCreation cc = ast.newClassInstanceCreation();
        cc.setType(ast.newSimpleType(ast.newSimpleName("SQLiteOpenHelper")));
        ThisExpression thisExp = ast.newThisExpression();
        MethodInvocation mi = ast.newMethodInvocation();
        mi.setName(ast.newSimpleName("getContext"));
        mi.setExpression(thisExp);/*w ww . java 2 s .c o m*/
        cc.arguments().add(mi);
        StringLiteral sl = ast.newStringLiteral();
        sl.setLiteralValue(dbName);

        cc.arguments().add(sl);
        cc.arguments().add(ast.newNullLiteral());
        cc.arguments().add(ast.newNumberLiteral("1"));
        a.setRightHandSide(cc);
        methodBlock.statements().add(ast.newExpressionStatement(a));

        AnonymousClassDeclaration acd = ast.newAnonymousClassDeclaration();
        cc.setAnonymousClassDeclaration(acd);
        genInnerSQLiteOpenHelper(acd, ast, tableCreators);

        a = ast.newAssignment();
        a.setOperator(Assignment.Operator.ASSIGN);

        a.setLeftHandSide(ast.newSimpleName("session"));

        ClassInstanceCreation cic = ast.newClassInstanceCreation();
        cic.setType(ast.newSimpleType(ast.newSimpleName("Session")));

        // SingleVariableDeclaration svd =
        // ast.newSingleVariableDeclaration();
        // svd.setName(ast.newSimpleName("mOpenHelper"));
        cic.arguments().add(ast.newSimpleName("mOpenHelper"));
        // vdf.setInitializer(cic);
        a.setRightHandSide(cic);
        // methodBlock.statements().add(vde);
        methodBlock.statements().add(ast.newExpressionStatement(a));

        ReturnStatement returnStmt = ast.newReturnStatement();
        returnStmt.setExpression(ast.newBooleanLiteral(true));
        methodBlock.statements().add(returnStmt);

        onCreate.setBody(methodBlock);
    }
}

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

License:Open Source License

/**
 * Add a static read accessor method for a specified variable. The generator
 * phase will rename the variable from "name" to "name_", following the Obj-C
 * style guide.//  www .  j  a v  a 2  s  . c om
 */
private MethodDeclaration makeStaticReader(VariableDeclarationFragment var, int modifiers) {
    AST ast = var.getAST();
    String varName = var.getName().getIdentifier();
    IVariableBinding varBinding = var.resolveBinding();
    String methodName;
    methodName = NameTable.getStaticAccessorName(varName);

    Type returnType = Types.makeType(varBinding.getType());
    MethodDeclaration accessor = createBlankAccessor(var, methodName, modifiers, returnType);

    ReturnStatement returnStmt = ast.newReturnStatement();
    SimpleName returnName = ast.newSimpleName(var.getName().getIdentifier() + "_");
    Types.addBinding(returnName, varBinding);
    returnStmt.setExpression(returnName);

    @SuppressWarnings("unchecked")
    List<Statement> stmts = accessor.getBody().statements(); // safe by definition
    stmts.add(returnStmt);

    GeneratedMethodBinding binding = new GeneratedMethodBinding(accessor, varBinding.getDeclaringClass(),
            false);
    Types.addBinding(accessor, binding);
    Types.addBinding(accessor.getName(), binding);
    Symbols.scanAST(accessor);
    return accessor;
}

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

License:Open Source License

/**
 * Java interfaces that redeclare java.lang.Object's equals, hashCode, or
 * toString methods need a forwarding method if the implementing class
 * relies on java.lang.Object's implementation.  This is because NSObject
 * is declared as adhering to the NSObject protocol, but doesn't explicitly
 * declare these method in its interface.  This prevents gcc from finding
 * an implementation, so it issues a warning.
 *//*from  w ww .j  a  v a 2 s  .c o  m*/
private void addForwardingMethod(AST ast, ITypeBinding typeBinding, IMethodBinding interfaceMethod,
        List<BodyDeclaration> decls) {
    Logger.getAnonymousLogger()
            .fine(String.format("adding %s to %s", interfaceMethod.getName(), typeBinding.getQualifiedName()));
    MethodDeclaration method = createInterfaceMethodBody(ast, typeBinding, interfaceMethod);

    // Add method body with single "super.method(parameters);" statement.
    Block body = ast.newBlock();
    method.setBody(body);
    SuperMethodInvocation superInvocation = ast.newSuperMethodInvocation();
    superInvocation.setName(NodeCopier.copySubtree(ast, method.getName()));

    @SuppressWarnings("unchecked")
    List<SingleVariableDeclaration> parameters = method.parameters(); // safe by design
    @SuppressWarnings("unchecked")
    List<Expression> args = superInvocation.arguments(); // safe by definition
    for (SingleVariableDeclaration param : parameters) {
        Expression arg = NodeCopier.copySubtree(ast, param.getName());
        args.add(arg);
    }
    Types.addBinding(superInvocation, Types.getMethodBinding(method));
    @SuppressWarnings("unchecked")
    List<Statement> stmts = body.statements(); // safe by definition
    ReturnStatement returnStmt = ast.newReturnStatement();
    returnStmt.setExpression(superInvocation);
    stmts.add(returnStmt);

    decls.add(method);
}

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  ww. j a  va 2 s.  com*/

    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.  ja va  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 getObjectReturnStatement(AST ast, String methodName, String parameterName) {
    ThisExpression thisExpression = ast.newThisExpression();
    MethodInvocation mi = ast.newMethodInvocation();
    mi.setExpression(thisExpression);// ww w  . j  av  a2  s  .c  om
    mi.setName(ast.newSimpleName(methodName));
    mi.arguments().add(ast.newSimpleName(parameterName));

    ReturnStatement returnStatement = ast.newReturnStatement();
    returnStatement.setExpression(mi);

    return returnStatement;
}

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

License:Open Source License

private Statement getPrimitiveReturnStatement(AST ast, String variableName) {
    ReturnStatement returnStatement = ast.newReturnStatement();
    returnStatement.setExpression(ast.newName(variableName));

    return returnStatement;
}

From source file:de.crowdcode.kissmda.cartridges.simplejava.EnumGenerator.java

License:Apache License

/**
 * Generate getter method./* ww  w .  ja va2 s  .  c  o  m*/
 * 
 * @param clazz
 *            UML2 classifier
 * @param ast
 *            JDT AST tree
 * @param ed
 *            EnumDeclaration JDT
 */
@SuppressWarnings("unchecked")
public void generateGetterMethod(Classifier clazz, AST ast, EnumDeclaration ed) {
    EList<Property> properties = clazz.getAttributes();
    for (Property property : properties) {
        Type type = property.getType();
        logger.log(Level.FINE, "Class: " + clazz.getName() + " - " + "Property: " + property.getName() + " - "
                + "Property Upper: " + property.getUpper() + " - " + "Property Lower: " + property.getLower());
        String umlTypeName = type.getName();
        String umlQualifiedTypeName = type.getQualifiedName();
        MethodDeclaration methodDeclaration = interfaceGenerator.generateGetterMethod(ast, ed, property,
                umlTypeName, umlQualifiedTypeName, sourceDirectoryPackageName);

        // Public
        methodDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));

        // Content of getter method
        Block block = ast.newBlock();
        ReturnStatement returnStatement = ast.newReturnStatement();
        SimpleName simpleName = ast.newSimpleName(property.getName());
        returnStatement.setExpression(simpleName);
        block.statements().add(returnStatement);
        methodDeclaration.setBody(block);
    }
}

From source file:de.dentrassi.varlink.generator.JdtGenerator.java

License:Open Source License

@SuppressWarnings("unchecked")
private void createImpl(final AST ast, final CompilationUnit cu, final Interface iface, final String name) {

    // create type

    final String implName = name + "Impl";

    final TypeDeclaration td = ast.newTypeDeclaration();
    cu.types().add(td);/*from w w w  .  ja  va2 s . co m*/
    td.setName(ast.newSimpleName(implName));

    make(td, PUBLIC_KEYWORD);

    final Type parentType = ast.newSimpleType(ast.newName(name));
    td.superInterfaceTypes().add(parentType);

    // create factory

    createImplFactory(ast, td);

    // create fields

    createField(td, "de.dentrassi.varlink.spi.Connection", "connection", PRIVATE_KEYWORD, FINAL_KEYWORD);
    createField(td, "de.dentrassi.varlink.internal.VarlinkImpl", "varlink", PRIVATE_KEYWORD, FINAL_KEYWORD);

    // create constructor

    final MethodDeclaration ctor = ast.newMethodDeclaration();
    td.bodyDeclarations().add(ctor);

    ctor.setConstructor(true);
    ctor.setName(ast.newSimpleName(implName));
    make(ctor, PRIVATE_KEYWORD);

    createParameter(ctor, "de.dentrassi.varlink.spi.Connection", "connection", FINAL_KEYWORD);
    createParameter(ctor, "de.dentrassi.varlink.internal.VarlinkImpl", "varlink", FINAL_KEYWORD);

    // constructor body
    {
        final Block body = ast.newBlock();
        ctor.setBody(body);

        createThisAssignment(body, "connection");
        createThisAssignment(body, "varlink");
    }

    // error mapper

    {
        final MethodDeclaration md = ast.newMethodDeclaration();
        make(md, PUBLIC_KEYWORD);
        td.bodyDeclarations().add(md);

        md.setName(ast.newSimpleName("checkError"));
        createParameter(md, "de.dentrassi.varlink.spi.CallResponse", "response", FINAL_KEYWORD);

        final Block body = ast.newBlock();
        md.setBody(body);

        final MethodInvocation mi = ast.newMethodInvocation();
        mi.setExpression(ast.newName("de.dentrassi.varlink.spi.Errors"));
        mi.setName(ast.newSimpleName("checkErrors"));
        mi.arguments().add(ast.newSimpleName("response"));

        final ExpressionMethodReference ref = ast.newExpressionMethodReference();
        ref.setExpression(ast.newThisExpression());
        ref.setName(ast.newSimpleName("mapError"));
        mi.arguments().add(ref);

        body.statements().add(ast.newExpressionStatement(mi));
    }

    {
        final MethodDeclaration md = ast.newMethodDeclaration();
        make(md, PUBLIC_KEYWORD);
        td.bodyDeclarations().add(md);

        md.setName(ast.newSimpleName("mapError"));
        createParameter(md, "java.lang.String", "error", FINAL_KEYWORD);
        createParameter(md, "de.dentrassi.varlink.spi.CallResponse", "response", FINAL_KEYWORD);
        md.setReturnType2(ast.newSimpleType(ast.newName("java.lang.RuntimeException")));

        final Block body = ast.newBlock();
        md.setBody(body);

        final SwitchStatement sw = ast.newSwitchStatement();
        body.statements().add(sw);
        sw.setExpression(ast.newSimpleName("error"));

        errors(iface).forEach(error -> {
            final String errorName = errorTypeName(error);
            final String fullErrorName = iface.getName() + "." + errorName;

            final SwitchCase sc = ast.newSwitchCase();
            sc.setExpression(JdtHelper.newStringLiteral(ast, fullErrorName));
            sw.statements().add(sc);

            final FieldAccess fa = ast.newFieldAccess();
            fa.setExpression(ast.newThisExpression());
            fa.setName(ast.newSimpleName("varlink"));

            final MethodInvocation fromJson = ast.newMethodInvocation();
            fromJson.setExpression(fa);
            fromJson.setName(ast.newSimpleName("fromJson"));

            // type name

            final TypeLiteral typeLiteral = ast.newTypeLiteral();
            typeLiteral.setType(ast.newSimpleType(ast.newName(errorName + ".Parameters")));

            fromJson.arguments().add(typeLiteral);

            // parameters

            final MethodInvocation parameters = ast.newMethodInvocation();
            parameters.setExpression(ast.newSimpleName("response"));
            parameters.setName(ast.newSimpleName("getParameters"));
            fromJson.arguments().add(parameters);

            // new exception

            final ClassInstanceCreation cic = ast.newClassInstanceCreation();
            cic.setType(ast.newSimpleType(ast.newName(errorName)));
            cic.arguments().add(fromJson);

            // return

            final ReturnStatement ret = ast.newReturnStatement();
            ret.setExpression(cic);
            sw.statements().add(ret);
        });

        {
            final SwitchCase sc = ast.newSwitchCase();
            sc.setExpression(null);
            sw.statements().add(sc);
            final ReturnStatement ret = ast.newReturnStatement();
            ret.setExpression(ast.newNullLiteral());
            sw.statements().add(ret);
        }

    }

    // async creator

    /*
     * @Override public Async async() { return new Async() {
     *
     * @Override public CompletableFuture<List<Netdev>> list() { return
     * executeList(); } }; }
     */

    {
        final MethodDeclaration md = ast.newMethodDeclaration();
        td.bodyDeclarations().add(md);

        md.setName(ast.newSimpleName("async"));
        addSimpleAnnotation(md, "Override");
        make(md, PUBLIC_KEYWORD);

        md.setReturnType2(ast.newSimpleType(ast.newName("Async")));

        final Block body = ast.newBlock();
        md.setBody(body);

        // inner class

        final ReturnStatement ret = ast.newReturnStatement();
        body.statements().add(ret);

        final ClassInstanceCreation cic = ast.newClassInstanceCreation();
        cic.setType(ast.newSimpleType(ast.newName("Async")));
        ret.setExpression(cic);

        final AnonymousClassDeclaration acc = ast.newAnonymousClassDeclaration();
        cic.setAnonymousClassDeclaration(acc);

        forMethods(ast, iface, (m, amd) -> {

            acc.bodyDeclarations().add(amd);

            amd.setName(ast.newSimpleName(m.getName()));
            make(amd, PUBLIC_KEYWORD);
            makeAsync(amd);

            final Block asyncBody = ast.newBlock();
            amd.setBody(asyncBody);

            final ReturnStatement asyncRet = ast.newReturnStatement();
            asyncBody.statements().add(asyncRet);

            final MethodInvocation mi = ast.newMethodInvocation();
            mi.setName(ast.newSimpleName(internalMethodName(m.getName())));

            for (final String argName : m.getParameters().keySet()) {
                mi.arguments().add(ast.newSimpleName(argName));
            }

            asyncRet.setExpression(mi);
        });

    }

    // internal methods

    forMethods(ast, iface, (m, md) -> {
        make(md, PROTECTED_KEYWORD);
        td.bodyDeclarations().add(md);
        md.setName(ast.newSimpleName(internalMethodName(m.getName())));
        makeAsync(md);
        createInternalMethod(td, m, md);
    });

}