Example usage for org.eclipse.jdt.core.dom MethodDeclaration setBody

List of usage examples for org.eclipse.jdt.core.dom MethodDeclaration setBody

Introduction

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

Prototype

public void setBody(Block body) 

Source Link

Document

Sets or clears the body of this method declaration.

Usage

From source file:ac.at.tuwien.dsg.uml.statemachine.export.transformation.engines.impl.PathWithUncertaintyTestStrategy.java

License:Open Source License

/**
 * Generates a class to be used in executing the test plan.
 * The class is abstract because at this point it is unclear how to assert that a certain state has been reached.
 * Thus, the assertStateReached will be abstract methods.
 * @param stateGraph/* w ww .  j  av  a 2  s .  c  om*/
 */
public Document generateTestPlan(StateMachineStateGraph stateGraph) {
    Document doc = new Document(
            "public abstract class TestPlanForStateMachine" + stateGraph.getStateMachineName() + " { \n");

    //from here we use the cumbersome and extremely detailed Eclipse recommended DOM/AST library
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(doc.get().toCharArray());
    CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    cu.recordModifications();
    AST ast = cu.getAST();
    ASTRewrite rewriter = ASTRewrite.create(ast);

    //create method which will contain one test plan (might be cloned and branched for each if-else in the state machine diagram)    
    MethodDeclaration testPlanMethodDeclaration = ast.newMethodDeclaration();
    testPlanMethodDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
    testPlanMethodDeclaration.setName(ast.newSimpleName("testPlan"));
    testPlanMethodDeclaration.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID)); //return true if successful or false otherwise

    //create method body
    Block testPlanMethodBody = ast.newBlock();
    testPlanMethodDeclaration.setBody(testPlanMethodBody);

    //create recursively the test plan by parsing the state graph starting with initial state
    try {
        generatePlanForState(stateGraph.getInitialState(), rewriter, testPlanMethodDeclaration,
                new HashSet<StateMachineStateTransition>());
    } catch (NoSuchStateException e) {
        e.printStackTrace();
    }

    ListRewrite listRewrite = rewriter.getListRewrite(cu, CompilationUnit.TYPES_PROPERTY);

    //add all generated abstract methods
    for (Map.Entry<String, MethodDeclaration> entry : generatedAbstractMethods.entrySet()) {
        listRewrite.insertLast(entry.getValue(), null);
    }

    if (generatedPlans.isEmpty()) {
        notifyUser("No test plans containing uncertainty states could have been generated. "
                + "\n Please ensure selected state machine has at least one state with at least one uncertainty"
                + "\n Please ensure there is at least one InitialState, one FinalState, and one path between Initial and Final states which passes through"
                + "at least one state with at least one uncertainty");
    }

    int index = 1;
    //add generated plan methods
    for (Map.Entry<String, MethodDeclaration> entry : generatedPlans.entrySet()) {
        //rename to PLAN_METHOD_LEADING + plan index from PLAN_METHOD_LEADING + UUID
        MethodDeclaration method = entry.getValue();
        method.setName(ast.newSimpleName(PLAN_METHOD_LEADING + index++));

        listRewrite.insertLast(method, null);
    }

    //add final }
    listRewrite.insertLast(rewriter.createStringPlaceholder("}\n", ASTNode.EMPTY_STATEMENT), null);

    TextEdit edits = rewriter.rewriteAST(doc, null);
    try {
        UndoEdit undo = edits.apply(doc);
    } catch (MalformedTreeException | BadLocationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println(doc.get());

    return doc;
}

From source file:ac.at.tuwien.dsg.uml.statemachine.export.transformation.engines.impl.TransitionCorrectnessTestStrategy.java

License:Open Source License

/**
 * Generates a class to be used in executing the test plan.
 * The class is abstract because at this point it is unclear how to assert that a certain state has been reached.
 * Thus, the assertStateReached will be abstract methods.
 * @param stateGraph//from ww w  .ja v  a  2 s .  c  om
 */
public Document generateTestPlan(StateMachineStateGraph stateGraph) {
    Document doc = new Document(
            "public abstract class TestPlanForStateMachine" + stateGraph.getStateMachineName() + " { \n");

    //from here we use the cumbersome and extremely detailed Eclipse recommended DOM/AST library
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(doc.get().toCharArray());
    CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    cu.recordModifications();
    AST ast = cu.getAST();
    ASTRewrite rewriter = ASTRewrite.create(ast);

    //create method which will contain one test plan (might be cloned and branched for each if-else in the state machine diagram)    
    MethodDeclaration testPlanMethodDeclaration = ast.newMethodDeclaration();
    testPlanMethodDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
    testPlanMethodDeclaration.setName(ast.newSimpleName("testPlan"));
    testPlanMethodDeclaration.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID)); //return true if successful or false otherwise

    //create method body
    Block testPlanMethodBody = ast.newBlock();
    testPlanMethodDeclaration.setBody(testPlanMethodBody);

    //create recursively the test plan by parsing the state graph starting with initial state
    try {
        generatePlanForState(stateGraph.getInitialState(), rewriter, testPlanMethodDeclaration,
                new HashSet<StateMachineStateTransition>());
    } catch (NoSuchStateException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    ListRewrite listRewrite = rewriter.getListRewrite(cu, CompilationUnit.TYPES_PROPERTY);

    //add all generated abstract methods
    for (Map.Entry<String, MethodDeclaration> entry : generatedAbstractMethods.entrySet()) {
        listRewrite.insertLast(entry.getValue(), null);
    }

    int index = 1;
    //add generated plan methods

    if (generatedPlans.isEmpty()) {
        notifyUser("No test plans could have been generated. "
                + "\n Please ensure selected state machine has at least one complete path from  initial to final state."
                + "\n Please ensure there is at least one InitialState, one FinalState, and one path between Initial and Final states");
    }

    for (Map.Entry<String, MethodDeclaration> entry : generatedPlans.entrySet()) {
        //rename to PLAN_METHOD_LEADING + plan index from PLAN_METHOD_LEADING + UUID
        MethodDeclaration method = entry.getValue();
        method.setName(ast.newSimpleName(PLAN_METHOD_LEADING + index++));

        listRewrite.insertLast(method, null);
    }

    //add final }
    listRewrite.insertLast(rewriter.createStringPlaceholder("}\n", ASTNode.EMPTY_STATEMENT), null);

    TextEdit edits = rewriter.rewriteAST(doc, null);
    try {
        UndoEdit undo = edits.apply(doc);
    } catch (MalformedTreeException | BadLocationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println(doc.get());

    return doc;
}

From source file:br.com.objectos.way.core.code.jdt.ASTTest.java

License:Apache License

@SuppressWarnings("unchecked")
public void stackoverflow_answer() {
    AST ast = AST.newAST(AST.JLS8);/*from w w  w. j  a  v  a  2  s.c o  m*/
    CompilationUnit cu = ast.newCompilationUnit();

    PackageDeclaration p1 = ast.newPackageDeclaration();
    p1.setName(ast.newSimpleName("foo"));
    cu.setPackage(p1);

    ImportDeclaration id = ast.newImportDeclaration();
    id.setName(ast.newName(new String[] { "java", "util", "Set" }));
    cu.imports().add(id);

    TypeDeclaration td = ast.newTypeDeclaration();
    td.setName(ast.newSimpleName("Foo"));
    TypeParameter tp = ast.newTypeParameter();
    tp.setName(ast.newSimpleName("X"));
    td.typeParameters().add(tp);
    cu.types().add(td);

    MethodDeclaration md = ast.newMethodDeclaration();
    md.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
    md.setName(ast.newSimpleName("bar"));

    SingleVariableDeclaration var = ast.newSingleVariableDeclaration();
    var.setType(ast.newSimpleType(ast.newSimpleName("String")));
    var.setName(ast.newSimpleName("a"));
    md.parameters().add(var);
    td.bodyDeclarations().add(md);

    Block block = ast.newBlock();
    md.setBody(block);

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

    ExpressionStatement e = ast.newExpressionStatement(mi);
    block.statements().add(e);

    System.out.println(cu);
}

From source file:ch.acanda.eclipse.pmd.java.resolution.design.UseUtilityClassQuickFix.java

License:Open Source License

@SuppressWarnings("unchecked")
private void addPrivateConstructor(final TypeDeclaration typeDeclaration, final ASTRewrite rewrite) {
    final AST ast = typeDeclaration.getAST();
    final MethodDeclaration constructor = (MethodDeclaration) ast.createInstance(MethodDeclaration.class);
    constructor.setConstructor(true);// w w w  .ja  v a2s . co  m

    final Modifier modifier = (Modifier) ast.createInstance(Modifier.class);
    modifier.setKeyword(ModifierKeyword.PRIVATE_KEYWORD);
    constructor.modifiers().add(modifier);

    constructor.setName(ASTUtil.copy(typeDeclaration.getName()));

    final Block body = (Block) ast.createInstance(Block.class);
    constructor.setBody(body);

    final ListRewrite statementRewrite = rewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY);
    final ASTNode comment = rewrite.createStringPlaceholder("// hide constructor of utility class",
            ASTNode.EMPTY_STATEMENT);
    statementRewrite.insertFirst(comment, null);

    final int position = findConstructorPosition(typeDeclaration);
    final ListRewrite bodyDeclarationRewrite = rewrite.getListRewrite(typeDeclaration,
            TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
    bodyDeclarationRewrite.insertAt(constructor, position, null);
}

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 w w  w.j av  a 2 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();/*from   www .  j  a va 2  s . c o m*/
    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);
        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:cn.ieclipse.adt.ext.jdt.SourceGenerator.java

License:Apache License

private static void genInnerSQLiteOpenHelper(AnonymousClassDeclaration acd, AST ast,
        List<String> tableCreators) {
    MethodDeclaration md = ast.newMethodDeclaration();
    md.modifiers().addAll(ast.newModifiers((Modifier.PUBLIC)));
    md.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID));
    md.setName(ast.newSimpleName("onCreate"));
    SingleVariableDeclaration svd = ast.newSingleVariableDeclaration();
    svd.setName(ast.newSimpleName("db"));
    svd.setType(ast.newSimpleType(ast.newSimpleName("SQLiteDatabase")));
    md.parameters().add(svd);/*  ww  w.ja  v a 2  s .c  o m*/
    Block innerBlock = ast.newBlock();
    md.setBody(innerBlock);
    VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment();
    vdf.setName(ast.newSimpleName("sql"));
    StringLiteral sl = ast.newStringLiteral();
    sl.setLiteralValue("");
    vdf.setInitializer(sl);
    VariableDeclarationStatement vds = ast.newVariableDeclarationStatement(vdf);
    vds.setType(ast.newSimpleType(ast.newSimpleName("String")));
    innerBlock.statements().add(vds);
    for (String creator : tableCreators) {
        String[] lines = creator.split(SourceAnalysis.LF);
        for (String line : lines) {
            Assignment a = ast.newAssignment();
            a.setOperator(Assignment.Operator.PLUS_ASSIGN);
            a.setLeftHandSide(ast.newSimpleName("sql"));
            StringLiteral temp = ast.newStringLiteral();
            temp.setLiteralValue(line);
            a.setRightHandSide(temp);
            innerBlock.statements().add(ast.newExpressionStatement(a));
        }

        MethodInvocation mi = ast.newMethodInvocation();
        mi.setName(ast.newSimpleName("execSQL"));
        mi.setExpression(ast.newSimpleName("db"));
        mi.arguments().add(ast.newSimpleName("sql"));
        innerBlock.statements().add(ast.newExpressionStatement(mi));
    }

    acd.bodyDeclarations().add(md);
    // onUpgrade
    md = ast.newMethodDeclaration();
    md.modifiers().addAll(ast.newModifiers((Modifier.PUBLIC)));
    md.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID));
    md.setName(ast.newSimpleName("onUpgrade"));
    svd = ast.newSingleVariableDeclaration();
    svd.setName(ast.newSimpleName("db"));
    svd.setType(ast.newSimpleType(ast.newSimpleName("SQLiteDatabase")));
    md.parameters().add(svd);

    svd = ast.newSingleVariableDeclaration();
    svd.setName(ast.newSimpleName("oldVersion"));
    svd.setType(ast.newPrimitiveType(PrimitiveType.INT));
    md.parameters().add(svd);

    svd = ast.newSingleVariableDeclaration();
    svd.setName(ast.newSimpleName("newVersion"));
    svd.setType(ast.newPrimitiveType(PrimitiveType.INT));
    md.parameters().add(svd);

    innerBlock = ast.newBlock();
    md.setBody(innerBlock);
    acd.bodyDeclarations().add(md);
}

From source file:com.crispico.flower.codesync.tests.java.JavaTestsOnSourceCode.java

License:Open Source License

@SuppressWarnings("unchecked")
public void testMethod_Adders() {
    javaCompilationUnit = JavaSyncUtils.loadJavaFile(folder.getFile("ClassA.java"),
            ASTParser.newParser(AST.JLS3));
    javaCompilationUnit.recordModifications();
    javaClass = JavaSyncUtils.getMasterClass(javaCompilationUnit);

    SingleVariableDeclaration variableDeclaration = null;
    MethodDeclaration methodDeclaration = null;
    AST ast = javaClass.getAST();/*w  w  w  . ja v a  2 s . com*/

    methodDeclaration = ast.newMethodDeclaration();// a()
    javaClass.bodyDeclarations().add(methodDeclaration);
    methodDeclaration.setName(ast.newSimpleName("addedMethod1"));
    methodDeclaration.setReturnType2(JavaSyncUtils.getJavaTypeFromString(ast, "void"));
    methodDeclaration.setBody(ast.newBlock());

    methodDeclaration = ast.newMethodDeclaration();// a():int
    javaClass.bodyDeclarations().add(methodDeclaration);
    methodDeclaration.setName(ast.newSimpleName("addedMethod2"));
    methodDeclaration.setReturnType2(JavaSyncUtils.getJavaTypeFromString(ast, "int"));
    methodDeclaration.setBody(ast.newBlock());

    methodDeclaration = ast.newMethodDeclaration();// a(par1:String):int
    javaClass.bodyDeclarations().add(methodDeclaration);
    methodDeclaration.setName(ast.newSimpleName("addedMethod3"));
    methodDeclaration.setReturnType2(JavaSyncUtils.getJavaTypeFromString(ast, "int"));
    methodDeclaration.setBody(ast.newBlock());
    variableDeclaration = ast.newSingleVariableDeclaration();
    variableDeclaration.setName(ast.newSimpleName("par1"));
    variableDeclaration.setType(JavaSyncUtils.getJavaTypeFromString(ast, "String"));
    methodDeclaration.parameters().add(variableDeclaration);

    methodDeclaration = ast.newMethodDeclaration();// a(par1:int, par2 :ClassB) :int
    javaClass.bodyDeclarations().add(methodDeclaration);
    methodDeclaration.setName(ast.newSimpleName("addedMethod4"));
    methodDeclaration.setReturnType2(JavaSyncUtils.getJavaTypeFromString(ast, "int"));
    methodDeclaration.setBody(ast.newBlock());
    variableDeclaration = ast.newSingleVariableDeclaration();
    variableDeclaration.setName(ast.newSimpleName("par1"));
    variableDeclaration.setType(JavaSyncUtils.getJavaTypeFromString(ast, "int"));
    methodDeclaration.parameters().add(variableDeclaration);
    variableDeclaration = ast.newSingleVariableDeclaration();
    variableDeclaration.setName(ast.newSimpleName("par2"));
    variableDeclaration.setType(JavaSyncUtils.getJavaTypeFromString(ast, "ClassB"));
    methodDeclaration.parameters().add(variableDeclaration);

    methodDeclaration = ast.newMethodDeclaration();
    javaClass.bodyDeclarations().add(methodDeclaration);
    methodDeclaration.setName(ast.newSimpleName("addedMethod6"));
    methodDeclaration.setBody(ast.newBlock());
    JavaSyncUtils.updateVisibilityFromModelToJavaClass(methodDeclaration, VisibilityKind.PUBLIC_LITERAL);

    methodDeclaration = ast.newMethodDeclaration();
    javaClass.bodyDeclarations().add(methodDeclaration);
    methodDeclaration.setName(ast.newSimpleName("addedMethod7"));
    methodDeclaration.setBody(ast.newBlock());
    JavaSyncUtils.updateVisibilityFromModelToJavaClass(methodDeclaration, VisibilityKind.PROTECTED_LITERAL);

    methodDeclaration = ast.newMethodDeclaration();
    javaClass.bodyDeclarations().add(methodDeclaration);
    methodDeclaration.setName(ast.newSimpleName("addedMethod8"));
    methodDeclaration.setBody(ast.newBlock());
    JavaSyncUtils.updateVisibilityFromModelToJavaClass(methodDeclaration, VisibilityKind.PRIVATE_LITERAL);

    methodDeclaration = ast.newMethodDeclaration();
    javaClass.bodyDeclarations().add(methodDeclaration);
    methodDeclaration.setName(ast.newSimpleName("addedMethod9"));
    methodDeclaration.setBody(ast.newBlock());
    JavaSyncUtils.updateVisibilityFromModelToJavaClass(methodDeclaration, VisibilityKind.PACKAGE_LITERAL);

    synchronizeAndCompareMasterClass();
}

From source file:com.crispico.flower.mp.metamodel.codesyncjava.algorithm.forward.ForwardJavaClass_OwnedMethods.java

License:Open Source License

/**
 * @author Luiza - conditions for interface and abstract methods added
 * @flowerModelElementId _zbW4iZiOEd6aNMdNFvR5WQ
 *///from   w w w .j a  v  a 2 s. com
@SuppressWarnings("unchecked")
@Override
protected MethodDeclaration createAndAddNewASTElement(Operation modelElement,
        CompilationUnit parentAstElement) {
    TypeDeclaration parentClass = JavaSyncUtils.getMasterClass((CompilationUnit) parentAstElement);
    AST ast = parentClass.getAST();
    MethodDeclaration method = ast.newMethodDeclaration();
    if (modelElement.getName().equals(parentClass.getName().getIdentifier())) {
        //create a constructor
        method.setConstructor(true);
    }
    parentClass.bodyDeclarations().add(method);

    //if this method is not in an interface and is not an abstract method then add a body
    if (!JavaSyncUtils.getMasterClass(parentAstElement).isInterface() && !modelElement.isAbstract()) {
        Block methodBlock = ast.newBlock();
        method.setBody(methodBlock);
    }
    return method;
}

From source file:com.crispico.flower.mp.metamodel.codesyncjava.algorithm.JavaSyncUtils.java

License:Open Source License

/**
 * Creates a new block and adds it as body to the given {@link MethodDeclaration}.
 * /* w w  w .  ja v  a  2  s .  c om*/
 * @param md - the {@link MethodDeclaration} that requires a new body block.
 * @param blockString - the {@link String} that will form the block content.
 * 
 * @author Luiza
 */
public static void generateBodyForMethod(MethodDeclaration md, String blockString) {
    AST ast = md.getAST();
    ASTParser statementParser = ASTParser.newParser(AST.JLS3);
    statementParser.setKind(ASTParser.K_STATEMENTS);
    // parse the block
    statementParser.setSource(blockString.toCharArray());
    Block block = (Block) statementParser.createAST(null);
    block = (Block) ASTNode.copySubtree(ast, block);

    md.setBody(block);
}