List of usage examples for org.eclipse.jdt.core.dom CompilationUnit recordModifications
public void recordModifications()
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/* www. j a v 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 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 . ja va2 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(); AST ast = cu.getAST();/*from ww w .j a v a 2 s . c o m*/ ASTRewrite rewriter = ASTRewrite.create(ast); ListRewrite listRewrite = rewriter.getListRewrite(cu, CompilationUnit.TYPES_PROPERTY); //TODO: here we take each property introduced by each Stereotype for (Stereotype stereotype : source.getAppliedStereotypes()) { //get all properties for (Property attribute : stereotype.getAllAttributes()) { //todo } } for (Property property : source.getAllAttributes()) { System.out.println(property.getName()); Association assoc = property.getAssociation(); if (assoc == null) { System.out.format("this is simple %s \n", property.getName()); VariableDeclarationFragment varDecl = ast.newVariableDeclarationFragment(); varDecl.setName(ast.newSimpleName(property.getName())); FieldDeclaration propertyField = ast.newFieldDeclaration(varDecl); propertyField.setType(ast.newSimpleType(ast.newName(property.getType().getName()))); final SingleMemberAnnotation annot = ast.newSingleMemberAnnotation(); annot.setTypeName(ast.newName("Property")); StringLiteral st = ast.newStringLiteral(); st.setLiteralValue("type=\"variable\""); annot.setValue(st); listRewrite.insertLast(annot, null); listRewrite.insertLast(propertyField, null); } else { System.out.format("this is complex %s \n", property.getName()); Type type = assoc.getEndTypes().stream().filter(a -> !a.equals(source)).findFirst().get(); System.out.format("Association end is %s \n", type.getName()); AggregationKind kind = property.getAggregation(); if (kind.equals(AggregationKind.COMPOSITE)) { System.out.format("Composition \n"); } else if (kind.equals(AggregationKind.SHARED)) { System.out.format("Aggregation \n"); } else if (kind.equals(AggregationKind.NONE)) { System.out.format("Association \n"); } } } TextEdit edits = rewriter.rewriteAST(document, null); try { UndoEdit undo = edits.apply(document); } catch (MalformedTreeException | BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(document.get()); return null; }
From source file:ch.acanda.eclipse.pmd.java.resolution.ASTQuickFix.java
License:Open Source License
@Override protected void startFixingMarkers(final CompilationUnit ast) { ast.recordModifications(); }
From source file:ch.acanda.eclipse.pmd.java.resolution.ASTQuickFixTestCase.java
License:Open Source License
private CompilationUnit createAST(final org.eclipse.jface.text.Document document, final ASTQuickFix<ASTNode> quickFix) { final ASTParser astParser = ASTParser.newParser(AST.JLS4); astParser.setSource(document.get().toCharArray()); astParser.setKind(ASTParser.K_COMPILATION_UNIT); astParser.setResolveBindings(quickFix.needsTypeResolution()); astParser.setEnvironment(new String[0], new String[0], new String[0], true); final String name = last(params.pmdReferenceId.or("QuickFixTest").split("/")); astParser.setUnitName(format("{0}.java", name)); final String version = last(params.language.or("java 1.7").split("\\s+")); astParser.setCompilerOptions(ImmutableMap.<String, String>builder().put(JavaCore.COMPILER_SOURCE, version) .put(JavaCore.COMPILER_COMPLIANCE, version).put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, version) .build());/*from www . j a v a 2 s. c o m*/ final CompilationUnit ast = (CompilationUnit) astParser.createAST(null); ast.recordModifications(); return ast; }
From source file:ch.acanda.eclipse.pmd.java.resolution.TextEditQuickFixTestCase.java
License:Open Source License
private CompilationUnit createAST(final org.eclipse.jface.text.Document document) { final ASTParser astParser = ASTParser.newParser(AST.JLS4); astParser.setKind(ASTParser.K_COMPILATION_UNIT); astParser.setSource(document.get().toCharArray()); astParser.setCompilerOptions(/* www . j a v a 2s . c o m*/ ImmutableMap.<String, String>builder().put(JavaCore.COMPILER_SOURCE, "1.7").build()); final CompilationUnit ast = (CompilationUnit) astParser.createAST(null); ast.recordModifications(); return ast; }
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(); AST ast = unit.getAST();//from w w w .j av a 2 s . com 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:com.alex.example.fixlicense.actions.SampleAction.java
License:Open Source License
private void processInlineLicense(IDocument doc) throws Exception { CompilationUnit cu = getAST(doc); cu.recordModifications(); AST ast = cu.getAST();/*from w w w. j av a2 s .c o m*/ 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.ashigeru.eclipse.util.jdt.internal.ui.handlers.InsertAssertionHandler.java
License:Apache License
private TextEdit createEdit(CompilationUnit ast, MethodDeclaration method, IDocument target) { assert ast != null; assert method != null; assert target != null; List<String> objectParams = new ArrayList<String>(); for (Object o : method.parameters()) { SingleVariableDeclaration var = (SingleVariableDeclaration) o; if (var.getType().getNodeType() != ASTNode.PRIMITIVE_TYPE) { objectParams.add(var.getName().getIdentifier()); }// w w w . ja va2s . c o m } if (objectParams.isEmpty()) { return null; } AST factory = ast.getAST(); ast.recordModifications(); List<Statement> toInsert = new ArrayList<Statement>(); for (String name : objectParams) { AssertStatement assertion = createAssertion(factory, name); toInsert.add(assertion); } Block body = method.getBody(); @SuppressWarnings("unchecked") List<Statement> statements = body.statements(); int offset = 0; if (statements.isEmpty() == false) { Statement first = statements.get(0); int type = first.getNodeType(); if (type == ASTNode.CONSTRUCTOR_INVOCATION || type == ASTNode.SUPER_CONSTRUCTOR_INVOCATION) { offset++; } } statements.addAll(offset, toInsert); return ast.rewrite(target, null); }
From source file:com.crispico.flower.mp.codesync.code.java.adapter.JavaFileModelAdapter.java
License:Open Source License
/** * Creates a new compilation unit from the file's content. *//*from ww w . j av a2 s . c o m*/ @Override protected Object createFileInfo(Object file) { ASTParser parser = ASTParser.newParser(AST.JLS4); Map options = new HashMap<>(JavaCore.getOptions()); options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_7); parser.setCompilerOptions(options); boolean fileExists = EditorPlugin.getInstance().getFileAccessController().exists(file); char[] initialContent = fileExists ? getFileContent(file) : new char[0]; parser.setSource(initialContent); CompilationUnit astRoot = (CompilationUnit) parser.createAST(null); astRoot.recordModifications(); return astRoot; }