Example usage for org.eclipse.jdt.core.dom ASTParser newParser

List of usage examples for org.eclipse.jdt.core.dom ASTParser newParser

Introduction

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

Prototype

public static ASTParser newParser(int level) 

Source Link

Document

Creates a new object for creating a Java abstract syntax tree (AST) following the specified set of API rules.

Usage

From source file:JavaCompleter.java

License:Apache License

public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    Scanner s = null;/*  w w w .  j  a v  a  2  s.c o m*/
    for (String filename = in.readLine(); filename != null; filename = in.readLine()) {
        s = new Scanner(new File(filename));
        s.useDelimiter("\\Z");
        ASTParser parser = ASTParser.newParser(AST.JLS4);
        parser.setSource(s.next().toCharArray());
        parser.setKind(ASTParser.K_COMPILATION_UNIT);
        ASTNode file = parser.createAST(null);
        ASTNode range = NodeFinder.perform(file, 200, 201);
        System.out.println(range.getNodeType());
    }
}

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   www . 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 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 ww.  j  a  va2s  .  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 w w  w. jav a2 s  . 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:ast.StructureParse.java

public void setCode(JTextPane textCode) {
    ASTParser parser = ASTParser.newParser(AST.JLS2);
    parser.setSource(textCode.getText().toCharArray());
    //parser.setSource("/*abc*/".toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);

    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    _package = new DefaultMutableTreeNode("root");

    codeTree.setRootVisible(false);/*w  ww.  ja  va  2s . c o  m*/

    cu.accept(new ASTVisitor() {
        Set names = new HashSet();

        /*
         * Package declaration
        */
        @Override
        public boolean visit(PackageDeclaration node) {
            _package = new DefaultMutableTreeNode(node.getName().toString());
            codeTree.setRootVisible(true);
            System.out.println("Package : " + node.getName().toString());
            return false;
        }

        /*
         * Class Declaration.
         * sub node from package
        */
        @Override
        public boolean visit(TypeDeclaration node) {
            String type;
            if (node.isInterface())
                type = "interface ";
            else
                type = "class ";
            _class = new DefaultMutableTreeNode(type + node.getName());
            System.out.println(type + node.getName());

            _package.add(_class);

            String superClass = node.getSuperclass() + "";
            if (!(superClass.equals("null") || (superClass.equals("")))) {
                _class.add(new DefaultMutableTreeNode("extends " + superClass));
                System.out.println("Extends : " + superClass);
            }

            for (Object getInterface : node.superInterfaces()) {
                _class.add(new DefaultMutableTreeNode("implements " + getInterface));
                System.out.println("Implements : " + getInterface);
            }
            return true;
        }

        /*
         * method declaration
         * sub node from class
        */
        @Override
        public boolean visit(MethodDeclaration node) {
            _method = new DefaultMutableTreeNode(node.getName());
            _class.add(_method);
            System.out.println("MethodDeclaration : " + node.getName());
            return true;
        }

        /*
         * field declaration
         * sub node from class
        */
        //            @Override
        //            public boolean visit(FieldDeclaration node)
        //            {
        //                _field=new DefaultMutableTreeNode(node.toString());
        //                _class.add(_field);
        //                Object o = node.fragments().get(0);
        //                if(o instanceof VariableDeclarationFragment){
        //                    _method.add(new DefaultMutableTreeNode(o.toString()));
        //                }
        //                return false;
        //            }

        /*
         * Variable declaration fragment AST node type
         * used in field declarations
         * local variable declarations
         * sub node from method
        */
        @Override
        public boolean visit(VariableDeclarationFragment node) {
            if (node.getParent() instanceof FieldDeclaration) {
                FieldDeclaration declaration = ((FieldDeclaration) node.getParent());
                _class.add(new DefaultMutableTreeNode(declaration.getType().toString()));
                System.out.println("FieldDeclaration : " + declaration.getType().toString());
            } else {
                _method.add(new DefaultMutableTreeNode(node.toString()));
                System.out.println("VariableDeclarationFragment : " + node.toString());
            }
            return false; // do not continue to avoid usage info
        }

        @Override
        public boolean visit(VariableDeclarationStatement node) {
            _method.add(new DefaultMutableTreeNode(node.toString()));
            System.out.println("VariableDeclarationStatement : " + node.toString());
            return false;
        }

        /*
         * Simple Name
         * A simple name is an identifier other than a keyword, boolean literal ("true", "false") or null literal ("null"). 
        */
        @Override
        public boolean visit(SimpleName node) {
            if (this.names.contains(node.getIdentifier())) {
                _method.add(new DefaultMutableTreeNode(node.toString()));
                System.out.println("SimpleNode Identifier : " + node.toString());
            }
            return false;
        }

        /*
         * Alternate constructor invocation (calling constructor) statement AST node type
         * For JLS2: 
        */
        @Override
        public boolean visit(SuperConstructorInvocation node) {
            _constructorCall = new DefaultMutableTreeNode(node);
            _method.add(_constructorCall);
            System.out.println("SuperConstructorInvocation : " + node);
            return false;
        }

        /*
         * method call
        */
        @Override
        public boolean visit(MethodInvocation node) {
            _methodCall = new DefaultMutableTreeNode(node);
            _method.add(_methodCall);
            System.out.println("MethodInvocation : " + node);
            return false;
        }

        @Override
        public boolean visit(SuperMethodInvocation node) {
            _methodCall = new DefaultMutableTreeNode(node);
            _method.add(_methodCall);
            System.out.println("SuperMethodInvocation : " + node);
            return false;
        }

        @Override
        public boolean visit(ReturnStatement node) {
            _method.add(new DefaultMutableTreeNode(node.toString()));
            System.out.println("ReturnStatement : " + node.toString());
            return false;
        }

        @Override
        public boolean visit(IfStatement node) {
            String elseExist = "";
            _if = new DefaultMutableTreeNode("if (" + node.getExpression() + ")");
            _method.add(_if);
            System.out.println("if : " + node.getExpression());
            enclose(node.getThenStatement().toString(), _if);
            elseExist = node.getElseStatement() + "";
            if (!(elseExist.equals("") || elseExist.equals("null"))) {
                _else = new DefaultMutableTreeNode("else");
                _method.add(_else);
                System.out.println("else : " + node.getElseStatement().toString());
                enclose(node.getElseStatement().toString(), _else);
            }
            return false;
        }

        @Override
        public boolean visit(EnhancedForStatement node) {
            _for = new DefaultMutableTreeNode(
                    "for (" + node.getParameter() + " : " + node.getExpression() + ")");
            _method.add(_for);
            System.out.println("EnchancedFor : (" + node.getParameter() + " : " + node.getExpression() + ")");
            enclose(node.getBody() + "", _for);
            return false;
        }

        @Override
        public boolean visit(ForStatement node) {
            /*
             * because initial may more than 1.
            */
            String initial = "";
            for (int i = 0; i < node.initializers().size(); i++) {
                initial += node.initializers().get(i);
                if (node.initializers().size() - 1 != i)
                    initial += ", ";
            }

            /*
             * because increment may more than 1
            */
            String inc = "";
            for (int i = 0; i < node.updaters().size(); i++) {
                inc += node.updaters().get(i);
                if (node.updaters().size() - 1 != i)
                    inc += ", ";
            }

            _for = new DefaultMutableTreeNode(
                    "for (" + initial + "; " + node.getExpression() + "; " + inc + ")");
            _method.add(_for);
            System.out.println("for (" + initial + "; " + node.getExpression() + "; " + inc + ")");
            enclose(node.getBody().toString(), _for);
            return false;
        }

        @Override
        public boolean visit(WhileStatement node) {
            _while = new DefaultMutableTreeNode("while " + node.getExpression());
            _method.add(_while);
            System.out.println("WhileStatement : " + node.getExpression());
            enclose(node.getBody().toString(), _while);
            return false;
        }

        @Override
        public boolean visit(DoStatement node) {
            _do = new DefaultMutableTreeNode("do");
            _method.add(_do);
            System.out.println("Do");
            enclose(node.getBody().toString(), _do);
            _while = new DefaultMutableTreeNode("while(" + node.getExpression() + ")");
            _method.add(_while);
            System.out.println("WhileDo : " + node.getExpression());
            return false;
        }

        @Override
        public boolean visit(TryStatement node) {
            String ada = "";
            _try = new DefaultMutableTreeNode("try");
            _method.add(_try);
            System.out.println("try");
            enclose(node.getBody().toString(), _try);
            ada = node.getFinally() + "";
            if (!(ada.equals("") || ada.equals("null"))) {
                _final = new DefaultMutableTreeNode("finally");
                _method.add(_final);
                System.out.println("finall");
                enclose(node.getFinally().toString(), _final);
            }
            return false;
        }

        @Override
        public boolean visit(CatchClause node) {
            _catch = new DefaultMutableTreeNode("catch (" + node.getException() + ")");
            _method.add(_catch);
            System.out.println("catch : " + node.getException());
            enclose(node.getBody().toString(), _catch);
            return false;
        }

        @Override
        public boolean visit(Assignment node) {
            _assignment = new DefaultMutableTreeNode(node.toString());
            _method.add(_assignment);
            System.out.println("Assignment : " + node.toString());
            return false;
        }

        @Override
        public boolean visit(ConstructorInvocation node) {
            _constructorCall = new DefaultMutableTreeNode(node.toString());
            _method.add(_constructorCall);
            System.out.println(node.toString());
            return false;
        }

        @Override
        public boolean visit(AnonymousClassDeclaration node) {
            _constructorCall = new DefaultMutableTreeNode(node.toString());
            _method.add(_constructorCall);
            System.out.println("AnonymousClassDeclaration : " + node.toString());
            return false;
        }

        @Override
        public boolean visit(ArrayAccess node) {
            _class = new DefaultMutableTreeNode(node.toString());
            _method.add(_class);
            System.out.println("AbstrackTypeDeclaration : " + node.toString());
            return false;
        }

        @Override
        public boolean visit(ArrayCreation node) {
            _array = new DefaultMutableTreeNode(node.toString());
            _method.add(_array);
            System.out.println("ArrayCreation : " + node.toString());
            return false;
        }

        @Override
        public boolean visit(ArrayInitializer node) {
            _array = new DefaultMutableTreeNode(node.toString());
            System.out.println("ArrayInitialize : " + node.toString());
            _method.add(_array);
            return false;
        }

        @Override
        public boolean visit(AssertStatement node) {
            _statement = new DefaultMutableTreeNode(node.toString());
            System.out.println("AssertStatement : " + node.toString());
            _method.add(_statement);
            return false;
        }

        @Override
        public boolean visit(ContinueStatement node) {
            _statement = new DefaultMutableTreeNode(node.toString());
            System.out.println("ContinueStatement : " + node.toString());
            _method.add(_statement);
            return false;
        }

        @Override
        public boolean visit(SwitchStatement node) {
            _switch = new DefaultMutableTreeNode("switch (" + node.getExpression() + ")");
            System.out.println("switch (" + node.getExpression() + ")");
            _method.add(_switch);
            List getStatement = node.statements();
            for (Object st : getStatement) {
                Matcher _caseMatch = Pattern.compile("^case\\s+.+\\:").matcher(st.toString());
                if (_caseMatch.find()) {
                    _case = new DefaultMutableTreeNode(_caseMatch.group());
                    _switch.add(_case);
                }

                enclose(st.toString(), _case);

                Matcher _breakMatch = Pattern.compile("^break\\s*.*;").matcher(st.toString());
                if (_breakMatch.find()) {
                    _break = new DefaultMutableTreeNode(_breakMatch.group());
                    _case.add(_break);
                }
            }
            return false;
        }

        @Override
        public boolean visit(ClassInstanceCreation node) {
            _constructorCall = new DefaultMutableTreeNode(node.toString());
            System.out.println("ClassInstanceCreation : " + node.toString());
            _method.add(_constructorCall);
            return false;
        }
    });

    //        model = new DefaultTreeModel(_package);
    //        model.reload();
    //        codeTree.setModel(model);
    codeTree.setModel(new DefaultTreeModel(_package) {
        public void reload(TreeNode node) {
            if (node != null) {
                fireTreeStructureChanged(this, getPathToRoot(node), null, null);
            }
        }
    });
    codeTree.setCellRenderer(new TreeRender());
    //        ((DefaultTreeModel)codeTree.getModel()).reload();
    for (int i = 0; i < codeTree.getRowCount(); i++)
        codeTree.expandRow(i);
}

From source file:ast.StructureParse.java

private void enclose(String body, DefaultMutableTreeNode parentNode) {
    ASTParser parser = ASTParser.newParser(AST.JLS2);
    /*//ww w  .  j  av  a2s  . co  m
     * make parse result into OPP structure, because AST wanna be that.
    */
    String setClass = "class fo{\nvoid foo(){ \n" + body + "\n}\n}";
    parser.setSource(setClass.toCharArray());
    //parser.setSource("/*abc*/".toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    //ASTNode node = parser.createAST(null);
    parser.setResolveBindings(true);

    try {
        final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

        cu.accept(new ASTVisitor() {
            Set names2 = new HashSet();

            @Override
            public boolean visit(SimpleName node) {
                if (this.names2.contains(node.getIdentifier())) {
                    parentNode.add(new DefaultMutableTreeNode(node.toString()));
                    System.out.println("SimpleNode : " + node.toString());
                }
                return true;
            }

            @Override
            public boolean visit(EnhancedForStatement node) {
                _for = new DefaultMutableTreeNode(
                        "for (" + node.getParameter() + " : " + node.getExpression() + ")");
                parentNode.add(_for);
                System.out.println("for (" + node.getParameter() + " : " + node.getExpression() + ")");
                enclose(node.getBody().toString(), _for);
                return false;
            }

            @Override
            public boolean visit(ForStatement node) {
                /*
                 * because initial may more than 1.
                */
                String initial = "";
                for (int i = 0; i < node.initializers().size(); i++) {
                    initial += node.initializers().get(i);
                    if (node.initializers().size() - 1 != i)
                        initial += ", ";
                }

                /*
                 * because increment may more than 1
                */
                String inc = "";
                for (int i = 0; i < node.updaters().size(); i++) {
                    inc += node.updaters().get(i);
                    if (node.updaters().size() - 1 != i)
                        inc += ", ";
                }

                _for = new DefaultMutableTreeNode(
                        "for (" + initial + "; " + node.getExpression() + "; " + inc + ")");
                parentNode.add(_for);
                System.out.println("for (" + initial + "; " + node.getExpression() + "; " + inc + ")");
                enclose(node.getBody().toString(), _for);
                return false;
            }

            @Override
            public boolean visit(IfStatement node) {
                String elseExist = "";
                _if = new DefaultMutableTreeNode("if (" + node.getExpression() + ")");
                System.out.println("if (+" + node.getExpression() + ")");
                parentNode.add(_if);
                enclose(node.getThenStatement().toString(), _if);
                elseExist = node.getElseStatement() + "";
                if (!(elseExist.equals("") || (elseExist.equals("null")))) {
                    _else = new DefaultMutableTreeNode("else");
                    System.out.println("else");
                    parentNode.add(_else);
                    enclose(node.getElseStatement().toString(), _else);
                }
                return false;
            }

            @Override
            public boolean visit(VariableDeclarationFragment node) {
                if (node.getParent() instanceof FieldDeclaration) {
                    FieldDeclaration declaration = ((FieldDeclaration) node.getParent());
                    _class.add(new DefaultMutableTreeNode(declaration.getType().toString()));
                } else {
                    System.out.println("VariableDeclarationFragment : " + node.toString());
                    parentNode.add(new DefaultMutableTreeNode(node.toString()));
                }
                return false; // do not continue to avoid usage info
            }

            @Override
            public boolean visit(ReturnStatement node) {
                parentNode.add(new DefaultMutableTreeNode(node.toString()));
                System.out.println("Return : " + node.toString());
                return false;
            }

            @Override
            public boolean visit(SuperConstructorInvocation node) {
                _constructorCall = new DefaultMutableTreeNode(node);
                parentNode.add(_constructorCall);
                System.out.println("SuperConstructorInvocation : " + node);
                return false;
            }

            @Override
            public boolean visit(MethodInvocation node) {
                _methodCall = new DefaultMutableTreeNode(node);
                parentNode.add(_methodCall);
                System.out.println("MethodInvocation : " + node);
                return true;
            }

            @Override
            public boolean visit(SuperMethodInvocation node) {
                _methodCall = new DefaultMutableTreeNode(node);
                parentNode.add(_methodCall);
                System.out.println("SuperMethodInvocation : " + node);
                return false;
            }

            @Override
            public boolean visit(WhileStatement node) {
                _while = new DefaultMutableTreeNode("while " + node.getExpression());
                parentNode.add(_while);
                System.out.println("WhileStatement : " + node.getExpression());
                enclose(node.getBody().toString(), _while);
                return false;
            }

            @Override
            public boolean visit(DoStatement node) {
                _do = new DefaultMutableTreeNode("do");
                parentNode.add(_do);
                System.out.println("do");
                enclose(node.getBody().toString(), _do);
                _while = new DefaultMutableTreeNode("while(" + node.getExpression() + ")");
                parentNode.add(_while);
                return false;
            }

            @Override
            public boolean visit(TryStatement node) {
                String ada = "";
                _try = new DefaultMutableTreeNode("try");
                parentNode.add(_try);
                System.out.println("try");
                enclose(node.getBody().toString(), _try);
                ada = node.getFinally() + "";
                if (!(ada.equals("") || (ada.equals("null")))) {
                    _final = new DefaultMutableTreeNode("finally");
                    parentNode.add(_final);
                    System.out.println("finally");
                    enclose(node.getFinally().toString(), _final);
                }
                return false;
            }

            @Override
            public boolean visit(CatchClause node) {
                _catch = new DefaultMutableTreeNode("catch (" + node.getException() + ")");
                parentNode.add(_catch);
                System.out.println("catch : " + node.getException());
                enclose(node.getBody().toString(), _catch);
                return false;
            }

            @Override
            public boolean visit(Assignment node) {
                _assignment = new DefaultMutableTreeNode(node.toString());
                parentNode.add(_assignment);
                System.out.println("Assignment : " + node.toString());
                return false;
            }

            @Override
            public boolean visit(ConstructorInvocation node) {
                _constructorCall = new DefaultMutableTreeNode(node.toString());
                parentNode.add(_constructorCall);
                System.out.println(node.toString());
                return false;
            }

            @Override
            public boolean visit(AnonymousClassDeclaration node) {
                _constructorCall = new DefaultMutableTreeNode(node.toString());
                parentNode.add(_constructorCall);
                System.out.println("AnonymousClassDeclaration : " + node.toString());
                return false;
            }

            @Override
            public boolean visit(ArrayAccess node) {
                _class = new DefaultMutableTreeNode(node.toString());
                parentNode.add(_class);
                System.out.println("AbstrackTypeDeclaration : " + node.toString());
                return false;
            }

            @Override
            public boolean visit(ArrayCreation node) {
                _array = new DefaultMutableTreeNode(node.toString());
                _method.add(_array);
                System.out.println("ArrayCreation : " + node.toString());
                return false;
            }

            @Override
            public boolean visit(ArrayInitializer node) {
                _array = new DefaultMutableTreeNode(node.toString());
                System.out.println("ArrayInitialize : " + node.toString());
                parentNode.add(_array);
                return false;
            }

            @Override
            public boolean visit(AssertStatement node) {
                _statement = new DefaultMutableTreeNode(node.toString());
                System.out.println("AssertStatement : " + node.toString());
                parentNode.add(_statement);
                return false;
            }

            @Override
            public boolean visit(ContinueStatement node) {
                _statement = new DefaultMutableTreeNode(node.toString());
                System.out.println("ContinueStatement : " + node.toString());
                parentNode.add(_statement);
                return false;
            }

            @Override
            public boolean visit(SwitchStatement node) {
                _switch = new DefaultMutableTreeNode("switch (" + node.getExpression() + ")");
                System.out.println("switch (" + node.getExpression() + ")");
                parentNode.add(_switch);
                List getStatement = node.statements();
                for (Object st : getStatement) {
                    Matcher _caseMatch = Pattern.compile("^case\\s+.+\\:").matcher(st.toString());
                    if (_caseMatch.find()) {
                        _case = new DefaultMutableTreeNode(_caseMatch.group());
                        _switch.add(_case);
                    }

                    enclose(st.toString(), _case);

                    Matcher _breakMatch = Pattern.compile("^break\\s*.*;").matcher(st.toString());
                    if (_breakMatch.find()) {
                        _break = new DefaultMutableTreeNode(_breakMatch.group());
                        _case.add(_break);
                    }
                }
                return false;
            }

            @Override
            public boolean visit(ClassInstanceCreation node) {
                _constructorCall = new DefaultMutableTreeNode(node.toString());
                System.out.println("ClassInstanceCreation : " + node.toString());
                parentNode.add(_constructorCall);
                return false;
            }
        });
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:ASTParser.ParseJavaFile.java

private void parse(final String str, File outputFile) {
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(str.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    StringBuffer allComments = new StringBuffer();

    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

    for (Comment comment : (List<Comment>) cu.getCommentList()) {
        CommentVisitor commentVisitor = new CommentVisitor(cu, str);
        comment.accept(commentVisitor);/*from   ww w  . j ava2s  .  co  m*/
        //            System.out.println(commentVisitor.getAllComments().toString());
        allComments.append(commentVisitor.getAllComments().toString());
    }

    allComments = ParseWords.parseAllWords(allComments);
    writeToFile(allComments.toString(), outputFile);
}

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);//ww  w .j a  va2  s.c o 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:at.bestsolution.fxide.jdt.text.javadoc.JavadocContentAccess2.java

License:Open Source License

private static CompilationUnit createAST(IJavaElement element, String cuSource) {
    Assert.isNotNull(element);/*  w  w w.j a v  a  2  s.com*/
    ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);

    IJavaProject javaProject = element.getJavaProject();
    parser.setProject(javaProject);
    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.datagen.scm.AbstractCommit.java

License:Apache License

private boolean parseJavaFile(final String path, final ChangedFile.Builder fb, final String content,
        final String compliance, final int astLevel, final boolean storeOnError, Writer astWriter, String key) {
    try {/*  w w w .  j  a v a 2s . co  m*/
        final ASTParser parser = ASTParser.newParser(astLevel);
        parser.setKind(ASTParser.K_COMPILATION_UNIT);
        parser.setResolveBindings(true);
        parser.setSource(content.toCharArray());

        final Map options = JavaCore.getOptions();
        JavaCore.setComplianceOptions(compliance, options);
        parser.setCompilerOptions(options);

        final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

        final JavaErrorCheckVisitor errorCheck = new JavaErrorCheckVisitor();
        cu.accept(errorCheck);

        if (!errorCheck.hasError || storeOnError) {
            final ASTRoot.Builder ast = ASTRoot.newBuilder();
            //final CommentsRoot.Builder comments = CommentsRoot.newBuilder();
            final JavaVisitor visitor = new JavaVisitor(content, connector.nameIndices);
            try {
                ast.addNamespaces(visitor.getNamespaces(cu));
                for (final String s : visitor.getImports())
                    ast.addImports(s);
                /*for (final Comment c : visitor.getComments())
                   comments.addComments(c);*/
            } catch (final UnsupportedOperationException e) {
                return false;
            } catch (final Exception e) {
                if (debug)
                    System.err.println("Error visiting: " + path);
                e.printStackTrace();
                return false;
            }

            if (astWriter != null) {
                try {
                    astWriter.append(new Text(key), new BytesWritable(ast.build().toByteArray()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else
                fb.setAst(ast);
            //fb.setComments(comments);
        }

        return !errorCheck.hasError;
    } catch (final Exception e) {
        e.printStackTrace();
        return false;
    }
}