Example usage for org.eclipse.jdt.core.dom CompilationUnit TYPES_PROPERTY

List of usage examples for org.eclipse.jdt.core.dom CompilationUnit TYPES_PROPERTY

Introduction

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

Prototype

ChildListPropertyDescriptor TYPES_PROPERTY

To view the source code for org.eclipse.jdt.core.dom CompilationUnit TYPES_PROPERTY.

Click Source Link

Document

The "types" structural property of this node type (element type: AbstractTypeDeclaration ).

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 w  ww  .ja 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 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  av  a  2s.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.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();//w w w.j  a  v a  2s.c  o  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:de.ovgu.cide.language.jdt.SimplePrintVisitor.java

License:Open Source License

public boolean visit(IASTNode node) {
    if (node instanceof ASTStringNode) {
        printToken(((ASTStringNode) node).getValue());
        return false;
    }//from w w w . jav  a 2s .co m
    if (node instanceof ASTTextNode) {
        printToken(((ASTTextNode) node).getValue());
        return false;
    }
    if (node instanceof UnifiedASTNode) {
        UnifiedASTNode unode = (UnifiedASTNode) node;

        if (unode.getEclipseASTNodeClass().equals("AnnotationTypeDeclaration")) {

            accept(node, AnnotationTypeDeclaration.JAVADOC_PROPERTY.getId());

        }

        if (unode.getEclipseASTNodeClass().equals(CompilationUnit.class.getSimpleName())) {
            accept(unode, CompilationUnit.PACKAGE_PROPERTY.getId());
            accept(unode, CompilationUnit.IMPORTS_PROPERTY.getId());
            accept(unode, CompilationUnit.TYPES_PROPERTY.getId());
        }

        if (unode.getEclipseASTNodeClass().equals(TypeDeclaration.class.getSimpleName())) {

            accept(node, TypeDeclaration.JAVADOC_PROPERTY.getId());
            accept(node, TypeDeclaration.MODIFIERS2_PROPERTY.getId());
            accept(node, TypeDeclaration.INTERFACE_PROPERTY.getId());
            accept(node, TypeDeclaration.NAME_PROPERTY.getId());
            accept(node, TypeDeclaration.TYPE_PARAMETERS_PROPERTY.getId(), "<", ",", ">", true);
            //            this.buffer.append(" ");//$NON-NLS-1$

            accept(node, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY.getId(), "extends", "", "", false);
            accept(node, TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY.getId(), "implements", ",", "", false);
            printToken("{");
            hintNewLine();
            hintIncIndent();

            accept(node, TypeDeclaration.BODY_DECLARATIONS_PROPERTY.getId());

            hintDecIndent();
            printToken("}");
            hintNewLine();
        }

        printToken(unode.getEclipseASTNodeClass());
    }
    return false;
}

From source file:edu.illinois.compositerefactorings.refactorings.NewClassCreator.java

License:Open Source License

public List<ResourceChange> createTopLevelParameterObject() throws CoreException {
    List<ResourceChange> changes = new ArrayList<ResourceChange>();
    ICompilationUnit unit = getPackageFragment()
            .getCompilationUnit(getClassName() + JavaModelUtil.DEFAULT_CU_SUFFIX);
    Assert.isTrue(!unit.exists());//from www  .j  a v  a2 s .c  om
    IJavaProject javaProject = unit.getJavaProject();
    ICompilationUnit workingCopy = unit.getWorkingCopy(null);

    try {
        // create stub with comments and dummy type
        String lineDelimiter = StubUtility.getLineDelimiterUsed(javaProject);
        String fileComment = getFileComment(workingCopy, lineDelimiter);
        String typeComment = getTypeComment(workingCopy, lineDelimiter);
        String content = CodeGeneration.getCompilationUnitContent(workingCopy, fileComment, typeComment,
                "class " + getClassName() + "{}", lineDelimiter); //$NON-NLS-1$ //$NON-NLS-2$
        workingCopy.getBuffer().setContents(content);

        CompilationUnitRewrite cuRewrite = new CompilationUnitRewrite(workingCopy);
        ASTRewrite rewriter = cuRewrite.getASTRewrite();
        CompilationUnit root = cuRewrite.getRoot();
        AST ast = cuRewrite.getAST();
        ImportRewrite importRewrite = cuRewrite.getImportRewrite();

        if (fSuperclassType != null) {
            importRewrite.addImport(fSuperclassType.resolveBinding());
        }

        // retrieve&replace dummy type with real class
        ListRewrite types = rewriter.getListRewrite(root, CompilationUnit.TYPES_PROPERTY);
        ASTNode dummyType = (ASTNode) types.getOriginalList().get(0);
        TypeDeclaration classDeclaration = createClassDeclaration(getClassName(), cuRewrite);
        classDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
        Javadoc javadoc = (Javadoc) dummyType.getStructuralProperty(TypeDeclaration.JAVADOC_PROPERTY);
        rewriter.set(classDeclaration, TypeDeclaration.JAVADOC_PROPERTY, javadoc, null);
        types.replace(dummyType, classDeclaration, null);

        // Apply rewrites and discard workingcopy
        // Using CompilationUnitRewrite.createChange() leads to strange
        // results
        String charset = ResourceUtil.getFile(unit).getCharset(false);
        Document document = new Document(content);
        try {
            rewriter.rewriteAST().apply(document);
            TextEdit rewriteImports = importRewrite.rewriteImports(null);
            rewriteImports.apply(document);
        } catch (BadLocationException e) {
            throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(),
                    RefactoringCoreMessages.IntroduceParameterObjectRefactoring_parameter_object_creation_error,
                    e));
        }
        String docContent = document.get();
        CreateCompilationUnitChange compilationUnitChange = new CreateCompilationUnitChange(unit, docContent,
                charset);
        changes.add(compilationUnitChange);
    } finally {
        workingCopy.discardWorkingCopy();
    }
    return changes;
}

From source file:edu.illinois.compositerefactorings.steps.CreateNewSuperclass.java

License:Open Source License

@Override
public Collection<ASTRewriteCorrectionProposal> getProposals(Object input) throws CoreException {
    TypeDeclaration typeDeclaration = (TypeDeclaration) input;
    ASTNode node = typeDeclaration.getParent();
    AST ast = node.getAST();//from w w  w.j a v  a2s. co m
    ASTRewrite rewrite = ASTRewrite.create(ast);
    String label = MessageFormat.format(CompositeRefactoringsMessages.CreateNewSuperclass_description,
            typeDeclaration.getName(), getCompilationUnit().getElementName());
    Image image = JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, getCompilationUnit(),
            rewrite, 0, image);
    TypeDeclaration newSuperclass = ast.newTypeDeclaration();
    newSuperclass.setName(ast.newSimpleName("Super" + typeDeclaration.getName()));
    ListRewrite listRewrite = rewrite.getListRewrite(node, CompilationUnit.TYPES_PROPERTY);
    listRewrite.insertLast(newSuperclass, null);
    rewrite.set(newSuperclass, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY,
            typeDeclaration.getStructuralProperty(TypeDeclaration.SUPERCLASS_TYPE_PROPERTY), null);
    rewrite.set(typeDeclaration, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY, newSuperclass.getName(), null);
    Collection<ASTRewriteCorrectionProposal> proposals = new ArrayList<ASTRewriteCorrectionProposal>();
    proposals.add(proposal);
    return proposals;
}

From source file:org.eclipse.emf.codegen.merge.java.facade.ast.ASTJCompilationUnit.java

License:Open Source License

/**
 * Returns the list of children in order: package declaration (<code>JPackage</code>), imports (<code>JImport</code>), and types (<code>JType</code>).
 * //from   w  w w.  jav a  2  s  .co m
 * @see org.eclipse.emf.codegen.merge.java.facade.AbstractJNode#getChildren()
 */
@Override
public List<JNode> getChildren() {
    if (!isDisposed()) {
        CompilationUnit astCompilationUnit = getASTNode();
        List<JNode> children = new ArrayList<JNode>();
        PackageDeclaration astPackage = astCompilationUnit.getPackage();
        if (astPackage != null) {
            JNode child = getFacadeHelper().convertToNode(astPackage);
            if (child != null) {
                children.add(child);
            }
        }

        ListRewrite importsListRewrite = rewriter.getListRewrite(astCompilationUnit,
                CompilationUnit.IMPORTS_PROPERTY);
        for (Object importDeclaration : importsListRewrite.getRewrittenList()) {
            JNode child = getFacadeHelper().convertToNode(importDeclaration);
            if (child != null) {
                children.add(child);
            }
        }

        ListRewrite typesListRewrite = rewriter.getListRewrite(astCompilationUnit,
                CompilationUnit.TYPES_PROPERTY);
        for (Object type : typesListRewrite.getRewrittenList()) {
            JNode child = getFacadeHelper().convertToNode(type);
            if (child != null) {
                children.add(child);
            }
        }
        if (!children.isEmpty()) {
            return Collections.unmodifiableList(children);
        }
    }
    return Collections.emptyList();
}

From source file:org.eclipse.emf.codegen.merge.java.facade.ast.ASTJCompilationUnit.java

License:Open Source License

@Override
public boolean addChild(ASTJNode<?> child) {
    if (child.getParent() != null) {
        return false;
    }/*  w ww.  ja  va 2 s .com*/

    if (child instanceof ASTJImport) {
        insertLast(child, CompilationUnit.IMPORTS_PROPERTY);
    } else if (child instanceof ASTJAbstractType<?>) {
        insertLast(child, CompilationUnit.TYPES_PROPERTY);
    } else if (child instanceof ASTJPackage) {
        setNodeProperty(getASTNode(), child.getASTNode(), CompilationUnit.PACKAGE_PROPERTY);
    } else {
        return false;
    }
    child.setParent(this);
    return true;
}

From source file:org.eclipse.emf.codegen.merge.java.facade.ast.ASTJCompilationUnit.java

License:Open Source License

@Override
public boolean insertSibling(ASTJNode<?> node, ASTJNode<?> newSibling, boolean before) {
    if (newSibling.getParent() != null) {
        return false;
    }//from   w  w  w  . j  a  v  a  2 s  . c o  m

    if (newSibling instanceof ASTJImport) {
        if (node instanceof ASTJImport) {
            insert(newSibling, CompilationUnit.IMPORTS_PROPERTY, node, before);
        } else if (node instanceof ASTJPackage) {
            insertFirst(newSibling, CompilationUnit.IMPORTS_PROPERTY);
        } else if (node instanceof ASTJAbstractType<?>) {
            insertLast(newSibling, CompilationUnit.IMPORTS_PROPERTY);
        } else {
            return false;
        }
    } else if (newSibling instanceof ASTJAbstractType<?>) {
        if (node instanceof ASTJAbstractType<?>) {
            insert(newSibling, CompilationUnit.TYPES_PROPERTY, node, before);
        } else if (node instanceof ASTJImport) {
            insertFirst(newSibling, CompilationUnit.TYPES_PROPERTY);
        } else if (node instanceof ASTJPackage) {
            insertFirst(newSibling, CompilationUnit.TYPES_PROPERTY);
        } else {
            return false;
        }
    } else if (newSibling instanceof ASTJPackage) {
        setNodeProperty(getASTNode(), newSibling.getASTNode(), CompilationUnit.PACKAGE_PROPERTY);
    } else {
        return false;
    }
    newSibling.setParent(this);
    return true;
}

From source file:org.eclipse.emf.codegen.merge.java.facade.ast.ASTJCompilationUnit.java

License:Open Source License

/**
 * Removes the given node.//from   w ww.ja  v a2s. c om
 * <p>
 * This implementation will not perform moving of the node if the node is inserted after being removed.
 * Hence, the removed node must not be inserted again.
 * 
 * @see org.eclipse.emf.codegen.merge.java.facade.ast.ASTJNode#remove(ASTJNode)
 */
@Override
public boolean remove(ASTJNode<?> node) {
    if (node.getParent() != this) {
        return false;
    }

    if (node instanceof ASTJImport) {
        remove(node, CompilationUnit.IMPORTS_PROPERTY);
    } else if (node instanceof ASTJAbstractType<?>) {
        remove(node, CompilationUnit.TYPES_PROPERTY);
    } else if (node instanceof ASTJPackage) {
        setNodeProperty(getASTNode(), null, CompilationUnit.PACKAGE_PROPERTY);
    } else {
        return false;
    }
    node.setParent(null);
    return true;
}