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

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

Introduction

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

Prototype

int JLS8

To view the source code for org.eclipse.jdt.core.dom AST JLS8.

Click Source Link

Document

Constant for indicating the AST API that handles JLS8.

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//from  ww w.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   w w  w  .  j a  v a 2 s  . c o  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 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.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();//from www . ja  v  a 2 s  . 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:at.bestsolution.fxide.jdt.corext.dom.ASTFlattener.java

License:Open Source License

void printTypeAnnotations(AnnotatableType node) {
    if (node.getAST().apiLevel() >= AST.JLS8) {
        printAnnotationsList(node.annotations());
    }
}

From source file:at.bestsolution.fxide.jdt.corext.dom.ASTFlattener.java

License:Open Source License

@Override
public boolean visit(ArrayType node) {
    if (node.getAST().apiLevel() < AST.JLS8) {
        getComponentType(node).accept(this);
        this.fBuffer.append("[]");//$NON-NLS-1$
    } else {//from  w w  w  .  j a  va 2  s .co  m
        node.getElementType().accept(this);
        List<Dimension> dimensions = node.dimensions();
        for (int i = 0; i < dimensions.size(); i++) {
            Dimension dimension = dimensions.get(i);
            dimension.accept(this);
        }
    }
    return false;
}

From source file:at.bestsolution.fxide.jdt.corext.dom.ASTFlattener.java

License:Open Source License

@Override
public boolean visit(MethodDeclaration node) {
    if (node.getJavadoc() != null) {
        node.getJavadoc().accept(this);
    }/*from  w  ww .  j  a  v a2 s . c o m*/
    if (node.getAST().apiLevel() >= JLS3) {
        printModifiers(node.modifiers());
        if (!node.typeParameters().isEmpty()) {
            this.fBuffer.append("<");//$NON-NLS-1$
            for (Iterator<TypeParameter> it = node.typeParameters().iterator(); it.hasNext();) {
                TypeParameter t = it.next();
                t.accept(this);
                if (it.hasNext()) {
                    this.fBuffer.append(", ");//$NON-NLS-1$
                }
            }
            this.fBuffer.append("> ");//$NON-NLS-1$
        }
    }
    if (!node.isConstructor()) {
        if (node.getReturnType2() != null) {
            node.getReturnType2().accept(this);
        } else {
            // methods really ought to have a return type
            this.fBuffer.append("void");//$NON-NLS-1$
        }
        this.fBuffer.append(" ");//$NON-NLS-1$
    }
    node.getName().accept(this);
    this.fBuffer.append("(");//$NON-NLS-1$
    if (node.getAST().apiLevel() >= AST.JLS8) {
        Type receiverType = node.getReceiverType();
        if (receiverType != null) {
            receiverType.accept(this);
            this.fBuffer.append(' ');
            SimpleName qualifier = node.getReceiverQualifier();
            if (qualifier != null) {
                qualifier.accept(this);
                this.fBuffer.append('.');
            }
            this.fBuffer.append("this"); //$NON-NLS-1$
            if (node.parameters().size() > 0) {
                this.fBuffer.append(',');
            }
        }
    }
    for (Iterator<SingleVariableDeclaration> it = node.parameters().iterator(); it.hasNext();) {
        SingleVariableDeclaration v = it.next();
        v.accept(this);
        if (it.hasNext()) {
            this.fBuffer.append(", ");//$NON-NLS-1$
        }
    }
    this.fBuffer.append(")");//$NON-NLS-1$
    if (node.getAST().apiLevel() >= AST.JLS8) {
        List<Dimension> dimensions = node.extraDimensions();
        for (Iterator<Dimension> it = dimensions.iterator(); it.hasNext();) {
            Dimension e = it.next();
            e.accept(this);
        }
    } else {
        for (int i = 0; i < node.getExtraDimensions(); i++) {
            this.fBuffer.append("[]"); //$NON-NLS-1$
        }
    }
    List<? extends ASTNode> thrownExceptions = node.getAST().apiLevel() >= AST.JLS8
            ? node.thrownExceptionTypes()
            : getThrownExceptions(node);
    if (!thrownExceptions.isEmpty()) {
        this.fBuffer.append(" throws ");//$NON-NLS-1$
        for (Iterator<? extends ASTNode> it = thrownExceptions.iterator(); it.hasNext();) {
            ASTNode n = it.next();
            n.accept(this);
            if (it.hasNext()) {
                this.fBuffer.append(", ");//$NON-NLS-1$
            }
        }
        this.fBuffer.append(" ");//$NON-NLS-1$
    }
    if (node.getBody() == null) {
        this.fBuffer.append(";");//$NON-NLS-1$
    } else {
        node.getBody().accept(this);
    }
    return false;
}

From source file:at.bestsolution.fxide.jdt.corext.dom.ASTFlattener.java

License:Open Source License

@Override
public boolean visit(SingleVariableDeclaration node) {
    if (node.getAST().apiLevel() >= JLS3) {
        printModifiers(node.modifiers());
    }/*from  www . j  a  va 2 s. c o  m*/
    node.getType().accept(this);
    if (node.getAST().apiLevel() >= JLS3) {
        if (node.isVarargs()) {
            if (node.getAST().apiLevel() >= AST.JLS8) {
                this.fBuffer.append(' ');
                List<Annotation> annotations = node.varargsAnnotations();
                printAnnotationsList(annotations);
            }
            this.fBuffer.append("...");//$NON-NLS-1$
        }
    }
    this.fBuffer.append(" ");//$NON-NLS-1$
    node.getName().accept(this);
    if (node.getAST().apiLevel() >= AST.JLS8) {
        List<Dimension> dimensions = node.extraDimensions();
        for (Iterator<Dimension> it = dimensions.iterator(); it.hasNext();) {
            Dimension e = it.next();
            e.accept(this);
        }
    } else {
        for (int i = 0; i < node.getExtraDimensions(); i++) {
            this.fBuffer.append("[]"); //$NON-NLS-1$
        }
    }
    if (node.getInitializer() != null) {
        this.fBuffer.append("=");//$NON-NLS-1$
        node.getInitializer().accept(this);
    }
    return false;
}

From source file:at.bestsolution.fxide.jdt.corext.dom.ASTFlattener.java

License:Open Source License

@Override
public boolean visit(VariableDeclarationFragment node) {
    node.getName().accept(this);
    if (node.getAST().apiLevel() >= AST.JLS8) {
        List<Dimension> dimensions = node.extraDimensions();
        for (Iterator<Dimension> it = dimensions.iterator(); it.hasNext();) {
            Dimension e = it.next();
            e.accept(this);
        }//from w w  w.j a va2  s.  c om
    } else {
        for (int i = 0; i < node.getExtraDimensions(); i++) {
            this.fBuffer.append("[]"); //$NON-NLS-1$
        }
    }
    if (node.getInitializer() != null) {
        this.fBuffer.append("=");//$NON-NLS-1$
        node.getInitializer().accept(this);
    }
    return false;
}

From source file:at.bestsolution.fxide.jdt.editor.JDTJavaDocSupport.java

License:Open Source License

private static CompilationUnit createAST(IJavaElement element, String cuSource) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);

    IJavaProject javaProject = element.getJavaProject();
    parser.setProject(javaProject);/*from   www .j a  v  a2  s  . co m*/
    Map<String, String> options = javaProject.getOptions(true);
    options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED); // workaround
    // for
    // https://bugs.eclipse.org/bugs/show_bug.cgi?id=212207
    parser.setCompilerOptions(options);

    parser.setSource(cuSource.toCharArray());
    return (CompilationUnit) parser.createAST(null);
}

From source file:boa.test.datagen.Java8BaseTest.java

License:Apache License

private static void setJava8() {
    astLevel = AST.JLS8;
    javaVersion = JavaCore.VERSION_1_8;/*from  w  w  w .j  a  v  a 2  s .c  o  m*/
    visitor = new Java8Visitor("", new HashMap<String, Integer>());
}