Java Code Examples for com.sun.source.tree.CompilationUnitTree

The following examples show how to use com.sun.source.tree.CompilationUnitTree. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private void runField(String code) throws IOException {
    String src = prefix +
            code + "; }" +
            postfix;

    try (JavaFileManager fm = tool.getStandardFileManager(null, null, null)) {
        JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null,
                null, Arrays.asList(new MyFileObject(src)));

        for (CompilationUnitTree cut : ct.parse()) {
            JCTree.JCVariableDecl var =
                    (JCTree.JCVariableDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);
            checkMatch(code, var);
        }
    }
}
 
Example 2
Source Project: netbeans   Source File: JavaSourceHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static ClassTree getTopLevelClassTree(CompilationController controller) {
    String className = controller.getFileObject().getName();

    CompilationUnitTree cu = controller.getCompilationUnit();
    if (cu != null) {
        List<? extends Tree> decls = cu.getTypeDecls();
        for (Tree decl : decls) {
            if (!TreeUtilities.CLASS_TREE_KINDS.contains(decl.getKind())) {
                continue;
            }

            ClassTree classTree = (ClassTree) decl;

            if (classTree.getSimpleName().contentEquals(className) && classTree.getModifiers().getFlags().contains(Modifier.PUBLIC)) {
                return classTree;
            }
        }
    }
    return null;
}
 
Example 3
Source Project: netbeans   Source File: StaticImport.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    WorkingCopy copy = ctx.getWorkingCopy();
    TreePath treePath = ctx.getPath();
    TreePath mitp = treePath.getParentPath();
    if (mitp == null) {
        return;
    }
    Element e = copy.getTrees().getElement(treePath);
    if (e == null || !e.getModifiers().contains(Modifier.STATIC)) {
        return;
    }
    TreeMaker make = copy.getTreeMaker();
    copy.rewrite(treePath.getLeaf(), make.Identifier(sn));
    if (fqn == null) {
        return;
    }
    CompilationUnitTree cut = (CompilationUnitTree) copy.resolveRewriteTarget(copy.getCompilationUnit());
    CompilationUnitTree nue = GeneratorUtilities.get(copy).addImports(cut, Collections.singleton(e));
    copy.rewrite(cut, nue);
}
 
Example 4
Source Project: jdk8u60   Source File: JavacParserTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
void testMissingParenthesisError() throws IOException {

    String code = "package test; public class ErrorTest { "
            + "void f() {String s = new String; } }";
    CompilationUnitTree cut = getCompilationUnitTree(code);
    final List<String> values = new ArrayList<>();
    final List<String> expectedValues =
            new ArrayList<>(Arrays.asList("[new String()]"));

    new TreeScanner<Void, Void>() {
        @Override
        public Void visitErroneous(ErroneousTree node, Void p) {
            values.add(getErroneousTreeValues(node).toString());
            return null;
        }
    }.scan(cut, null);

    assertEquals("testSwitchError: The Erroneous tree "
            + "error values: " + values
            + " do not match expected error values: "
            + expectedValues, values, expectedValues);
}
 
Example 5
Source Project: openjdk-8-source   Source File: ApNavigator.java    License: GNU General Public License v2.0 6 votes vote down vote up
private Location getLocation(final String name, final TreePath treePath) {
    return new Location() {
        public String toString() {
            if (treePath == null)
                return name + " (Unknown Source)";
            // just like stack trace, we just print the file name and
            // not the whole path. The idea is that the package name should
            // provide enough clue on which directory it lives.
            CompilationUnitTree compilationUnit = treePath.getCompilationUnit();
            Trees trees = Trees.instance(env);
            long startPosition = trees.getSourcePositions().getStartPosition(compilationUnit, treePath.getLeaf());
            return name + "(" +
                    compilationUnit.getSourceFile().getName() + ":" + compilationUnit.getLineMap().getLineNumber(startPosition) +
                    ")";
        }
    };
}
 
Example 6
@Test
void testMissingParenthesisError() throws IOException {

    String code = "package test; public class ErrorTest { "
            + "void f() {String s = new String; } }";
    CompilationUnitTree cut = getCompilationUnitTree(code);
    final List<String> values = new ArrayList<>();
    final List<String> expectedValues =
            new ArrayList<>(Arrays.asList("[new String()]"));

    new TreeScanner<Void, Void>() {
        @Override
        public Void visitErroneous(ErroneousTree node, Void p) {
            values.add(getErroneousTreeValues(node).toString());
            return null;
        }
    }.scan(cut, null);

    assertEquals("testSwitchError: The Erroneous tree "
            + "error values: " + values
            + " do not match expected error values: "
            + expectedValues, values, expectedValues);
}
 
Example 7
@Test
void testMissingClassError() throws IOException {

    String code = "package Test; clas ErrorTest {  "
            + "void f() {String s = new String(); } }";
    CompilationUnitTree cut = getCompilationUnitTree(code);
    final List<String> values = new ArrayList<>();
    final List<String> expectedValues =
            new ArrayList<>(Arrays.asList("[, clas]", "[]"));

    new TreeScanner<Void, Void>() {
        @Override
        public Void visitErroneous(ErroneousTree node, Void p) {
            values.add(getErroneousTreeValues(node).toString());
            return null;
        }
    }.scan(cut, null);

    assertEquals("testSwitchError: The Erroneous tree "
            + "error values: " + values
            + " do not match expected error values: "
            + expectedValues, values, expectedValues);
}
 
Example 8
Source Project: openjdk-8-source   Source File: T6963934.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File thisSrc = new File(testSrc, T6963934.class.getSimpleName() + ".java");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    JavacTask task = (JavacTask) compiler.getTask(null, fileManager, null, null, null,
            fileManager.getJavaFileObjects(thisSrc));
    CompilationUnitTree tree = task.parse().iterator().next();
    int count = 0;
    for (ImportTree importTree : tree.getImports()) {
        System.out.println(importTree);
        count++;
    }
    int expected = 7;
    if (count != expected)
        throw new Exception("unexpected number of imports found: " + count + ", expected: " + expected);
}
 
Example 9
@Test
void testNewClassWithEnclosing() throws IOException {

    final String theString = "Test.this.new d()";
    String code = "package test; class Test { " +
            "class d {} private void method() { " +
            "Object o = " + theString + "; } }";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(code)));
    CompilationUnitTree cut = ct.parse().iterator().next();
    SourcePositions pos = Trees.instance(ct).getSourcePositions();

    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    ExpressionTree est =
            ((VariableTree) ((MethodTree) clazz.getMembers().get(1)).getBody().getStatements().get(0)).getInitializer();

    final int spos = code.indexOf(theString);
    final int epos = spos + theString.length();
    assertEquals("testNewClassWithEnclosing",
            spos, pos.getStartPosition(cut, est));
    assertEquals("testNewClassWithEnclosing",
            epos, pos.getEndPosition(cut, est));
}
 
Example 10
private Location getLocation(final String name, final TreePath treePath) {
    return new Location() {
        public String toString() {
            if (treePath == null)
                return name + " (Unknown Source)";
            // just like stack trace, we just print the file name and
            // not the whole path. The idea is that the package name should
            // provide enough clue on which directory it lives.
            CompilationUnitTree compilationUnit = treePath.getCompilationUnit();
            Trees trees = Trees.instance(env);
            long startPosition = trees.getSourcePositions().getStartPosition(compilationUnit, treePath.getLeaf());
            return name + "(" +
                    compilationUnit.getSourceFile().getName() + ":" + compilationUnit.getLineMap().getLineNumber(startPosition) +
                    ")";
        }
    };
}
 
Example 11
Source Project: netbeans   Source File: CopyClassesRefactoringPlugin.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run(WorkingCopy compiler) throws IOException {
    compiler.toPhase(JavaSource.Phase.RESOLVED);
    CompilationUnitTree cu = compiler.getCompilationUnit();
    if (cu == null) {
        ErrorManager.getDefault().log(ErrorManager.ERROR, "compiler.getCompilationUnit() is null " + compiler); // NOI18N
        return;
    }
    FileObject file = compiler.getFileObject();
    FileObject folder = file.getParent();
    
    final String newName;
    if(folder.getFileObject(oldName, file.getExt()) != null) {
        newName = file.getName();
    } else {
        newName = oldName;
    }
    
    CopyTransformer findVisitor = new CopyTransformer(compiler, oldName, newName, insertImport, oldPackage);
    findVisitor.scan(compiler.getCompilationUnit(), null);
}
 
Example 12
private static TreePath pathFor(final Trees trees, final CompilationUnitTree cut, final int pos) {
    final TreePath[] result = new TreePath[1];

    new TreePathScanner<Void, Void>() {
        @Override public Void scan(Tree node, Void p) {
            if (   node != null
                && trees.getSourcePositions().getStartPosition(cut, node) <= pos
                && pos <= trees.getSourcePositions().getEndPosition(cut, node)) {
                result[0] = new TreePath(getCurrentPath(), node);
                return super.scan(node, p);
            }
            return null;
        }
    }.scan(cut, null);

    return result[0];
}
 
Example 13
Source Project: netbeans   Source File: WrappingTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testWrapMethod2() throws Exception {
    String code = "package hierbas.del.litoral;\n\n" +
        "import java.util.concurrent.atomic.AtomicBoolean;\n\n" +
        "public class Test {\n" +
        "}\n";
    runWrappingTest(code, new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            ExpressionTree parsed = workingCopy.getTreeUtilities().parseExpression("new Object() { private void test(int a, int b, int c) throws java.io.FileNotFoundException, java.net.MalformedURLException { } }", new SourcePositions[1]);
            parsed = GeneratorUtilities.get(workingCopy).importFQNs(parsed);
            MethodTree method = (MethodTree) ((NewClassTree) parsed).getClassBody().getMembers().get(0);
            workingCopy.rewrite(clazz, make.addClassMember(clazz, method));
        }
    },
    FmtOptions.wrapMethodParams, WrapStyle.WRAP_ALWAYS.name(),
    FmtOptions.wrapThrowsKeyword, WrapStyle.WRAP_ALWAYS.name(),
    FmtOptions.wrapThrowsList, WrapStyle.WRAP_ALWAYS.name());
}
 
Example 14
Source Project: netbeans   Source File: ImportFormatTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testRemoveLastImport() throws IOException, FileStateInvalidException {
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            List<ImportTree> imports = new ArrayList<ImportTree>(cut.getImports());
            imports.remove(1);
            CompilationUnitTree unit = make.CompilationUnit(
                    cut.getPackageName(),
                    imports,
                    cut.getTypeDecls(),
                    cut.getSourceFile()
            );
            workingCopy.rewrite(cut, unit);
        }
    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertFiles("testRemoveLastImport_ImportFormatTest.pass");
}
 
Example 15
Source Project: netbeans   Source File: CompilationInfo.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns tree which was reparsed by an incremental reparse.
 * When the source file wasn't parsed yet or the parse was a full parse
 * this method returns null.
 * <p class="nonnormative">
 * Currently the leaf tree is a MethodTree but this may change in the future.
 * Client of this method is responsible to check the corresponding TreeKind
 * to find out if it may perform on the changed subtree or it needs to
 * reprocess the whole tree.
 * </p>
 * @return {@link TreePath} or null
 * @since 0.31
 */
public @CheckForNull @CheckReturnValue TreePath getChangedTree () {
    checkConfinement();
    if (JavaSource.Phase.PARSED.compareTo (impl.getPhase())>0) {
        return null;
    }
    final Pair<DocPositionRegion,MethodTree> changedTree = impl.getChangedTree();
    if (changedTree == null) {
        return null;
    }
    final CompilationUnitTree cu = impl.getCompilationUnit();
    if (cu == null) {
        return null;
    }
    return TreePath.getPath(cu, changedTree.second());
}
 
Example 16
Source Project: buck   Source File: ValidatingTaskListener.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void finished(TaskEvent e) {
  TaskEvent.Kind kind = e.getKind();
  if (kind == TaskEvent.Kind.PARSE) {
    CompilationUnitTree compilationUnit = e.getCompilationUnit();
    compilationUnits.add(compilationUnit);
  } else if (kind == TaskEvent.Kind.ENTER) {
    enterDepth -= 1;
    // We wait until we've received all enter events so that the validation time shows up
    // separately from compiler enter time in the traces. We wait until after annotation
    // processing so we catch all the types.
    if (!annotationProcessing && enterDepth == 0 && !errorsExist.get()) {
      getValidator().validate(compilationUnits);
    }
  } else if (kind == TaskEvent.Kind.ANNOTATION_PROCESSING) {
    annotationProcessing = false;
  }
}
 
Example 17
private boolean testStatement(StringWriter writer, SourcePositions sp, String text, CompilationUnitTree cut, Tree statement) {
    if (statement == null) {
        return true;
    }
    int start = (int) sp.getStartPosition(cut, statement);
    int end = (int) sp.getEndPosition(cut, statement);
    char ch = text.charAt(end - 1);
    SourceCodeAnalysis.Completeness expected = COMPLETE;
    LineMap lineMap = cut.getLineMap();
    int row = (int) lineMap.getLineNumber(start);
    int column = (int) lineMap.getColumnNumber(start);
    switch (ch) {
        case ',':
        case ';':
            expected = (statement instanceof ExpressionStatementTree)
                    ? COMPLETE
                    : COMPLETE_WITH_SEMI;
            --end;
            break;
        case '}':
            break;
        default:
            writer.write(String.format("Unexpected end: row %d, column %d: '%c' -- %s\n",
                    row, column, ch, text.substring(start, end)));
            return true;
    }
    String unit = text.substring(start, end);
    SourceCodeAnalysis.CompletionInfo ci = getAnalysis().analyzeCompletion(unit);
    if (ci.completeness() != expected) {
        if (expected == COMPLETE_WITH_SEMI && (ci.completeness() == CONSIDERED_INCOMPLETE || ci.completeness() == EMPTY)) {
            writer.write(String.format("Empty statement: row %d, column %d: -- %s\n",
                    start, end, unit));
        } else {
            writer.write(String.format("Expected %s got %s: '%s'  row %d, column %d: -- %s\n",
                    expected, ci.completeness(), unit, row, column, unit));
            return false;
        }
    }
    return true;
}
 
Example 18
static JavaFileObject clearAnnotations(Trees trees, CompilationUnitTree cut)
        throws IOException {
    ClearAnnotations a = new ClearAnnotations(trees);
    a.scan(cut, null);
    Collections.sort(a.spans2Clear, (s1, s2) -> s2[0] - s1[0]);
    StringBuilder result = new StringBuilder(cut.getSourceFile().getCharContent(true));
    for (int[] toClear : a.spans2Clear) {
        result.delete(toClear[0], toClear[1]);
    }
    return new TestJavaFileObject(cut.getSourceFile().toUri(), result.toString());
}
 
Example 19
Source Project: netbeans   Source File: ImportsTest.java    License: Apache License 2.0 5 votes vote down vote up
public void test137771() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
        "import java.util.LinkedList;\n" +
        "import java.util.List;//tttt\n" +
        "/*asdf\n" +
        " */\n" +
        "/**\n" +
        " */\n" +
        "public class Test {\n" +
        "}\n"
        );
    String golden = 
        "import java.util.LinkedList;\n" +
        "/*asdf\n" +
        " */\n" +
        "/**\n" +
        " */\n" +
        "public class Test {\n" +
        "}\n";

    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            CompilationUnitTree node = workingCopy.getCompilationUnit();
            workingCopy.rewrite(node, make.removeCompUnitImport(node, 1));
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example 20
Source Project: netbeans   Source File: WebRefactoringFactory.java    License: Apache License 2.0 5 votes vote down vote up
private TreePathHandle resolveTreePathHandle(final AbstractRefactoring refactoring){
    
    TreePathHandle tph = refactoring.getRefactoringSource().lookup(TreePathHandle.class);
    if (tph != null) {
        return tph;
    }
    
    FileObject sourceFO = refactoring.getRefactoringSource().lookup(FileObject.class);
    if (sourceFO == null || !RefactoringUtil.isJavaFile(sourceFO)){
        return null;
    }
    final TreePathHandle[] result = new TreePathHandle[1];
    try{
        
        JavaSource source = JavaSource.forFileObject(sourceFO);
        
        source.runUserActionTask(new CancellableTask<CompilationController>() {
            public void cancel() {
            }
            public void run(CompilationController co) throws Exception {
                co.toPhase(JavaSource.Phase.RESOLVED);
                CompilationUnitTree cut = co.getCompilationUnit();
                if (cut.getTypeDecls().isEmpty()){
                    return;
                }
                result[0] = TreePathHandle.create(TreePath.getPath(cut, cut.getTypeDecls().get(0)), co);
            }
            
        }, true);
    }catch(IOException ioe){
        Exceptions.printStackTrace(ioe);
    }
    
    return result[0];
}
 
Example 21
@Test
void testErrorRecoveryForEnhancedForLoop142381() throws IOException {

    String code = "package test; class Test { " +
            "private void method() { " +
            "java.util.Set<String> s = null; for (a : s) {} } }";

    final List<Diagnostic<? extends JavaFileObject>> errors =
            new LinkedList<Diagnostic<? extends JavaFileObject>>();

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null,
            new DiagnosticListener<JavaFileObject>() {
        public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
            errors.add(diagnostic);
        }
    }, null, null, Arrays.asList(new MyFileObject(code)));

    CompilationUnitTree cut = ct.parse().iterator().next();

    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    StatementTree forStatement =
            ((MethodTree) clazz.getMembers().get(0)).getBody().getStatements().get(1);

    assertEquals("testErrorRecoveryForEnhancedForLoop142381",
            Kind.ENHANCED_FOR_LOOP, forStatement.getKind());
    assertFalse("testErrorRecoveryForEnhancedForLoop142381", errors.isEmpty());
}
 
Example 22
Source Project: openjdk-jdk9   Source File: JavacTrees.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override @DefinedBy(Api.COMPILER_TREE)
public DocCommentTree getDocCommentTree(TreePath path) {
    CompilationUnitTree t = path.getCompilationUnit();
    Tree leaf = path.getLeaf();
    if (t instanceof JCTree.JCCompilationUnit && leaf instanceof JCTree) {
        JCCompilationUnit cu = (JCCompilationUnit) t;
        if (cu.docComments != null) {
            return cu.docComments.getCommentTree((JCTree) leaf);
        }
    }
    return null;
}
 
Example 23
Source Project: openjdk-8-source   Source File: DocLint.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Void visitCompilationUnit(CompilationUnitTree tree, Void ignore) {
    if (tree.getPackageName() != null) {
        visitDecl(tree, null);
    }
    return super.visitCompilationUnit(tree, ignore);
}
 
Example 24
Source Project: annotation-tools   Source File: ASTPath.java    License: MIT License 5 votes vote down vote up
/**
 * Determine whether this {@code ASTPath} matches a given {@code TreePath}.
 */
public boolean matches(TreePath treePath) {
  CompilationUnitTree cut = treePath.getCompilationUnit();
  Tree leaf = treePath.getLeaf();
  ASTPath astPath = ASTIndex.indexOf(cut).get(leaf).astPath;  // FIXME
  return this.equals(astPath);
}
 
Example 25
public static void main(String... args) throws IOException {
    class MyFileObject extends SimpleJavaFileObject {
        MyFileObject() {
            super(URI.create("myfo:///Test.java"), SOURCE);
        }
        @Override
        public String getCharContent(boolean ignoreEncodingErrors) {
            //      0         1          2          3
            //      01234567890123456 7890 123456789012345
            return "@SuppressWarning(\"foo\") @Deprecated class Test { Test() { } }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    JavacTask task = (JavacTask)javac.getTask(null, null, null, null, null, compilationUnits);
    Trees trees = Trees.instance(task);
    CompilationUnitTree toplevel = task.parse().iterator().next();
    ClassTree classTree = (ClassTree)toplevel.getTypeDecls().get(0);
    List<? extends Tree> annotations = classTree.getModifiers().getAnnotations();
    Tree tree1 = annotations.get(0);
    Tree tree2 = annotations.get(1);
    long pos = trees.getSourcePositions().getStartPosition(toplevel, tree1);
    if (pos != 0)
        throw new AssertionError(String.format("Start pos for %s is incorrect (%s)!",
                                               tree1, pos));
    pos = trees.getSourcePositions().getEndPosition(toplevel, tree1);
    if (pos != 23)
        throw new AssertionError(String.format("End pos for %s is incorrect (%s)!",
                                               tree1, pos));
    pos = trees.getSourcePositions().getStartPosition(toplevel, tree2);
    if (pos != 24)
        throw new AssertionError(String.format("Start pos for %s is incorrect (%s)!",
                                               tree2, pos));
    pos = trees.getSourcePositions().getEndPosition(toplevel, tree2);
    if (pos != 35)
        throw new AssertionError(String.format("End pos for %s is incorrect (%s)!",
                                               tree2, pos));
}
 
Example 26
Source Project: netbeans   Source File: GeneratorUtilities.java    License: Apache License 2.0 5 votes vote down vote up
private Element getElementByFQN(CompilationUnitTree cut, String fqn) {
    Elements elements = copy.getElements();
    Element element = elements.getTypeElement(fqn);
    if (element == null)
        element = elements.getPackageElement(fqn);
    if (element == null)
        element = Symtab.instance(copy.impl.getJavacTask().getContext()).enterClass(
                Modules.instance(copy.impl.getJavacTask().getContext()).getDefaultModule(),
                (com.sun.tools.javac.util.Name)elements.getName(fqn));
    return element;
}
 
Example 27
Source Project: netbeans   Source File: CommanAndWhitespaceTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testNewClassToFactory() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public void taragui() {\n" +
        "        tests(Integer.MAX_VALUE, new Integer(1));\n" +
        "    }" +
        "    private void test(Integer i1, Integer i2) {}\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public void taragui() {\n" +
        "        tests(Integer.MAX_VALUE, Integer.valueOf(1));\n" +
        "    }" +
        "    private void test(Integer i1, Integer i2) {}\n" +
        "}\n";
    JavaSource src = getJavaSource(testFile);
    
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            MethodInvocationTree mit = (MethodInvocationTree) ((ExpressionStatementTree) method.getBody().getStatements().get(0)).getExpression();
            MethodInvocationTree valueOf = make.MethodInvocation(Collections.<ExpressionTree>emptyList(), make.MemberSelect(make.Identifier("Integer"), "valueOf"), Collections.singletonList(make.Literal(1)));
            workingCopy.rewrite(mit.getArguments().get(1), valueOf);
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example 28
Source Project: netbeans   Source File: ImportsTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testRemoveImportsNoEOL() throws Exception {
    testFile = new File(getWorkDir(), "MoveClass.java");
    TestUtilities.copyStringToFile(testFile,
            "package movepkg;"
            + " "
            + "import movepkg.*;"
            + " "
            + "public class MoveClass {"
            + "    "
            + "    public MoveClass() {"
            + "        super();"
            + "    }"
            + "}");
    String golden = "package movepkg;"
            + ""
            + "public class MoveClass {"
            + "    "
            + "    public MoveClass() {"
            + "        super();"
            + "    }"
            + "}";
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            CompilationUnitTree node = workingCopy.getCompilationUnit();
            CompilationUnitTree copy = make.CompilationUnit(node.getPackageAnnotations(), node.getPackageName(), new java.util.LinkedList<ImportTree>(), node.getTypeDecls(), node.getSourceFile());
            workingCopy.rewrite(node, copy);
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example 29
Source Project: netbeans   Source File: Utilities.java    License: Apache License 2.0 5 votes vote down vote up
public static int findLastBracket(final Tree tree, final CompilationUnitTree cu, final SourcePositions positions, final Document doc) {
    final int[] result = new int[1];
    
    doc.render(new Runnable() {
        public void run() {
            result[0] = findLastBracketImpl(tree, cu, positions, doc);
        }
    });
    
    return result[0];
}
 
Example 30
Source Project: annotation-tools   Source File: ASTIndex.java    License: MIT License 5 votes vote down vote up
public static String getParameterName(CompilationUnitTree cut,
    String className, String methodName, int index) {
  try {
    ASTIndex ai = (ASTIndex) ASTIndex.indexOf(cut);
    return ai.formals.get(className).get(methodName).get(index);
  } catch (NullPointerException ex) {
    return null;
  }
}