List of usage examples for org.eclipse.jdt.core.dom CompilationUnit getAST
public final AST getAST()
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 . 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 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 .jav 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 w w w. j a v a 2 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:br.com.objectos.way.core.code.jdt.CompilationUnitWriter.java
License:Apache License
private CompilationUnitWriter(CompilationUnit compilationUnit, PackageInfo packageInfo) { this.ast = compilationUnit.getAST(); this.compilationUnit = compilationUnit; this.packageInfo = packageInfo; }
From source file:cideplus.ui.astview.ASTView.java
License:Open Source License
private void updateContentDescription(IJavaElement element, CompilationUnit root, long time) { String version = root.getAST().apiLevel() == JLS2 ? "AST Level 2" : "AST Level 3"; //$NON-NLS-1$//$NON-NLS-2$ if (getCurrentInputKind() == ASTInputKindAction.USE_RECONCILE) { version += ", from reconciler"; //$NON-NLS-1$ } else if (getCurrentInputKind() == ASTInputKindAction.USE_CACHE) { version += ", from ASTProvider"; //$NON-NLS-1$ } else if (getCurrentInputKind() == ASTInputKindAction.USE_FOCAL) { version += ", using focal position"; //$NON-NLS-1$ }/*from ww w .j a va2 s . co m*/ TreeInfoCollector collector = new TreeInfoCollector(root); String msg = "{0} ({1}). Creation time: {2,number} ms. Size: {3,number} nodes, {4,number} bytes (AST nodes only)."; //$NON-NLS-1$ Object[] args = { element.getElementName(), version, new Long(time), new Integer(collector.getNumberOfNodes()), new Integer(collector.getSize()) }; setContentDescription(MessageFormat.format(msg, args)); }
From source file:cn.ieclipse.adt.ext.jdt.SourceGenerator.java
License:Apache License
private static void merge(CompilationUnit unit, String pkgName, String typeName, String auth, String dbName, List<String> tableCreators) { unit.recordModifications();/*from ww w .ja v a2s . c o m*/ AST ast = unit.getAST(); TypeDeclaration type = (TypeDeclaration) unit.types().get(0); ImportDeclaration id = ast.newImportDeclaration(); id.setName(ast.newName("cn.ieclipse.aorm.Session")); unit.imports().add(id); id = ast.newImportDeclaration(); id.setName(ast.newName("android.content.UriMatcher")); unit.imports().add(id); id = ast.newImportDeclaration(); id.setName(ast.newName("android.database.sqlite.SQLiteDatabase")); unit.imports().add(id); id = ast.newImportDeclaration(); id.setName(ast.newName("android.database.sqlite.SQLiteOpenHelper")); unit.imports().add(id); id = ast.newImportDeclaration(); id.setName(ast.newName("java.net.Uri")); unit.imports().add(id); id = ast.newImportDeclaration(); id.setName(ast.newName("android.content.ContentValue")); unit.imports().add(id); VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment(); vdf.setName(ast.newSimpleName("AUTH")); StringLiteral sl = ast.newStringLiteral(); sl.setLiteralValue(auth); vdf.setInitializer(sl); FieldDeclaration fd = ast.newFieldDeclaration(vdf); fd.modifiers().addAll(ast.newModifiers((Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL))); fd.setType(ast.newSimpleType(ast.newSimpleName("String"))); int i = 0; type.bodyDeclarations().add(i++, fd); // URI = Uri.parse("content://" + AUTH); vdf = ast.newVariableDeclarationFragment(); vdf.setName(ast.newSimpleName("URI")); MethodInvocation mi = ast.newMethodInvocation(); mi.setExpression(ast.newSimpleName("Uri")); mi.setName(ast.newSimpleName("parse")); InfixExpression fix = ast.newInfixExpression(); fix.setOperator(InfixExpression.Operator.PLUS); sl = ast.newStringLiteral(); sl.setLiteralValue("content://"); fix.setLeftOperand(sl); fix.setRightOperand(ast.newSimpleName("AUTH")); mi.arguments().add(fix); vdf.setInitializer(mi); fd = ast.newFieldDeclaration(vdf); fd.modifiers().addAll(ast.newModifiers((Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL))); fd.setType(ast.newSimpleType(ast.newSimpleName("Uri"))); type.bodyDeclarations().add(i++, fd); // private mOpenHelper; vdf = ast.newVariableDeclarationFragment(); vdf.setName(ast.newSimpleName("mOpenHelper")); fd = ast.newFieldDeclaration(vdf); fd.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD)); fd.setType(ast.newSimpleType(ast.newName("SQLiteOpenHelper"))); type.bodyDeclarations().add(i++, fd); // private static session; vdf = ast.newVariableDeclarationFragment(); vdf.setName(ast.newSimpleName("session")); fd = ast.newFieldDeclaration(vdf); fd.modifiers().addAll(ast.newModifiers((Modifier.PRIVATE | Modifier.STATIC))); fd.setType(ast.newSimpleType(ast.newName("Session"))); type.bodyDeclarations().add(i++, fd); // public static Session getSession(){ // return session; // } MethodDeclaration md = ast.newMethodDeclaration(); md.modifiers().addAll(ast.newModifiers((Modifier.PUBLIC | Modifier.STATIC))); md.setReturnType2(ast.newSimpleType(ast.newName("Session"))); md.setName(ast.newSimpleName("getSession")); Block methodBlock = ast.newBlock(); ReturnStatement returnStmt = ast.newReturnStatement(); returnStmt.setExpression(ast.newSimpleName("session")); methodBlock.statements().add(returnStmt); md.setBody(methodBlock); type.bodyDeclarations().add(i, md); // modify onCreate rewriteOnCreate(unit, dbName, tableCreators); }
From source file:cn.ieclipse.adt.ext.jdt.SourceGenerator.java
License:Apache License
private static void rewriteOnCreate(CompilationUnit unit, String dbName, List<String> tableCreators) { AST ast = unit.getAST(); TypeDeclaration type = (TypeDeclaration) unit.types().get(0); MethodDeclaration onCreate = getMethod(type, ("onCreate"), null); if (onCreate != null) { Block methodBlock = ast.newBlock(); // mOpenHelper = new // InlineOpenHelper(this.getContext(),"person.db",null,1); Assignment a = ast.newAssignment(); a.setOperator(Assignment.Operator.ASSIGN); a.setLeftHandSide(ast.newSimpleName("mOpenHelper")); ClassInstanceCreation cc = ast.newClassInstanceCreation(); cc.setType(ast.newSimpleType(ast.newSimpleName("SQLiteOpenHelper"))); ThisExpression thisExp = ast.newThisExpression(); MethodInvocation mi = ast.newMethodInvocation(); mi.setName(ast.newSimpleName("getContext")); mi.setExpression(thisExp);/* ww w .j ava 2 s . c om*/ cc.arguments().add(mi); StringLiteral sl = ast.newStringLiteral(); sl.setLiteralValue(dbName); cc.arguments().add(sl); cc.arguments().add(ast.newNullLiteral()); cc.arguments().add(ast.newNumberLiteral("1")); a.setRightHandSide(cc); methodBlock.statements().add(ast.newExpressionStatement(a)); AnonymousClassDeclaration acd = ast.newAnonymousClassDeclaration(); cc.setAnonymousClassDeclaration(acd); genInnerSQLiteOpenHelper(acd, ast, tableCreators); a = ast.newAssignment(); a.setOperator(Assignment.Operator.ASSIGN); a.setLeftHandSide(ast.newSimpleName("session")); ClassInstanceCreation cic = ast.newClassInstanceCreation(); cic.setType(ast.newSimpleType(ast.newSimpleName("Session"))); // SingleVariableDeclaration svd = // ast.newSingleVariableDeclaration(); // svd.setName(ast.newSimpleName("mOpenHelper")); cic.arguments().add(ast.newSimpleName("mOpenHelper")); // vdf.setInitializer(cic); a.setRightHandSide(cic); // methodBlock.statements().add(vde); methodBlock.statements().add(ast.newExpressionStatement(a)); ReturnStatement returnStmt = ast.newReturnStatement(); returnStmt.setExpression(ast.newBooleanLiteral(true)); methodBlock.statements().add(returnStmt); onCreate.setBody(methodBlock); } }
From source file:cn.ieclipse.adt.ext.jdt.SourceGenerator.java
License:Apache License
public static void applyChange(ICompilationUnit cu, CompilationUnit unit) { try {//from w ww . java 2 s . co 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.alex.example.fixlicense.actions.SampleAction.java
License:Open Source License
private void processInlineLicense(IDocument doc) throws Exception { CompilationUnit cu = getAST(doc); cu.recordModifications();/*from w ww .j a va 2 s .co m*/ AST ast = cu.getAST(); if (cu.types().get(0) instanceof TypeDeclaration) { TypeDeclaration td = (TypeDeclaration) cu.types().get(0); FieldDeclaration[] fd = td.getFields(); if (fd.length == 0) { td.bodyDeclarations().add(0, createLiceseInLineField(ast)); } else { FieldDeclaration firstFd = fd[0]; VariableDeclarationFragment vdf = (VariableDeclarationFragment) firstFd.fragments().get(0); if (vdf.getName().getIdentifier().equals("COPYRIGHT")) { td.bodyDeclarations().remove(0); td.bodyDeclarations().add(0, createLiceseInLineField(ast)); } else { td.bodyDeclarations().add(0, createLiceseInLineField(ast)); } } } //record changes TextEdit edits = cu.rewrite(doc, null); edits.apply(doc); }
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(); 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); }/* w ww. j a va 2 s . co m*/ 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; }