List of usage examples for org.eclipse.jdt.core.dom.rewrite ListRewrite insertLast
public void insertLast(ASTNode node, TextEditGroup editGroup)
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//w ww .j av a 2s . 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.ja v a 2 s .c om */ public Document generateTestPlan(StateMachineStateGraph stateGraph) { Document doc = new Document( "public abstract class TestPlanForStateMachine" + stateGraph.getStateMachineName() + " { \n"); //from here we use the cumbersome and extremely detailed Eclipse recommended DOM/AST library ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setSource(doc.get().toCharArray()); CompilationUnit cu = (CompilationUnit) parser.createAST(null); cu.recordModifications(); AST ast = cu.getAST(); ASTRewrite rewriter = ASTRewrite.create(ast); //create method which will contain one test plan (might be cloned and branched for each if-else in the state machine diagram) MethodDeclaration testPlanMethodDeclaration = ast.newMethodDeclaration(); testPlanMethodDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD)); testPlanMethodDeclaration.setName(ast.newSimpleName("testPlan")); testPlanMethodDeclaration.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID)); //return true if successful or false otherwise //create method body Block testPlanMethodBody = ast.newBlock(); testPlanMethodDeclaration.setBody(testPlanMethodBody); //create recursively the test plan by parsing the state graph starting with initial state try { generatePlanForState(stateGraph.getInitialState(), rewriter, testPlanMethodDeclaration, new HashSet<StateMachineStateTransition>()); } catch (NoSuchStateException 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 . java 2s. co m AST ast = cu.getAST(); ASTRewrite rewriter = ASTRewrite.create(ast); ListRewrite listRewrite = rewriter.getListRewrite(cu, CompilationUnit.TYPES_PROPERTY); //TODO: here we take each property introduced by each Stereotype for (Stereotype stereotype : source.getAppliedStereotypes()) { //get all properties for (Property attribute : stereotype.getAllAttributes()) { //todo } } for (Property property : source.getAllAttributes()) { System.out.println(property.getName()); Association assoc = property.getAssociation(); if (assoc == null) { System.out.format("this is simple %s \n", property.getName()); VariableDeclarationFragment varDecl = ast.newVariableDeclarationFragment(); varDecl.setName(ast.newSimpleName(property.getName())); FieldDeclaration propertyField = ast.newFieldDeclaration(varDecl); propertyField.setType(ast.newSimpleType(ast.newName(property.getType().getName()))); final SingleMemberAnnotation annot = ast.newSingleMemberAnnotation(); annot.setTypeName(ast.newName("Property")); StringLiteral st = ast.newStringLiteral(); st.setLiteralValue("type=\"variable\""); annot.setValue(st); listRewrite.insertLast(annot, null); listRewrite.insertLast(propertyField, null); } else { System.out.format("this is complex %s \n", property.getName()); Type type = assoc.getEndTypes().stream().filter(a -> !a.equals(source)).findFirst().get(); System.out.format("Association end is %s \n", type.getName()); AggregationKind kind = property.getAggregation(); if (kind.equals(AggregationKind.COMPOSITE)) { System.out.format("Composition \n"); } else if (kind.equals(AggregationKind.SHARED)) { System.out.format("Aggregation \n"); } else if (kind.equals(AggregationKind.NONE)) { System.out.format("Association \n"); } } } TextEdit edits = rewriter.rewriteAST(document, null); try { UndoEdit undo = edits.apply(document); } catch (MalformedTreeException | BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(document.get()); return null; }
From source file:ch.acanda.eclipse.pmd.java.resolution.design.UseUtilityClassQuickFix.java
License:Open Source License
private void addFinalIfNecessary(final TypeDeclaration typeDeclaration, final ASTRewrite rewrite) { @SuppressWarnings("unchecked") final List<IExtendedModifier> modifiers = typeDeclaration.modifiers(); if (!Iterables.any(modifiers, isFinal())) { final ListRewrite modifierRewrite = rewrite.getListRewrite(typeDeclaration, TypeDeclaration.MODIFIERS2_PROPERTY); final Modifier modifier = (Modifier) typeDeclaration.getAST().createInstance(Modifier.class); modifier.setKeyword(ModifierKeyword.FINAL_KEYWORD); modifierRewrite.insertLast(modifier, null); }//from w w w. j a v a 2 s .c om }
From source file:com.android.icu4j.srcgen.RunWithAnnotator.java
License:Apache License
private void appendImport(CompilationUnit cu, ASTRewrite rewriter, Name name) { ListRewrite lrw = rewriter.getListRewrite(cu, CompilationUnit.IMPORTS_PROPERTY); AST ast = cu.getAST();//from w ww. j a va 2s . c o m ImportDeclaration importDeclaration = ast.newImportDeclaration(); importDeclaration.setName(name); lrw.insertLast(importDeclaration, null); }
From source file:com.android.ide.eclipse.adt.internal.lint.AddSuppressAnnotation.java
License:Open Source License
@SuppressWarnings({ "rawtypes" }) // Java AST API has raw types
private MultiTextEdit addSuppressAnnotation(IDocument document, ICompilationUnit compilationUnit,
BodyDeclaration declaration) throws CoreException {
List modifiers = declaration.modifiers();
SingleMemberAnnotation existing = null;
for (Object o : modifiers) {
if (o instanceof SingleMemberAnnotation) {
SingleMemberAnnotation annotation = (SingleMemberAnnotation) o;
String type = annotation.getTypeName().getFullyQualifiedName();
if (type.equals(FQCN_SUPPRESS_LINT) || type.endsWith(SUPPRESS_LINT)) {
existing = annotation;/* www . j ava2 s.co m*/
break;
}
}
}
ImportRewrite importRewrite = ImportRewrite.create(compilationUnit, true);
String local = importRewrite.addImport(FQCN_SUPPRESS_LINT);
AST ast = declaration.getAST();
ASTRewrite rewriter = ASTRewrite.create(ast);
if (existing == null) {
SingleMemberAnnotation newAnnotation = ast.newSingleMemberAnnotation();
newAnnotation.setTypeName(ast.newSimpleName(local));
StringLiteral value = ast.newStringLiteral();
value.setLiteralValue(mId);
newAnnotation.setValue(value);
ListRewrite listRewrite = rewriter.getListRewrite(declaration, declaration.getModifiersProperty());
listRewrite.insertFirst(newAnnotation, null);
} else {
Expression existingValue = existing.getValue();
if (existingValue instanceof StringLiteral) {
StringLiteral stringLiteral = (StringLiteral) existingValue;
if (mId.equals(stringLiteral.getLiteralValue())) {
// Already contains the id
return null;
}
// Create a new array initializer holding the old string plus the new id
ArrayInitializer array = ast.newArrayInitializer();
StringLiteral old = ast.newStringLiteral();
old.setLiteralValue(stringLiteral.getLiteralValue());
array.expressions().add(old);
StringLiteral value = ast.newStringLiteral();
value.setLiteralValue(mId);
array.expressions().add(value);
rewriter.set(existing, VALUE_PROPERTY, array, null);
} else if (existingValue instanceof ArrayInitializer) {
// Existing array: just append the new string
ArrayInitializer array = (ArrayInitializer) existingValue;
List expressions = array.expressions();
if (expressions != null) {
for (Object o : expressions) {
if (o instanceof StringLiteral) {
if (mId.equals(((StringLiteral) o).getLiteralValue())) {
// Already contains the id
return null;
}
}
}
}
StringLiteral value = ast.newStringLiteral();
value.setLiteralValue(mId);
ListRewrite listRewrite = rewriter.getListRewrite(array, EXPRESSIONS_PROPERTY);
listRewrite.insertLast(value, null);
} else {
assert false : existingValue;
return null;
}
}
TextEdit importEdits = importRewrite.rewriteImports(new NullProgressMonitor());
TextEdit annotationEdits = rewriter.rewriteAST(document, null);
// Apply to the document
MultiTextEdit edit = new MultiTextEdit();
// Create the edit to change the imports, only if
// anything changed
if (importEdits.hasChildren()) {
edit.addChild(importEdits);
}
edit.addChild(annotationEdits);
return edit;
}
From source file:com.android.ide.eclipse.auidt.internal.lint.AddSuppressAnnotation.java
License:Open Source License
@SuppressWarnings({ "rawtypes" }) // Java AST API has raw types
private MultiTextEdit addSuppressAnnotation(IDocument document, ICompilationUnit compilationUnit,
BodyDeclaration declaration) throws CoreException {
List modifiers = declaration.modifiers();
SingleMemberAnnotation existing = null;
for (Object o : modifiers) {
if (o instanceof SingleMemberAnnotation) {
SingleMemberAnnotation annotation = (SingleMemberAnnotation) o;
String type = annotation.getTypeName().getFullyQualifiedName();
if (type.equals(FQCN_SUPPRESS_LINT) || type.endsWith(SUPPRESS_LINT)) {
existing = annotation;/*w ww . j a v a2 s . c o m*/
break;
}
}
}
ImportRewrite importRewrite = ImportRewrite.create(compilationUnit, true);
String local = importRewrite.addImport(FQCN_SUPPRESS_LINT);
AST ast = declaration.getAST();
ASTRewrite rewriter = ASTRewrite.create(ast);
if (existing == null) {
SingleMemberAnnotation newAnnotation = ast.newSingleMemberAnnotation();
newAnnotation.setTypeName(ast.newSimpleName(local));
StringLiteral value = ast.newStringLiteral();
value.setLiteralValue(mId);
newAnnotation.setValue(value);
ListRewrite listRewrite = rewriter.getListRewrite(declaration, declaration.getModifiersProperty());
listRewrite.insertFirst(newAnnotation, null);
} else {
Expression existingValue = existing.getValue();
if (existingValue instanceof StringLiteral) {
// Create a new array initializer holding the old string plus the new id
ArrayInitializer array = ast.newArrayInitializer();
StringLiteral old = ast.newStringLiteral();
StringLiteral stringLiteral = (StringLiteral) existingValue;
old.setLiteralValue(stringLiteral.getLiteralValue());
array.expressions().add(old);
StringLiteral value = ast.newStringLiteral();
value.setLiteralValue(mId);
array.expressions().add(value);
rewriter.set(existing, VALUE_PROPERTY, array, null);
} else if (existingValue instanceof ArrayInitializer) {
// Existing array: just append the new string
ArrayInitializer array = (ArrayInitializer) existingValue;
StringLiteral value = ast.newStringLiteral();
value.setLiteralValue(mId);
ListRewrite listRewrite = rewriter.getListRewrite(array, EXPRESSIONS_PROPERTY);
listRewrite.insertLast(value, null);
} else {
assert false : existingValue;
return null;
}
}
TextEdit importEdits = importRewrite.rewriteImports(new NullProgressMonitor());
TextEdit annotationEdits = rewriter.rewriteAST(document, null);
// Apply to the document
MultiTextEdit edit = new MultiTextEdit();
// Create the edit to change the imports, only if
// anything changed
if (importEdits.hasChildren()) {
edit.addChild(importEdits);
}
edit.addChild(annotationEdits);
return edit;
}
From source file:com.arcbees.gwtp.plugin.core.presenter.CreatePresenterPage.java
License:Apache License
private void addMethodsToNameTokens(ICompilationUnit unit, String nameToken, IProgressMonitor monitor) throws JavaModelException, MalformedTreeException, BadLocationException { String fieldName = getFieldNameFromNameToken(nameToken); Document document = new Document(unit.getSource()); CompilationUnit astRoot = initAstRoot(unit, monitor); // creation of ASTRewrite ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST()); // find existing method MethodDeclaration method = findMethod(astRoot, getNameTokenMethod(fieldName)); if (method != null) { logger.severe("FYI: the method in nameTokens already exists." + method.toString()); return;/*w w w . ja v a 2s. c o m*/ } List types = astRoot.types(); ASTNode rootNode = (ASTNode) types.get(0); ListRewrite listRewrite = rewrite.getListRewrite(rootNode, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); ASTNode fieldNode = rewrite.createStringPlaceholder( "public static final String " + fieldName + " = \"" + nameToken + "\";", ASTNode.EMPTY_STATEMENT); StringBuilder nameTokenMethod = new StringBuilder(); nameTokenMethod.append("public static String ").append(getNameTokenMethod(fieldName)).append("() {\n") .append("return " + fieldName + ";\n").append("}\n"); ASTNode methodNode = rewrite.createStringPlaceholder(nameTokenMethod.toString(), ASTNode.EMPTY_STATEMENT); listRewrite.insertFirst(fieldNode, null); listRewrite.insertLast(methodNode, null); // computation of the text edits TextEdit edits = rewrite.rewriteAST(document, unit.getJavaProject().getOptions(true)); // computation of the new source code edits.apply(document); // format code String newSource = new CodeFormattingUtil(getJavaProject(), monitor).formatCodeJavaClass(document); // update of the compilation unit and save it IBuffer buffer = unit.getBuffer(); buffer.setContents(newSource); buffer.save(monitor, true); }
From source file:com.google.currysrc.api.process.JavadocUtils.java
License:Apache License
public static void addJavadocTag(ASTRewrite rewrite, Javadoc javadoc, String tagText) { AST ast = javadoc.getAST();/* ww w.j a v a 2 s.c o m*/ TagElement tagElement = AstNodes.createTextTagElement(ast, tagText); ListRewrite listRewrite = rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY); listRewrite.insertLast(tagElement, null /* editGroup */); }
From source file:com.google.gdt.eclipse.appengine.rpc.markers.quickfixes.CreateRequestFactoryMethodProposal.java
License:Open Source License
@Override protected ASTRewrite getRewrite() { CompilationUnit targetAstRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null); createImportRewrite(targetAstRoot);/*from w w w .j a va 2 s. co m*/ // Find the target type declaration TypeDeclaration typeDecl = (TypeDeclaration) targetAstRoot.types().get(0); if (typeDecl == null) { return null; } ASTRewrite rewrite = ASTRewrite.create(targetAstRoot.getAST()); // Generate the new method declaration MethodDeclaration methodDecl = createMethodDeclaration(rewrite); if (methodDecl != null) { ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(typeDecl); ListRewrite listRewriter = rewrite.getListRewrite(typeDecl, property); listRewriter.insertLast(methodDecl, null); } return rewrite; }