org.netbeans.api.java.source.JavaSource Java Examples

The following examples show how to use org.netbeans.api.java.source.JavaSource. 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
Source File: MethodElem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** "body" of this TestCase
 * @param o SourceElement - target for generating
 * @param log log is used for logging StackTraces
 * @throws Exception
 * @return true if test passed
 * false if failed
 */
public boolean go(Object o, java.io.PrintWriter log) throws Exception {
    
    //        org.openide.src.ClassElement clazz = ((org.openide.src.SourceElement) o).getClasses()[0];
    boolean passed = true;
    FileObject fo = (FileObject) o;
    JavaSource js = JavaSource.forFileObject(fo);
    
    Common.addMethod(js, "method1",Common.PARS1,"void", EnumSet.of(Modifier.PUBLIC,Modifier.STATIC));        
    Common.addMethod(js, "method1",Common.PARS2,"int", EnumSet.of(Modifier.PRIVATE,Modifier.SYNCHRONIZED));        
    Common.addMethod(js, "method1",Common.PARS3,"float", EnumSet.of(Modifier.PRIVATE,Modifier.FINAL));        
    Common.addMethod(js, "method2",Common.PARS1,"double", EnumSet.of(Modifier.PUBLIC,Modifier.STATIC));
    Common.addMethod(js, "method2",Common.PARS2,"boolean", EnumSet.of(Modifier.PUBLIC,Modifier.STATIC));        
    Common.addMethod(js, "method2",Common.PARS3,"void", EnumSet.of(Modifier.PUBLIC,Modifier.STATIC));
    
    return passed;
}
 
Example #2
Source File: ImportAnalysisTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testAddImport10() throws IOException {
    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 node = (MethodTree) clazz.getMembers().get(0);
            BlockTree body = node.getBody();
            List<StatementTree> stats = new ArrayList<StatementTree>();
            for (StatementTree st : body.getStatements()) {
                stats.add(st);
            }
            TypeElement list = workingCopy.getElements().getTypeElement("java.util.List");
            TypeElement awtList = workingCopy.getElements().getTypeElement("java.awt.List");
            stats.add(make.Variable(make.Modifiers(Collections.<Modifier>emptySet()), "list1", make.QualIdent(list), null));
            stats.add(make.Variable(make.Modifiers(Collections.<Modifier>emptySet()), "list2", make.QualIdent(awtList), null));
            workingCopy.rewrite(body, make.Block(stats, false));
        }
    };
    src.runModificationTask(task).commit();
    assertFiles("testAddImport10.pass");
}
 
Example #3
Source File: ImportAnalysisTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testDefaultPackage3() throws IOException {
    testFile = getFile(getSourceDir(), "ImportAnalysisDefaultPackage3.java");
    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 node = (MethodTree) clazz.getMembers().get(0);
            BlockTree body = node.getBody();
            List<StatementTree> stats = new ArrayList<StatementTree>();
            for (StatementTree st : body.getStatements()) {
                stats.add(st);
            }
            TypeElement exc = workingCopy.getElements().getTypeElement("ImportAnalysisDefaultPackage3A.B");
            stats.add(make.Variable(make.Modifiers(Collections.<Modifier>emptySet()), "s", make.QualIdent(exc), null));
            workingCopy.rewrite(body, make.Block(stats, false));
        }
    };
    src.runModificationTask(task).commit();
    assertFiles("testDefaultPackage3.pass");
}
 
Example #4
Source File: InnerToOutterTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void performInnerToOuterTest(String generateOuter, final int position, Problem... expectedProblems) throws Exception {
    final InnerToOuterRefactoring[] r = new InnerToOuterRefactoring[1];

    JavaSource.forFileObject(src.getFileObject("t/A.java")).runUserActionTask(new Task<CompilationController>() {

        @Override
        public void run(CompilationController parameter) throws Exception {
            parameter.toPhase(JavaSource.Phase.RESOLVED);
            TreePath tp = parameter.getTreeUtilities().pathFor(position);
            r[0] = new InnerToOuterRefactoring(TreePathHandle.create(tp, parameter));
        }
    }, true);

    r[0].setClassName("F");
    r[0].setReferenceName(generateOuter);

    RefactoringSession rs = RefactoringSession.create("Session");
    List<Problem> problems = new LinkedList<>();

    addAllProblems(problems, r[0].preCheck());
    addAllProblems(problems, r[0].prepare(rs));
    addAllProblems(problems, rs.doRefactoring(true));

    assertProblems(Arrays.asList(expectedProblems), problems);
}
 
Example #5
Source File: SpringRefactorings.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static RenamedClassName getRenamedClassName(final TreePathHandle oldHandle, final JavaSource javaSource, final String newName) throws IOException {
    final RenamedClassName[] result = { null };
    javaSource.runUserActionTask(new Task<CompilationController>() {
        public void run(CompilationController cc) throws IOException {
            cc.toPhase(Phase.RESOLVED);
            Element element = oldHandle.resolveElement(cc);
            if (element == null || element.getKind() != ElementKind.CLASS) {
                return;
            }
            String oldBinaryName = ElementUtilities.getBinaryName((TypeElement)element);
            String oldSimpleName = element.getSimpleName().toString();
            String newBinaryName = null;
            element = element.getEnclosingElement();
            if (element.getKind() == ElementKind.CLASS) {
                newBinaryName = ElementUtilities.getBinaryName((TypeElement)element) + '$' + newName;
            } else if (element.getKind() == ElementKind.PACKAGE) {
                String packageName = ((PackageElement)element).getQualifiedName().toString();
                newBinaryName = createQualifiedName(packageName, newName);
            } else {
                LOGGER.log(Level.WARNING, "Enclosing element of {0} was neither class nor package", oldHandle);
            }
            result[0] = new RenamedClassName(oldSimpleName, oldBinaryName, newBinaryName);
        }
    }, true);
    return result[0];
}
 
Example #6
Source File: BreakContinueTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void testHelper(String test, String golden, final Kind kind, final Delegate delegate) throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    final int index = test.indexOf("|");
    assertTrue(index != -1);
    TestUtilities.copyStringToFile(testFile, test.replace("|", ""));
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy copy) throws Exception {
            if (copy.toPhase(Phase.RESOLVED).compareTo(Phase.RESOLVED) < 0) {
                return;
            }
            TreePath node = copy.getTreeUtilities().pathFor(index);
            assertTrue(node.getLeaf().getKind() == kind);
            delegate.run(copy, node.getLeaf());
        }
    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    assertEquals(golden, res);
}
 
Example #7
Source File: Common.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static void setPackage(JavaSource js, final String pack) throws IOException {
    CancellableTask task = new CancellableTask<WorkingCopy>() {
        public void cancel() {
            throw new UnsupportedOperationException("Not supported yet.");
        }
        
        public void run(WorkingCopy workingCopy) throws Exception {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            CompilationUnitTree copy = make.CompilationUnit(make.Identifier(pack),cut.getImports(), cut.getTypeDecls(), cut.getSourceFile());
            workingCopy.rewrite(cut, copy);
        }
    };
    js.runModificationTask(task).commit();
}
 
Example #8
Source File: ImportAnalysisTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void test157566c() throws IOException {
    testFile = getFile(getSourceDir(), "org/netbeans/test/codegen/imports157566/b/Test.java");
    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);
            final TypeElement foo = workingCopy.getElements().getTypeElement("java.lang.Character");
            assertNotNull(foo);
            Tree type = make.QualIdent(foo);
            VariableTree vt = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "test", type, null);
            workingCopy.rewrite(clazz, make.addClassMember(clazz, vt));
        }
    };
    src.runModificationTask(task).commit();
    assertFiles("testImports157566c.pass");
}
 
Example #9
Source File: CallEjbCodeGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public List<? extends CodeGenerator> create(Lookup context) {
    ArrayList<CodeGenerator> ret = new ArrayList<CodeGenerator>();
    JTextComponent component = context.lookup(JTextComponent.class);
    CompilationController controller = context.lookup(CompilationController.class);
    TreePath path = context.lookup(TreePath.class);
    path = path != null ? SendEmailCodeGenerator.getPathElementOfKind(TreeUtilities.CLASS_TREE_KINDS, path) : null;
    if (component == null || controller == null || path == null)
        return ret;
    try {
        controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
        Element elem = controller.getTrees().getElement(path);
        if (elem != null) {
            CallEjbCodeGenerator gen = createCallEjbAction(component, controller, elem);
            if (gen != null)
                ret.add(gen);
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return ret;
}
 
Example #10
Source File: ImportAnalysisTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testAddImportThroughMethod3() throws IOException {
    JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws java.io.IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
            MethodTree node = (MethodTree) clazz.getMembers().get(0);
            int offset = (int) (workingCopy.getTrees().getSourcePositions().getStartPosition(workingCopy.getCompilationUnit(), node) + 1);
            TreePath context = workingCopy.getTreeUtilities().pathFor(offset);
            try {
                assertEquals("List", SourceUtils.resolveImport(workingCopy, context, "java.util.List"));
                assertEquals("Map", SourceUtils.resolveImport(workingCopy, context, "java.util.Map"));
                assertEquals("java.awt.List", SourceUtils.resolveImport(workingCopy, context, "java.awt.List"));
            } catch (IOException e) {
                throw new IllegalStateException(e);
            }
        }
    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertFiles("testAddImportThroughMethod3.pass");
}
 
Example #11
Source File: JavaSourceHelper.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static List<? extends AnnotationMirror> getClassAnnotations(JavaSource source) {
    final List<? extends AnnotationMirror>[] classAnons = new List[1];

    try {
        source.runUserActionTask(new AbstractTask<CompilationController>() {

            public void run(CompilationController controller) throws IOException {
                controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);

                TypeElement classElement = getTopLevelClassElement(controller);
                if (classElement == null) {
                    return;
                }

                classAnons[0] = controller.getElements().getAllAnnotationMirrors(classElement);
            }
        }, true);
    } catch (IOException ex) {
    }

    return classAnons[0];
}
 
Example #12
Source File: JavacParserTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void test199332() throws Exception {
    settings.commandLine = "-Xlint:serial";

    FileObject f2 = createFile("test/Test2.java", "package test; class Test2 implements Runnable, java.io.Serializable {}");
    JavaSource js = JavaSource.forFileObject(f2);

    SourceUtilsTestUtil.compileRecursively(sourceRoot);

    js.runUserActionTask(new Task<CompilationController>() {
        public void run(CompilationController parameter) throws Exception {
            assertTrue(Phase.RESOLVED.compareTo(parameter.toPhase(Phase.RESOLVED)) <= 0);
            assertEquals(parameter.getDiagnostics().toString(), 2, parameter.getDiagnostics().size());

            Set<String> codes = new HashSet<String>();

            for (Diagnostic d : parameter.getDiagnostics()) {
                codes.add(d.getCode());
            }

            assertEquals(new HashSet<String>(Arrays.asList("compiler.warn.missing.SVUID", "compiler.err.does.not.override.abstract")), codes);
        }
    }, true);
    
    settings.commandLine = null;
}
 
Example #13
Source File: JavaHintsPositionRefresher.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void run(CompilationController controller) throws Exception {
    if (controller.toPhase(JavaSource.Phase.RESOLVED).compareTo(Phase.RESOLVED) < 0) {
        return ;
    }

    Document doc = controller.getDocument();

    if (doc == null) {
        return;
    }

    for (PositionRefresherHelper h : refreshers) {
        if (ctx.isCanceled()) {
            return;
        }
        
        List errors = h.getErrorDescriptionsAt(controller, ctx, doc);
        
        if (errors == null) continue;
        
        eds.put(h.getKey(), errors);
    }
}
 
Example #14
Source File: AnnotationOnLocVarTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testAddAnnToLocVar() throws IOException {
    System.err.println("testAddAnnToLocVar");
    JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws java.io.IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(0);
            BlockTree body = method.getBody();
            List<? extends StatementTree> statements = body.getStatements();
            VariableTree statement = (VariableTree) statements.get(1);
            // mods will be replaced by a new one
            ModifiersTree mods = statement.getModifiers();
            List<AnnotationTree> anns = new ArrayList<AnnotationTree>(1);
            List<AssignmentTree> attribs = new ArrayList<AssignmentTree>(4);
            attribs.add(make.Assignment(make.Identifier("id"), make.Literal(Integer.valueOf(666))));
            attribs.add(make.Assignment(make.Identifier("synopsis"), make.Literal("fat")));
            attribs.add(make.Assignment(make.Identifier("engineer"), make.Literal("PaF")));
            attribs.add(make.Assignment(make.Identifier("date"), make.Literal("2005")));
            anns.add(make.Annotation(make.Identifier("AnnotationType"), attribs));
            workingCopy.rewrite(mods, make.Modifiers(mods.getFlags(), anns));
        }
    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    File g = getFile(getGoldenDir(), getGoldenPckg() + "testAddAnnToLocVar_AnnotationOnLocVarTest.pass");
    String gold = TestUtilities.copyFileToString(g);
    assertEquals(res, gold);
}
 
Example #15
Source File: AnnotationTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testFirstAnnotationWithImport() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    String code = "package hierbas.del.litoral;\n" +
                  "\n" +
                  "public class Test {\n" +
                  "}\n";
    String golden =
        "package hierbas.del.litoral;\n" +
        "\n" +
        "import java.lang.annotation.Retention;\n" +
        "\n" +
        "@Retention\n" +
        "public class Test {\n" +
        "}\n";

    TestUtilities.copyStringToFile(testFile, code);

    JavaSource src = getJavaSource(testFile);
    Task task = new Task<WorkingCopy>() {
        public void run(final WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);

            ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
            ModifiersTree mods = clazz.getModifiers();
            TreeMaker make = workingCopy.getTreeMaker();
            workingCopy.rewrite(mods,
                                make.addModifiersAnnotation(mods,
                                                            make.Annotation(make.Type("java.lang.annotation.Retention"),
                                                                            Collections.<ExpressionTree>emptyList())));
        }
    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example #16
Source File: ClassPathProviderImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void registerClassPaths() {
    GlobalPathRegistry.getDefault().register(ClassPath.BOOT, new ClassPath[] {bootCP});
    GlobalPathRegistry.getDefault().register(ClassPath.COMPILE, new ClassPath[] {compileCP});
    GlobalPathRegistry.getDefault().register(ClassPath.SOURCE, new ClassPath[] {sourceCP});
    if (REGISTER_TESTS_AS_JAVA)
        GlobalPathRegistry.getDefault().register(ClassPath.SOURCE, new ClassPath[] {testsRegCP});
    GlobalPathRegistry.getDefault().register(TEST_SOURCE, new ClassPath[] {testsRegCP});
    try {
        JavaSource.create(ClasspathInfo.create(ClassPath.EMPTY, testsCompileCP, ClassPath.EMPTY))
                  .runWhenScanFinished(cc -> initialScanDone.set(true), true);
    } catch (IOException ex) {
        Logger.getLogger(ClassPathProviderImpl.class.getName())
              .log(Level.FINE, null, ex);
    }
}
 
Example #17
Source File: JavaSourceHelper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static void getAvailableFieldSignature(JavaSource source,
        Map<String, String> map) {
    List<VariableTree> fields = getAllFields(source);
    for (VariableTree v : fields) {
        map.put(createFieldSignature(v), v.getName().toString());
    }
}
 
Example #18
Source File: LocationOpener.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private int getMethodLine(final FileObject fo, final String methodName) {
    final int[] line = new int[1];
    JavaSource javaSource = JavaSource.forFileObject(fo);
    if (javaSource != null) {
        try {
            javaSource.runUserActionTask((CompilationController compilationController) -> {
                compilationController.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                Trees trees = compilationController.getTrees();
                CompilationUnitTree compilationUnitTree = compilationController.getCompilationUnit();
                List<? extends Tree> typeDecls = compilationUnitTree.getTypeDecls();
                for (Tree tree : typeDecls) {
                    Element element = trees.getElement(trees.getPath(compilationUnitTree, tree));
                    if (element != null && element.getKind() == ElementKind.CLASS && element.getSimpleName().contentEquals(fo.getName())) {
                        List<? extends ExecutableElement> methodElements = ElementFilter.methodsIn(element.getEnclosedElements());
                        for (Element child : methodElements) {
                            if (child.getSimpleName().contentEquals(methodName)) {
                                long pos = trees.getSourcePositions().getStartPosition(compilationUnitTree, trees.getTree(child));
                                line[0] = (int) compilationUnitTree.getLineMap().getLineNumber(pos);
                                break;
                            }
                        }
                    }
                }
            }, true);
            return line[0];
        } catch (IOException ioe) {
            //TODO: Do nothing?
        }
    }
    return 1;
}
 
Example #19
Source File: BodyStatementTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void test182542() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
        "package personal;\n" +
        "\n" +
        "public class Test {\n" +
        "    public void m() { System.err.println(); }\n" +
        "}\n");

     String golden =
        "package personal;\n" +
        "\n" +
        "public class Test {\n" +
        "    public void m() {}\n" +
        "}\n";

    JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws java.io.IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            BlockTree block = method.getBody();
            workingCopy.rewrite(block, make.removeBlockStatement(block, 0));
        }

    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example #20
Source File: LambdaTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testOnlyLambdaParam() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public static void taragui() {\n" +
        "        ChangeListener l = (e) -> {};\n" + 
        "    }\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public static void taragui() {\n" +
        "        ChangeListener l = () -> {};\n" + 
        "    }\n" +
        "}\n";
    JavaSource src = getJavaSource(testFile);
    
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(final WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            final TreeMaker make = workingCopy.getTreeMaker();
            new ErrorAwareTreeScanner<Void, Void>() {
                @Override public Void visitLambdaExpression(LambdaExpressionTree node, Void p) {
                    workingCopy.rewrite(node, make.removeLambdaParameter(node, 0));
                    return super.visitLambdaExpression(node, p);
                }
            }.scan(workingCopy.getCompilationUnit(), null);
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
 
Example #21
Source File: AnnotationTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testAnnotation187551a() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
        "\n" +
        "@interface Test {\n" +
        "}\n"
        );
    String golden =
        "\n" +
        "@interface Foo {\n" +
        "}\n";

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

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();

            for (Tree typeDecl : cut.getTypeDecls()) {
                // ensure that it is correct type declaration, i.e. class
                if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDecl.getKind())) {
                    ClassTree clazz = (ClassTree) typeDecl;
                    ClassTree copy = make.AnnotationType(clazz.getModifiers(), "Foo", clazz.getMembers());
                    workingCopy.rewrite(typeDecl, copy);
                }
            }
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example #22
Source File: Utils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static void showMethod(FileObject source, String methodName) {
    try {
        DataObject dataObj = DataObject.find(source);          
        JavaSource javaSource = JavaSource.forFileObject(source);
        
        // Force a save to make sure to make sure the line position in
        // the editor is in sync with the java source.
        SaveCookie sc = (SaveCookie) dataObj.getCookie(SaveCookie.class);
 
        if (sc != null) {
            sc.save();
        }
        
        LineCookie lc = (LineCookie) dataObj.getCookie(LineCookie.class);
        
        if (lc != null) {
            final long[] position = JavaSourceHelper.getPosition(javaSource, methodName);
            final Line line = lc.getLineSet().getOriginal((int) position[0]);
            
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    line.show(ShowOpenType.OPEN, ShowVisibilityType.NONE, (int) position[1]);
                }
            });
        }
    } catch (Exception de) {
        Exceptions.printStackTrace(de);
    }    
}
 
Example #23
Source File: JavaSourceHelper.java    From jeddict with Apache License 2.0 5 votes vote down vote up
public static String getClassNameQuietly(JavaSource source) {
    try {
        return getClassName(source);
    } catch (IOException ioe) {
        Logger.getLogger(JavaSourceHelper.class.getName()).log(Level.WARNING, ioe.getLocalizedMessage());
    }
    return null;
}
 
Example #24
Source File: IfTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void test158154OneIf() throws Exception {
    String source = "class Test {\n"
            + "    void m1(boolean b) {\n"
            + "        if (b) ; else System.out.println(\"hi\");\n"
            + "    }\n"
            + "}";
    String golden = "class Test {\n"
            + "    void m1(boolean b) {\n"
            + "        if (!(b)) System.out.println(\"hi\");\n"
            + "    }\n"
            + "}";
    testFile = new File(getWorkDir(), "Test.java");

    TestUtilities.copyStringToFile(testFile, source);
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {
        public void run(WorkingCopy copy) throws Exception {
            if (copy.toPhase(Phase.RESOLVED).compareTo(Phase.RESOLVED) < 0) {
                return;
            }

            TreeMaker make = copy.getTreeMaker();
            ClassTree clazz = (ClassTree) copy.getCompilationUnit().getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            BlockTree block = method.getBody();
            IfTree original = (IfTree) block.getStatements().get(0);

            IfTree modified = make.If(
                    make.Parenthesized(
                    make.Unary(Kind.LOGICAL_COMPLEMENT, original.getCondition())),
                    original.getElseStatement(), null);
            copy.rewrite(original, modified);
        }
    };

    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.out.println(res);
    assertEquals(golden, res);
}
 
Example #25
Source File: ConstructorTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testAddConstructor2() throws IOException {
    testFile = getFile(getSourceDir(), getSourcePckg() + "ConstructorTest2.java");

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

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            // exactly one class in compilation unit
            ClassTree topLevel = (ClassTree) cut.getTypeDecls().iterator().next();

            ModifiersTree mods = make.Modifiers(EnumSet.of(Modifier.PUBLIC));
            List<VariableTree> arguments = new ArrayList<VariableTree>();
            arguments.add(make.Variable(
                    make.Modifiers(EnumSet.noneOf(Modifier.class)),
                    "a",
                    make.PrimitiveType(TypeKind.BOOLEAN), null)
            );
            MethodTree newConstructor = make.Constructor(
                    mods,
                    Collections.<TypeParameterTree>emptyList(),
                    arguments,
                    Collections.<ExpressionTree>emptyList(),
                    make.Block(Collections.<StatementTree>emptyList(), false)
            );

            ClassTree newClass = make.addClassMember(topLevel, newConstructor);
            workingCopy.rewrite(topLevel, newClass);
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertFiles("testAddConstructor2.pass");
}
 
Example #26
Source File: JavaUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public MethodFinder(JavaSource javaSource, String classBinName, String methodName, int argCount, Public publicFlag, Static staticFlag) {
    super(javaSource);
    this.classBinName = classBinName;
    this.methodName = methodName;
    this.argCount = argCount;
    this.publicFlag = publicFlag;
    this.staticFlag = staticFlag;
}
 
Example #27
Source File: ShowMembersAtCaretAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private JavaSource getContext(JTextComponent target) {
    final Document doc = Utilities.getDocument(target);
    if (doc == null) {
        return null;
    }
    return JavaSource.forDocument(doc);
}
 
Example #28
Source File: ClassDialog.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean isWantedClass(final JavaSource js) {
    if (extendingClass == null) {
        return true;
    }
    final Boolean[] subType = new Boolean[1];
    subType[0] = false;
    ScanDialog.runWhenScanFinished( new Runnable() {
        
        @Override
        public void run() {
            try {
                js.runUserActionTask(new AbstractTask<CompilationController>() {
                    @Override
                     public void run(CompilationController controller) throws java.io.IOException {
                         controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                         SourceUtils sourceUtils = SourceUtils.newInstance(controller);
                         subType[0] = Boolean.valueOf(sourceUtils.isSubtype(extendingClass));
                     }
                 }, true);
            } catch (Throwable t) { // we don't care about anything else happening here - either the file is recognize, or not
                Logger.global.log(Level.INFO, t.getMessage());
            }                    
        }
    }, NbBundle.getMessage(ClassDialog.class, "LBL_AnalyzeClass"));     // NOI18N
    
    return subType[0];
}
 
Example #29
Source File: LambdaTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testMethodReferenceFirstTypeParam() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public static void taragui() {\n" +
        "        Runnable r = Test::taragui;\n" + 
        "    }\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public static void taragui() {\n" +
        "        Runnable r = Test::<String>taragui;\n" + 
        "    }\n" +
        "}\n";
    JavaSource src = getJavaSource(testFile);
    
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(final WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            final TreeMaker make = workingCopy.getTreeMaker();
            new ErrorAwareTreeScanner<Void, Void>() {
                @Override public Void visitMemberReference(MemberReferenceTree node, Void p) {
                    workingCopy.rewrite(node, make.MemberReference(node.getMode(), node.getQualifierExpression(), node.getName(), Collections.singletonList(make.Identifier("String"))));
                    return super.visitMemberReference(node, p);
                }
            }.scan(workingCopy.getCompilationUnit(), null);
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
 
Example #30
Source File: ImportsTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testRemoveAllInDefault() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
        "import java.util.List;\n" +
        "import java.util.ArrayList;\n" +
        "import java.util.Collections;\n" +
        "\n" +
        "public class Test {\n" +
        "    public void taragui() {\n" +
        "    }\n" +
        "}\n");
    String golden =
        "\n" +
        "public class Test {\n" +
        "    public void taragui() {\n" +
        "    }\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 cut = workingCopy.getCompilationUnit();
            CompilationUnitTree copy = make.removeCompUnitImport(cut, 0);
            copy = make.removeCompUnitImport(copy, 0);
            copy = make.removeCompUnitImport(copy, 0);
            workingCopy.rewrite(cut, copy);
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}