Example usage for org.eclipse.jdt.core.dom.rewrite ASTRewrite getListRewrite

List of usage examples for org.eclipse.jdt.core.dom.rewrite ASTRewrite getListRewrite

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom.rewrite ASTRewrite getListRewrite.

Prototype

public final ListRewrite getListRewrite(ASTNode node, ChildListPropertyDescriptor property) 

Source Link

Document

Creates and returns a new rewriter for describing modifications to the given list property of the given node.

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/* ww w .j  a va 2s .  co m*/
 */
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.PathWithUncertaintyTestStrategy.java

License:Open Source License

/**
 * //  w  ww . ja  v  a 2s  .c  o m
 * @param state - the state for which we inspect the transitions and generate the test plan
 * @param rewrite - rewriter used to modify the generated code
 * @param planMethodDeclaration - the method in which the code must be added
 * @param parrentPlanBlock - the block of code where the new state code must be added. Can be a method body, the body of an If statement, etc
 * @param pathTransitions - used to avoid testing cycles and ensure test plan keeps uniqueness on transitions
 */
private void generatePlanForState(final StateMachineState state, final ASTRewrite rewrite,
        final MethodDeclaration planMethodDeclaration, final Set<StateMachineStateTransition> pathTransitions) {

    AST ast = planMethodDeclaration.getAST();
    Block parrentPlanBlock = planMethodDeclaration.getBody();

    ListRewrite listRewrite = rewrite.getListRewrite(parrentPlanBlock, Block.STATEMENTS_PROPERTY);

    /**
     * First we create an abstract method to assert that we have reached current state and we call it
     * only if the state is not a choice. Choices are "virtual" states that signal splits in transition.
     * 
     */
    {

        //only create method if not previously created
        String stateName = state.getName();
        String methodName = ASSERT_STATE_LEADING + stateName;
        if (!generatedAbstractMethods.containsKey(stateName)) {
            MethodDeclaration method = createAbstractMethodForState(state, planMethodDeclaration.getAST());
            generatedAbstractMethods.put(stateName, method);
        }

        /**
         * Call the assert state method to check if we have reached the current state.
         * For the initial state this assert can also reset the system to initial state.
         */
        {
            //invoke guard as Assert statement
            AssertStatement assertStatement = ast.newAssertStatement();
            MethodInvocation invocation = ast.newMethodInvocation();
            invocation.setName(ast.newSimpleName(methodName));
            assertStatement.setExpression(invocation);

            parrentPlanBlock.statements().add(assertStatement);

            //                  listRewrite.insertFirst(rewrite.createStringPlaceholder("//Call the assert state method to check if we have reached the current state.", ASTNode.EMPTY_STATEMENT), null);
            //                  listRewrite.insertLast(rewrite.createStringPlaceholder("//For the initial state this assert can also reset the system to initial state.", ASTNode.EMPTY_STATEMENT), null);
            //                  listRewrite.insertLast(assertStatement, null);
            //                  listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null);
        }

    }

    /**
     * If from one state we have multiple triggers, or from a choice we can go to multiple classes
     * then we generate for each of these transitions paths a separate test plan.
     * This means we clone the previous method into how many we need
     */
    List<StateMachineStateTransition> transitions = state.getOutTransitions();

    //if 1 transition, then we add to same plan
    //if more, we need separate test plans for each branching
    if (transitions.isEmpty() && !(state.getVertex() instanceof FinalState)) {
        //notify user that  something is wrong with the model we are converting 
        notifyUser("State \"" + state.getName()
                + "\"is not final and does not have any transitions. All state machine flows must reach a FinalState.");
        System.err.println(state.getName()
                + " is not final and does not have any transitions. All state machine flows must reach a FinalState to be converted in test plans.");
    } else if (transitions.size() == 1) {
        StateMachineStateTransition transition = transitions.get(0);

        //if we have visited this transition, continue
        if (pathTransitions.contains(transition)) {
            return;
        } else {
            // add transition to visited transitions
            pathTransitions.add(transition);
        }

        //                listRewrite.insertLast(rewrite.createStringPlaceholder("//Test transition " + transition.getTransition().getName(), ASTNode.EMPTY_STATEMENT), null);

        /**
         * Must assert before any transition that the guard condition is fulfilled
         */
        {
            //get transition condition (could also be Rule, currently we get only Guard transitions)
            Constraint guard = transition.getTransition().getGuard();
            if (guard != null) {
                for (Element element : guard.allOwnedElements()) {
                    //currently condition retrieved as plain text that will need to be parsed and evaluated
                    OpaqueExpression expression = (OpaqueExpression) element;
                    for (String body : expression.getBodies()) {
                        if (body.isEmpty()) {
                            notifyUser("Guard condition for transition  " + transition.getTransition().getName()
                                    + " from state " + state.getName() + " is empty");
                            System.err.println(
                                    "Guard condition for transition  " + transition.getTransition().getName()
                                            + " from state " + state.getName() + " is empty");
                            continue;
                        }
                        MethodDeclaration method = createAbstractMethodForGuard(body, ast);
                        if (!generatedAbstractMethods.containsKey(method.getName().toString())) {
                            generatedAbstractMethods.put(method.getName().toString(), method);
                        }
                        //invoke guard as Assert statement
                        AssertStatement assertStatement = ast.newAssertStatement();
                        MethodInvocation invocation = ast.newMethodInvocation();
                        invocation.setName(ast.newSimpleName(method.getName().toString()));
                        assertStatement.setExpression(invocation);

                        parrentPlanBlock.statements().add(assertStatement);

                        //                           listRewrite.insertLast(rewrite.createStringPlaceholder("//Assert guard condition for next transition is true", ASTNode.EMPTY_STATEMENT), null);
                        //                           listRewrite.insertLast(assertStatement, null);
                        //                           listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null);
                    }
                }
            }
        }

        //get all transition triggers
        List<Trigger> triggers = transition.getTransition().getTriggers();

        //for each trigger
        for (Trigger trigger : triggers) {

            /**
             * If we have not created it already, we create an abstract method to invoke the trigger
             */
            {
                //TODO: update so we do not generate the trigger if it was already generated
                MethodDeclaration method = createAbstractTriggerInvocation(trigger,
                        planMethodDeclaration.getAST());
                if (!generatedAbstractMethods.containsKey(method.getName().toString())) {
                    generatedAbstractMethods.put(method.getName().toString(), method);
                }
                //invoke trigger
                MethodInvocation invocation = ast.newMethodInvocation();
                invocation.setName(ast.newSimpleName(method.getName().toString()));
                //                     listRewrite.insertLast(rewrite.createStringPlaceholder("//Invoke transition trigger", ASTNode.EMPTY_STATEMENT), null);
                //                     listRewrite.insertLast(ast.newExpressionStatement(invocation), null);
                //                     listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null);

                parrentPlanBlock.statements().add(ast.newExpressionStatement(invocation));

            }

        }

        if (!(state.getVertex() instanceof FinalState)) {
            //continue from target state with plan generation

            StateMachineState targetState = transition.getTargetState();
            generatePlanForState(targetState, rewrite, planMethodDeclaration, pathTransitions);
        } else {
            if (transition.getTargetState() == null) {
                notifyUser(state.getName() + " is not final and does not have a target state on transition "
                        + transition.getTransition().getName());
                System.err.println(
                        state.getName() + " is not final and does not have a target state on transition "
                                + transition.getTransition().getName());
            }
        }

    } else if (transitions.size() > 1) {
        for (StateMachineStateTransition transition : transitions) {

            //clone transitions to use clean path for each sub-trees
            Set<StateMachineStateTransition> transitionsCopy = new HashSet<>();
            transitionsCopy.addAll(pathTransitions);

            //if we have visited this transition, continue
            if (transitionsCopy.contains(transition)) {
                continue;
            } else {
                // add transition to visited transitions
                transitionsCopy.add(transition);
            }

            //for each transition we do a clone of the plan until now
            MethodDeclaration transitionMethod = cloneMethodDeclaration(planMethodDeclaration);
            transitionMethod.setName(ast
                    .newSimpleName(PLAN_METHOD_LEADING + (UUID.randomUUID().toString().replaceAll("\\W", ""))));

            //shadowing to local parrentPlanBlock
            parrentPlanBlock = transitionMethod.getBody();

            //shadowing to local ListRewrite 
            //                  listRewrite = rewrite.getListRewrite(transitionMethod.getBody(), Block.STATEMENTS_PROPERTY);
            //                  listRewrite.insertLast(rewrite.createStringPlaceholder("//Forcing transition " + transition.getTransition().getName() + " by ensuring guard conditions are met and triggers are invoked.", ASTNode.EMPTY_STATEMENT), null);
            /**
             * Must force-set all guard conditions to navigate to this particular execution branch
             */
            {
                //get transition condition (could also be Rule, currently we get only Guard transitions)
                //force for the current test the transition condition to true, to enable the system to navigate to expected state
                Constraint guard = transition.getTransition().getGuard();
                if (guard != null) {
                    for (Element element : guard.allOwnedElements()) {
                        //currently condition retrieved as plain text that will need to be parsed and evaluated
                        OpaqueExpression expression = (OpaqueExpression) element;
                        for (String body : expression.getBodies()) {

                            if (body.isEmpty()) {
                                notifyUser("Guard condition for transition  "
                                        + transition.getTransition().getName() + " from state "
                                        + state.getName() + " is empty");
                                System.err.println("Guard condition for transition  "
                                        + transition.getTransition().getName() + " from state "
                                        + state.getName() + " is empty");
                                continue;
                            }

                            MethodDeclaration method = createAbstractForceConditionMethod(body, ast);
                            if (!generatedAbstractMethods.containsKey(method.getName().toString())) {
                                generatedAbstractMethods.put(method.getName().toString(), method);
                            }
                            //invoke method to force guard condition to true
                            MethodInvocation invocation = ast.newMethodInvocation();
                            invocation.setName(ast.newSimpleName(method.getName().toString()));
                            //                              listRewrite.insertLast(rewrite.createStringPlaceholder("//Invoke method to force guard condition to true: " + body, ASTNode.EMPTY_STATEMENT), null);
                            //                              listRewrite.insertLast(ast.newExpressionStatement(invocation), null);
                            //                              listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null);
                            parrentPlanBlock.statements().add(ast.newExpressionStatement(invocation));
                        }
                    }
                }
            }

            //get all transition triggers and execute them, like if we had only one transition
            List<Trigger> triggers = transition.getTransition().getTriggers();

            //for each trigger
            for (Trigger trigger : triggers) {

                /**
                 * If we have not created it already, we create an abstract method to invoke the trigger
                 */
                {
                    //TODO: update so we do not generate the trigger if it was already generated
                    MethodDeclaration method = createAbstractTriggerInvocation(trigger,
                            transitionMethod.getAST());
                    if (!generatedAbstractMethods.containsKey(method.getName().toString())) {
                        generatedAbstractMethods.put(method.getName().toString(), method);
                    }
                    //invoke trigger
                    MethodInvocation invocation = ast.newMethodInvocation();
                    invocation.setName(ast.newSimpleName(method.getName().toString()));
                    //                        listRewrite.insertLast(rewrite.createStringPlaceholder("//Invoke transition trigger", ASTNode.EMPTY_STATEMENT), null);
                    //                        listRewrite.insertLast(ast.newExpressionStatement(invocation), null);
                    //                        listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null);
                    parrentPlanBlock.statements().add(ast.newExpressionStatement(invocation));
                }

            }

            if (!(state.getVertex() instanceof FinalState)) {
                //continue from target state with plan generation
                StateMachineState targetState = transition.getTargetState();
                generatePlanForState(targetState, rewrite, transitionMethod, transitionsCopy);
            } else {
                if (transition.getTargetState() == null) {
                    notifyUser(state.getName() + " is not final and does not have a target state on transition "
                            + transition.getTransition().getName());
                    System.err.println(
                            state.getName() + " is not final and does not have a target state on transition "
                                    + transition.getTransition().getName());
                }
            }

        }

    }

    if (state.getVertex() instanceof FinalState) {
        //store generated method in methods
        //check and store only if there is at least one transition with an uncertain state 
        boolean hasUncertainty = false;
        for (StateMachineStateTransition transition : pathTransitions) {

            //TODO: remove constant and make this efficient

            //check for all transitions only initial state for uncertainties
            //as for next transition, the initial will be the target of this one (except for final state)
            for (Stereotype stereotype : transition.getSourceState().getVertex().getAppliedStereotypes()) {
                //check if the applied stereotype is InfrastructureLevelUncertainty
                if (stereotype.getName().equals(INFRASTRUCTURE_UNCERTAINTY_NAME)) {
                    hasUncertainty = true;
                    break;
                }
            }
        }

        //if does not have any uncertainty on it, do not add it to generated plans
        if (hasUncertainty) {
            generatedPlans.put(planMethodDeclaration.getName().toString(), planMethodDeclaration);
        }
    }

}

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  w ww .  j  a v a2s .  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:ac.at.tuwien.dsg.uml.statemachine.export.transformation.engines.impl.TransitionCorrectnessTestStrategy.java

License:Open Source License

/**
 * //from ww w .  j ava  2s . c o m
 * @param state - the state for which we inspect the transitions and generate the test plan
 * @param rewrite - rewriter used to modify the generated code
 * @param planMethodDeclaration - the method in which the code must be added
 * @param parrentPlanBlock - the block of code where the new state code must be added. Can be a method body, the body of an If statement, etc
 * @param pathTransitions - used to avoid testing cycles and ensure test plan keeps uniqueness on transitions
 */
private void generatePlanForState(final StateMachineState state, final ASTRewrite rewrite,
        final MethodDeclaration planMethodDeclaration, final Set<StateMachineStateTransition> pathTransitions) {

    AST ast = planMethodDeclaration.getAST();
    Block parrentPlanBlock = planMethodDeclaration.getBody();

    ListRewrite listRewrite = rewrite.getListRewrite(parrentPlanBlock, Block.STATEMENTS_PROPERTY);

    /**
     * First we create an abstract method to assert that we have reached current state and we call it
     * only if the state is not a choice. Choices are "virtual" states that signal splits in transition.
     * 
     */
    {

        //only create method if not previously created
        String stateName = state.getName();
        String methodName = ASSERT_STATE_LEADING + stateName;
        if (!generatedAbstractMethods.containsKey(stateName)) {
            MethodDeclaration method = createAbstractMethodForState(state, planMethodDeclaration.getAST());
            generatedAbstractMethods.put(stateName, method);
        }

        /**
        * Call the assert state method to check if we have reached the current state.
        * For the initial state this assert can also reset the system to initial state.
        */
        {
            //invoke guard as Assert statement
            AssertStatement assertStatement = ast.newAssertStatement();
            MethodInvocation invocation = ast.newMethodInvocation();
            invocation.setName(ast.newSimpleName(methodName));
            assertStatement.setExpression(invocation);

            parrentPlanBlock.statements().add(assertStatement);

            //                  listRewrite.insertFirst(rewrite.createStringPlaceholder("//Call the assert state method to check if we have reached the current state.", ASTNode.EMPTY_STATEMENT), null);
            //                  listRewrite.insertLast(rewrite.createStringPlaceholder("//For the initial state this assert can also reset the system to initial state.", ASTNode.EMPTY_STATEMENT), null);
            //                  listRewrite.insertLast(assertStatement, null);
            //                  listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null);
        }

    }

    /**
     * If from one state we have multiple triggers, or from a choice we can go to multiple classes
     * then we generate for each of these transitions paths a separate test plan.
     * This means we clone the previous method into how many we need
     */
    List<StateMachineStateTransition> transitions = state.getOutTransitions();

    //if 1 transition, then we add to same plan
    //if more, we need separate test plans for each branching
    if (transitions.isEmpty() && !(state.getVertex() instanceof FinalState)) {
        //notify user that  something is wrong with the model we are converting 
        notifyUser("State \"" + state.getName()
                + "\"is not final and does not have any transitions. All state machine flows must reach a FinalState.");
        System.err.println(state.getName()
                + " is not final and does not have any transitions. All state machine flows must reach a FinalState to be converted in test plans.");
    } else if (transitions.size() == 1) {
        StateMachineStateTransition transition = transitions.get(0);

        //if we have visited this transition, continue
        if (pathTransitions.contains(transition)) {
            return;
        } else {
            // add transition to visited transitions
            pathTransitions.add(transition);
        }

        //                listRewrite.insertLast(rewrite.createStringPlaceholder("//Test transition " + transition.getTransition().getName(), ASTNode.EMPTY_STATEMENT), null);

        /**
        * Must assert before any transition that the guard condition is fulfilled
        */
        {
            //get transition condition (could also be Rule, currently we get only Guard transitions)
            Constraint guard = transition.getTransition().getGuard();
            if (guard != null) {
                for (Element element : guard.allOwnedElements()) {
                    //currently condition retrieved as plain text that will need to be parsed and evaluated
                    OpaqueExpression expression = (OpaqueExpression) element;
                    for (String body : expression.getBodies()) {
                        if (body.isEmpty()) {
                            notifyUser("Guard condition for transition  " + transition.getTransition().getName()
                                    + " from state " + state.getName() + " is empty");
                            System.err.println(
                                    "Guard condition for transition  " + transition.getTransition().getName()
                                            + " from state " + state.getName() + " is empty");
                            continue;
                        }
                        MethodDeclaration method = createAbstractMethodForGuard(body, ast);
                        if (!generatedAbstractMethods.containsKey(method.getName().toString())) {
                            generatedAbstractMethods.put(method.getName().toString(), method);
                        }
                        //invoke guard as Assert statement
                        AssertStatement assertStatement = ast.newAssertStatement();
                        MethodInvocation invocation = ast.newMethodInvocation();
                        invocation.setName(ast.newSimpleName(method.getName().toString()));
                        assertStatement.setExpression(invocation);

                        parrentPlanBlock.statements().add(assertStatement);

                        //                           listRewrite.insertLast(rewrite.createStringPlaceholder("//Assert guard condition for next transition is true", ASTNode.EMPTY_STATEMENT), null);
                        //                           listRewrite.insertLast(assertStatement, null);
                        //                           listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null);
                    }
                }
            }
        }

        //get all transition triggers
        List<Trigger> triggers = transition.getTransition().getTriggers();

        //for each trigger
        for (Trigger trigger : triggers) {

            /**
             * If we have not created it already, we create an abstract method to invoke the trigger
             */
            {
                //TODO: update so we do not generate the trigger if it was already generated
                MethodDeclaration method = createAbstractTriggerInvocation(trigger,
                        planMethodDeclaration.getAST());
                if (!generatedAbstractMethods.containsKey(method.getName().toString())) {
                    generatedAbstractMethods.put(method.getName().toString(), method);
                }
                //invoke trigger
                MethodInvocation invocation = ast.newMethodInvocation();
                invocation.setName(ast.newSimpleName(method.getName().toString()));
                //                     listRewrite.insertLast(rewrite.createStringPlaceholder("//Invoke transition trigger", ASTNode.EMPTY_STATEMENT), null);
                //                     listRewrite.insertLast(ast.newExpressionStatement(invocation), null);
                //                     listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null);

                parrentPlanBlock.statements().add(ast.newExpressionStatement(invocation));

            }

        }

        if (!(state.getVertex() instanceof FinalState)) {
            //continue from target state with plan generation
            StateMachineState targetState = transition.getTargetState();
            generatePlanForState(targetState, rewrite, planMethodDeclaration, pathTransitions);
        } else {
            if (transition.getTargetState() == null) {
                notifyUser(state.getName() + " is not final and does not have a target state on transition "
                        + transition.getTransition().getName());
                System.err.println(
                        state.getName() + " is not final and does not have a target state on transition "
                                + transition.getTransition().getName());
            }
        }

    } else if (transitions.size() > 1) {

        for (StateMachineStateTransition transition : transitions) {

            //clone transitions to use clean path for each sub-trees
            //cloning is done here as we are generating different paths for each transition at this point
            Set<StateMachineStateTransition> transitionsCopy = new HashSet<>();
            transitionsCopy.addAll(pathTransitions);

            //if we have visited this transition, continue
            if (transitionsCopy.contains(transition)) {
                continue;
            } else {
                // add transition to visited transitions
                transitionsCopy.add(transition);
            }

            //for each transition we do a clone of the plan until now
            MethodDeclaration transitionMethod = cloneMethodDeclaration(planMethodDeclaration);
            transitionMethod.setName(ast
                    .newSimpleName(PLAN_METHOD_LEADING + (UUID.randomUUID().toString().replaceAll("\\W", ""))));

            //shadowing to local parrentPlanBlock
            parrentPlanBlock = transitionMethod.getBody();

            //shadowing to local ListRewrite 
            //                  listRewrite = rewrite.getListRewrite(transitionMethod.getBody(), Block.STATEMENTS_PROPERTY);
            //                  listRewrite.insertLast(rewrite.createStringPlaceholder("//Forcing transition " + transition.getTransition().getName() + " by ensuring guard conditions are met and triggers are invoked.", ASTNode.EMPTY_STATEMENT), null);
            /**
             * Must force-set all guard conditions to navigate to this particular execution branch
             */
            {
                //get transition condition (could also be Rule, currently we get only Guard transitions)
                //force for the current test the transition condition to true, to enable the system to navigate to expected state
                Constraint guard = transition.getTransition().getGuard();
                if (guard != null) {
                    for (Element element : guard.allOwnedElements()) {
                        //currently condition retrieved as plain text that will need to be parsed and evaluated
                        OpaqueExpression expression = (OpaqueExpression) element;
                        for (String body : expression.getBodies()) {

                            if (body.isEmpty()) {
                                notifyUser("Guard condition for transition  "
                                        + transition.getTransition().getName() + " from state "
                                        + state.getName() + " is empty");
                                System.err.println("Guard condition for transition  "
                                        + transition.getTransition().getName() + " from state "
                                        + state.getName() + " is empty");
                                continue;
                            }

                            MethodDeclaration method = createAbstractForceConditionMethod(body, ast);
                            if (!generatedAbstractMethods.containsKey(method.getName().toString())) {
                                generatedAbstractMethods.put(method.getName().toString(), method);
                            }
                            //invoke method to force guard condition to true
                            MethodInvocation invocation = ast.newMethodInvocation();
                            invocation.setName(ast.newSimpleName(method.getName().toString()));
                            //                              listRewrite.insertLast(rewrite.createStringPlaceholder("//Invoke method to force guard condition to true: " + body, ASTNode.EMPTY_STATEMENT), null);
                            //                              listRewrite.insertLast(ast.newExpressionStatement(invocation), null);
                            //                              listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null);
                            parrentPlanBlock.statements().add(ast.newExpressionStatement(invocation));
                        }
                    }
                }
            }

            //get all transition triggers and execute them, like if we had only one transition
            List<Trigger> triggers = transition.getTransition().getTriggers();

            //for each trigger
            for (Trigger trigger : triggers) {

                /**
                 * If we have not created it already, we create an abstract method to invoke the trigger
                 */
                {
                    //TODO: update so we do not generate the trigger if it was already generated
                    MethodDeclaration method = createAbstractTriggerInvocation(trigger,
                            transitionMethod.getAST());
                    if (!generatedAbstractMethods.containsKey(method.getName().toString())) {
                        generatedAbstractMethods.put(method.getName().toString(), method);
                    }
                    //invoke trigger
                    MethodInvocation invocation = ast.newMethodInvocation();
                    invocation.setName(ast.newSimpleName(method.getName().toString()));
                    //                        listRewrite.insertLast(rewrite.createStringPlaceholder("//Invoke transition trigger", ASTNode.EMPTY_STATEMENT), null);
                    //                        listRewrite.insertLast(ast.newExpressionStatement(invocation), null);
                    //                        listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null);
                    parrentPlanBlock.statements().add(ast.newExpressionStatement(invocation));
                }

            }

            if (!(state.getVertex() instanceof FinalState)) {
                //continue from target state with plan generation
                StateMachineState targetState = transition.getTargetState();
                generatePlanForState(targetState, rewrite, transitionMethod, transitionsCopy);
            } else {
                if (transition.getTargetState() == null) {
                    notifyUser(state.getName() + " is not final and does not have a target state on transition "
                            + transition.getTransition().getName());
                    System.err.println(
                            state.getName() + " is not final and does not have a target state on transition "
                                    + transition.getTransition().getName());
                }
            }

        }

    }

    if (state.getVertex() instanceof FinalState) {
        //store generated method in methods
        generatedPlans.put(planMethodDeclaration.getName().toString(), planMethodDeclaration);
    }

}

From source file:ac.at.tuwien.dsg.utest.transformation.umlclassdiagram2javadb.id.rules.UMLClassDiagram2JavaDBTransformationRule.java

License:Open Source License

public Object createTarget(ITransformContext context) {

    ClassImpl source = (ClassImpl) context.getSource();

    Document document = new Document("@NodeType \n public class " + source.getName() + "{ \n");

    //below helper classes toi generate our desired .java file
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(document.get().toCharArray());
    CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    cu.recordModifications();/*  www . jav  a  2s  .co m*/
    AST ast = cu.getAST();

    ASTRewrite rewriter = ASTRewrite.create(ast);

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

    //TODO: here we take each property introduced by each Stereotype

    for (Stereotype stereotype : source.getAppliedStereotypes()) {

        //get all properties
        for (Property attribute : stereotype.getAllAttributes()) {

            //todo
        }
    }

    for (Property property : source.getAllAttributes()) {
        System.out.println(property.getName());

        Association assoc = property.getAssociation();

        if (assoc == null) {
            System.out.format("this is simple %s \n", property.getName());

            VariableDeclarationFragment varDecl = ast.newVariableDeclarationFragment();
            varDecl.setName(ast.newSimpleName(property.getName()));

            FieldDeclaration propertyField = ast.newFieldDeclaration(varDecl);
            propertyField.setType(ast.newSimpleType(ast.newName(property.getType().getName())));

            final SingleMemberAnnotation annot = ast.newSingleMemberAnnotation();
            annot.setTypeName(ast.newName("Property"));

            StringLiteral st = ast.newStringLiteral();
            st.setLiteralValue("type=\"variable\"");

            annot.setValue(st);

            listRewrite.insertLast(annot, null);
            listRewrite.insertLast(propertyField, null);

        } else {
            System.out.format("this is complex %s \n", property.getName());
            Type type = assoc.getEndTypes().stream().filter(a -> !a.equals(source)).findFirst().get();
            System.out.format("Association end is   %s \n", type.getName());

            AggregationKind kind = property.getAggregation();
            if (kind.equals(AggregationKind.COMPOSITE)) {
                System.out.format("Composition \n");
            } else if (kind.equals(AggregationKind.SHARED)) {
                System.out.format("Aggregation \n");
            } else if (kind.equals(AggregationKind.NONE)) {
                System.out.format("Association \n");
            }

        }

    }

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

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

    return null;
}

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

License:Open Source License

private void addFinalIfNecessary(final TypeDeclaration typeDeclaration, final ASTRewrite rewrite) {
    @SuppressWarnings("unchecked")
    final List<IExtendedModifier> modifiers = typeDeclaration.modifiers();
    if (!Iterables.any(modifiers, isFinal())) {
        final ListRewrite modifierRewrite = rewrite.getListRewrite(typeDeclaration,
                TypeDeclaration.MODIFIERS2_PROPERTY);
        final Modifier modifier = (Modifier) typeDeclaration.getAST().createInstance(Modifier.class);
        modifier.setKeyword(ModifierKeyword.FINAL_KEYWORD);
        modifierRewrite.insertLast(modifier, null);
    }/*w  w  w. j  a  va  2  s .c  o m*/
}

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);/*from  w  ww .j  a v a2  s  . c o  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

public static void applyChange(ICompilationUnit cu, CompilationUnit unit) {
    try {/*ww  w.j  a va 2  s  . c o m*/
        ASTRewrite rewrite = ASTRewrite.create(unit.getAST());
        ImportRewrite importRewrite = StubUtility.createImportRewrite(unit, false);

        ASTNode node = unit.findDeclaringNode(cu.getTypes()[0].getKey());
        AbstractTypeDeclaration type = ((AbstractTypeDeclaration) node);
        ListRewrite listRewrite = rewrite.getListRewrite(node, type.getBodyDeclarationsProperty());
        MultiTextEdit edit = new MultiTextEdit();
        TextEdit sub = importRewrite.rewriteImports(null);

        edit.addChild(sub);

        // System.out.println(unit);
        org.eclipse.jface.text.Document doc = new org.eclipse.jface.text.Document(cu.getSource());
        TextEdit te = rewrite.rewriteAST(doc, cu.getJavaProject().getOptions(true));
        te.apply(doc);
        IBuffer buffer = cu.getBuffer();
        buffer.setContents(doc.get());
        buffer.save(null, true);
        // System.out.println(buffer.getContents());

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.android.icu4j.srcgen.RunWithAnnotator.java

License:Apache License

private boolean addRunWithAnnotation(CompilationUnit cu, ASTRewrite rewrite, TypeDeclaration type,
        String runnerClass, boolean imported) {

    AST ast = cu.getAST();/*w  ww. j a v  a  2s .co  m*/

    QualifiedName qRunWith = (QualifiedName) ast.newName(RUN_WITH_CLASS_NAME);
    QualifiedName qRunner = (QualifiedName) ast.newName(runnerClass);
    if (!imported) {
        appendImport(cu, rewrite, qRunWith);
        appendImport(cu, rewrite, qRunner);
    }
    String runWithName = qRunWith.getName().getIdentifier();
    String runnerName = qRunner.getName().getIdentifier();

    SingleMemberAnnotation annotation = ast.newSingleMemberAnnotation();
    annotation.setTypeName(ast.newSimpleName(runWithName));

    TypeLiteral junit4Literal = ast.newTypeLiteral();
    junit4Literal.setType(ast.newSimpleType(ast.newSimpleName(runnerName)));
    annotation.setValue(junit4Literal);

    ListRewrite lrw = rewrite.getListRewrite(type, type.getModifiersProperty());
    lrw.insertFirst(annotation, null);

    return imported;
}

From source file:com.android.icu4j.srcgen.RunWithAnnotator.java

License:Apache License

private void appendImport(CompilationUnit cu, ASTRewrite rewriter, Name name) {
    ListRewrite lrw = rewriter.getListRewrite(cu, CompilationUnit.IMPORTS_PROPERTY);
    AST ast = cu.getAST();//  w w  w.j av a 2 s  . c om
    ImportDeclaration importDeclaration = ast.newImportDeclaration();
    importDeclaration.setName(name);
    lrw.insertLast(importDeclaration, null);
}