Package org.eclipse.jdt.core.dom.rewrite

Examples of org.eclipse.jdt.core.dom.rewrite.ASTRewrite


   */
  protected void generateNewCompilationUnitAST(ICompilationUnit cu) throws JavaModelException {
    this.cuAST = parse(cu);

    AST ast = this.cuAST.getAST();
    ASTRewrite rewriter = ASTRewrite.create(ast);
    ASTNode child = generateElementAST(rewriter, cu);
    if (child != null) {
      ASTNode parent = ((JavaElement) getParentElement()).findNode(this.cuAST);
      if (parent == null)
        parent = this.cuAST;
      insertASTNode(rewriter, parent, child);
      TextEdit edits = rewriter.rewriteAST();
      applyTextEdit(cu, edits);
    }
    worked(1);
  }
View Full Code Here


            }
        }

        // now add all the new methods and fields to the existing
        // CompilationUnit with a ListRewrite
        ASTRewrite rewrite = ASTRewrite.create(topLevelType.getRoot().getAST());
        ListRewrite listRewrite = rewrite.getListRewrite(topLevelType,
                TypeDeclaration.BODY_DECLARATIONS_PROPERTY);

        Iterator<ASTNode> astIter = newJavaFileVisitor.getNewNodes().iterator();
        int i = 0;
        while (astIter.hasNext()) {
            ASTNode node = astIter.next();
           
            if (node.getNodeType() == ASTNode.TYPE_DECLARATION) {
                String name = ((TypeDeclaration) node).getName().getFullyQualifiedName();
                if (visitor.containsInnerClass(name)) {
                    continue;
                }
            }
           
            listRewrite.insertAt(node, i++, null);
        }

        textEdit = rewrite.rewriteAST(document, JavaCore.getOptions());
        try {
            textEdit.apply(document);
        } catch (BadLocationException e) {
            throw new ShellException(
                    "BadLocationException adding new fields and methods");
View Full Code Here

            }
        }

        // now add all the new methods and fields to the existing
        // CompilationUnit with a ListRewrite
        ASTRewrite rewrite = ASTRewrite.create(topLevelType.getRoot().getAST());
        ListRewrite listRewrite = rewrite.getListRewrite(topLevelType,
                TypeDeclaration.BODY_DECLARATIONS_PROPERTY);

        Iterator<ASTNode> astIter = newJavaFileVisitor.getNewNodes().iterator();
        int i = 0;
        while (astIter.hasNext()) {
            ASTNode node = astIter.next();

            if (node.getNodeType() == ASTNode.TYPE_DECLARATION) {
                String name = ((TypeDeclaration) node).getName()
                        .getFullyQualifiedName();
                if (visitor.containsInnerClass(name)) {
                    continue;
                }
            } else if (node instanceof FieldDeclaration) {
                addExistsAnnotations((BodyDeclaration) node,
                        visitor.getFieldAnnotations((FieldDeclaration) node));
            } else if (node instanceof MethodDeclaration) {
                addExistsAnnotations((BodyDeclaration) node,
                        visitor.getMethodAnnotations((MethodDeclaration) node));
            }

            listRewrite.insertAt(node, i++, null);
        }

        textEdit = rewrite.rewriteAST(document, JavaCore.getOptions());
        try {
            textEdit.apply(document);
        } catch (BadLocationException e) {
            throw new ShellException(
                    "BadLocationException adding new fields and methods");
View Full Code Here

  public ImportAssertRewriter(String node) {
    m_assert = node;
  }

  public ASTRewrite createRewriter(CompilationUnit astRoot, AST ast) {
    final ASTRewrite result = ASTRewrite.create(astRoot.getAST());
    TestNGVisitor visitor = new TestNGVisitor();
    astRoot.accept(visitor);

    //
    // Add a static import for this method
    //
    ListRewrite lr = result.getListRewrite(astRoot, CompilationUnit.IMPORTS_PROPERTY);
    ImportDeclaration id = ast.newImportDeclaration();
    id.setStatic(true);
    id.setName(ast.newName("org.testng.AssertJUnit." + m_assert));
    lr.insertFirst(id, null);
View Full Code Here

* @author Cedric Beust <cedric@beust.com>
*/
public class PullTestRewriter implements IRewriteProvider {

  public ASTRewrite createRewriter(CompilationUnit astRoot, AST ast) {
    final ASTRewrite result = ASTRewrite.create(astRoot.getAST());
    TestNGVisitor visitor = new TestNGVisitor();
    astRoot.accept(visitor);

    //
    // Remove all the @Test annotations
    //
    for (Annotation a: visitor.getTestMethods().values()) {
      result.remove(a, null);
    }

    //
    // Add @Test at the class level
    //
    MarkerAnnotation test = ast.newMarkerAnnotation();
    test.setTypeName(ast.newName("Test"));
    ListRewrite lr = result.getListRewrite(visitor.getType(), TypeDeclaration.MODIFIERS2_PROPERTY);
    lr.insertFirst(test, null);

    return result;
  }
View Full Code Here

        String node = findAssertInContext(context);
        if (node != null) providers.add(new ImportAssertRewriter(node));
      }

      for (IRewriteProvider provider : providers) {
        ASTRewrite rewriter = provider.createRewriter(m_astRoot, m_ast);
        vResult.add(new JUnitRewriteCorrectionProposal(
            provider.getName(), m_compilationUnit, rewriter, 1));
      }
    }
   
View Full Code Here

      IRewriteProvider[] providers = new IRewriteProvider[] {
          new AnnotationRewriter(),
      };

      for (int i = 0; i < providers.length; i++) {
        ASTRewrite rewriter = providers[i].createRewriter(astRoot, ast);
        vResult.add(new JUnitRewriteCorrectionProposal(
            providers[i].getName(), cu, rewriter, 1));
      }
    }
   
View Full Code Here

    return change;
  }

  protected void addEdits(IDocument document, TextEdit editRoot) throws CoreException {
//    super.addEdits(document, editRoot);
    ASTRewrite rewrite = m_rewriter;
    if (rewrite != null) {
      try {
        TextEdit edit= rewrite.rewriteAST();
        editRoot.addChild(edit);
      } catch (IllegalArgumentException e) {
        throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
      }
    }
View Full Code Here

  private static final Set<String> STATIC_IMPORTS_TO_REMOVE = new HashSet<String>() {{
    add("org.junit.Assert");
  }};

  public ASTRewrite createRewriter(CompilationUnit astRoot, AST ast) {
    final ASTRewrite result = ASTRewrite.create(astRoot.getAST());
    JUnitVisitor visitor = new JUnitVisitor();
    astRoot.accept(visitor);


    //
    // Remove some JUnit imports.
    //
    List<ImportDeclaration> oldImports = visitor.getJUnitImports();
    for (int i = 0; i < oldImports.size(); i++) {
      Name importName = oldImports.get(i).getName();
      String fqn = importName.getFullyQualifiedName();
      if (IMPORTS_TO_REMOVE.contains(fqn)) {
        result.remove(oldImports.get(i), null);
      }
      for (String s : STATIC_IMPORTS_TO_REMOVE) {
        if (fqn.contains(s)) {
          result.remove(oldImports.get(i), null);
        }
      }
    }
   
    //
    // Add imports as needed
    //
    maybeAddImport(ast, result, astRoot, visitor.hasAsserts(), "org.testng.AssertJUnit");
    maybeAddImport(ast, result, astRoot, visitor.hasFail(), "org.testng.Assert");
    maybeAddImport(ast, result, astRoot, !visitor.getBeforeClasses().isEmpty(),
    "org.testng.annotations.BeforeClass");
    maybeAddImport(ast, result, astRoot, !visitor.getBeforeMethods().isEmpty(),
        "org.testng.annotations.BeforeMethod");
    maybeAddImport(ast, result, astRoot, visitor.hasTestMethods(), "org.testng.annotations.Test");
    maybeAddImport(ast, result, astRoot, !visitor.getAfterMethods().isEmpty(),
        "org.testng.annotations.AfterMethod");
    maybeAddImport(ast, result, astRoot, !visitor.getAfterClasses().isEmpty(),
    "org.testng.annotations.AfterClass");

    //
    // Add static imports
    //
    Set<String> staticImports = visitor.getStaticImports();
    for (String si : staticImports) {
      addImport(ast, result, astRoot, "org.testng.AssertJUnit." + si, true /* static import */);
    }

    //
    // Remove "extends TestCase"
    //
    SimpleType td = visitor.getTestCase();
    if (null != td) {
      result.remove(td, null);
    }

    //
    // Addd the annotations as needed
    //
    maybeAddAnnotations(ast, visitor, result, visitor.getTestMethods(), "Test", null, null);
    maybeAddAnnotations(ast, visitor, result, visitor.getDisabledTestMethods(), "Test", null,
        createDisabledAttribute(ast));
    maybeAddAnnotations(ast, visitor, result, visitor.getBeforeMethods(), "BeforeMethod",
        "@Before" /* annotation to remove */);
    maybeAddAnnotations(ast, visitor, result, visitor.getAfterMethods(), "AfterMethod",
        "@After" /* annotation to remove */);

    //
    // suite() method: remove, comment out or leave untouched, depending on the setting
    //
    SuiteMethodTreatment smt = TestNGPlugin.getPluginPreferenceStore().getSuiteMethodTreatement();

    MethodDeclaration suiteMethod = visitor.getSuite();
    if (smt != SuiteMethodTreatment.DONT_TOUCH && suiteMethod != null) {
      if (smt == SuiteMethodTreatment.REMOVE) {
        // Remove suite()
        result.remove(suiteMethod, null);
      } else {
        // Comment out suite()
        TypeDeclaration type = visitor.getType();
        ListRewrite lr = result.getListRewrite(type, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
        lr.insertBefore(result.createStringPlaceholder("/*", ASTNode.METHOD_DECLARATION),
            suiteMethod, null);
        lr.insertAfter(result.createStringPlaceholder("*/", ASTNode.METHOD_DECLARATION),
            suiteMethod, null);
      }
    }

    //
    // Remove all the nodes that need to be removed
    //
    for (ASTNode n : visitor.getNodesToRemove()) {
      result.remove(n, null);
    }

    //
    // Replace @Ignore with @Test(enabled = false)
    //
    for (Map.Entry<MethodDeclaration, Annotation> e : visitor.getIgnoredMethods().entrySet()) {
      MethodDeclaration md = e.getKey();
      Annotation ignored = e.getValue();
      // Add the @Test(enabled = false)
      NormalAnnotation test = ast.newNormalAnnotation();
      test.setTypeName(ast.newName("Test"));
      MemberValuePair mvp = ast.newMemberValuePair();
      mvp.setName(ast.newSimpleName("enabled"));
      mvp.setValue(ast.newBooleanLiteral(false));
      test.values().add(mvp);
      result.remove(ignored, null);
      ListRewrite lr = result.getListRewrite(md, MethodDeclaration.MODIFIERS2_PROPERTY);
      lr.insertFirst(test, null);
    }

    //
    // Replace "Assert" with "AssertJUnit", unless the method is already imported statically.
    //
    Set<MethodInvocation> asserts = visitor.getAsserts();
    for (MethodInvocation m : asserts) {
      if (! staticImports.contains(m.getName().toString())) {
        Expression exp = m.getExpression();
        Name name = ast.newName("AssertJUnit");
        if (exp != null) {
          result.replace(exp, name, null);
        } else {
          result.set(m, MethodInvocation.EXPRESSION_PROPERTY, name, null);
        }
      }
    }

    //
    // Replace "fail()" with "Assert.fail()"
    //
    for (MethodInvocation fail : visitor.getFails()) {
      SimpleName exp = ast.newSimpleName("Assert");
      result.set(fail, MethodInvocation.EXPRESSION_PROPERTY, exp, null);
    }

    //
    // Replace @Test(expected) with @Test(expectedExceptions)
    // and @Test(timeout) with @Test(timeOut)
    //
    for (Map.Entry<MemberValuePair, String> pair : visitor.getTestsWithExpected().entrySet()) {
      result.replace(pair.getKey().getName(), ast.newSimpleName(pair.getValue()), null);
    }

    //
    // Remove super invocation in the constructor
    //
    SuperConstructorInvocation sci = visitor.getSuperConstructorInvocation();
    if (sci != null) {
      result.remove(sci, null);
    }

    //
    // Convert @RunWith(Parameterized.class)
    //
    SingleMemberAnnotation runWith = visitor.getRunWithParameterized();
    if (runWith != null) {
      // Remove @RunWith
      result.remove(runWith, null);

      // Add imports
      addImport(ast, result, astRoot, "org.testng.ConversionUtils.wrapDataProvider",
          true /* static import */);
      addImport(ast, result, astRoot, "org.testng.annotations.Factory", false /* not static */);

      // Add the factory method
      MethodDeclaration parameterMethod = visitor.getParametersMethod();
      ListRewrite lr = result.getListRewrite(visitor.getType(),
          TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
      MethodDeclaration md = ast.newMethodDeclaration();
      md.setName(ast.newSimpleName("factory" + capitalize(parameterMethod.getName().toString())));

      // Add the "Factory" annotation
View Full Code Here

* @author Cedric Beust <cedric@beust.com>
*/
public class PushTestRewriter implements IRewriteProvider {

  public ASTRewrite createRewriter(CompilationUnit astRoot, AST ast) {
    final ASTRewrite result = ASTRewrite.create(astRoot.getAST());
    TestNGVisitor visitor = new TestNGVisitor();
    astRoot.accept(visitor);

    //
    // Remove the class @Test annotation
    //
    result.remove(visitor.getTestClassAnnotation(), null);

    //
    // Add a @Test annotation on all the public methods that don't already
    // have a TestNG annotation.
    //
    for (MethodDeclaration md : visitor.getPublicMethods()) {
      ListRewrite lr = result.getListRewrite(md, MethodDeclaration.MODIFIERS2_PROPERTY);
      MarkerAnnotation test = ast.newMarkerAnnotation();
      test.setTypeName(ast.newSimpleName("Test"));
      lr.insertFirst(test, null);
    }

View Full Code Here

TOP

Related Classes of org.eclipse.jdt.core.dom.rewrite.ASTRewrite

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.