Java Code Examples for org.netbeans.api.java.source.JavaSource#create()

The following examples show how to use org.netbeans.api.java.source.JavaSource#create() . 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: JSFRefactoringUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static Element resolveElement(final ClasspathInfo cpInfo, final AbstractRefactoring refactoring, final TreePathHandle treePathHandle) {
    final Element[] element = new Element[1];
    JavaSource source = JavaSource.create(cpInfo, new FileObject[]{treePathHandle.getFileObject()});
    try {
        source.runUserActionTask(new Task<CompilationController>() {

            @Override
            public void run(CompilationController info) throws Exception {
                info.toPhase(JavaSource.Phase.RESOLVED);
                element[0] = treePathHandle.resolveElement(info);
            }
        }, true);
    } catch (IOException exception) {
        LOGGER.log(Level.WARNING, "Exception by refactoring:", exception); //NOI18NN
    }

    return element[0];
}
 
Example 2
Source File: Utils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static JavaSource getJavaSource(Document doc) {
    FileObject fileObject = NbEditorUtilities.getFileObject(doc);
    if (fileObject == null) {
        return null;
    }
    Project project = FileOwnerQuery.getOwner(fileObject);
    if (project == null) {
        return null;
    }
    // XXX this only works correctly with projects with a single sourcepath,
    // but we don't plan to support another kind of projects anyway (what about Maven?).
    // mkleint: Maven has just one sourceroot for java sources, the config files are placed under
    // different source root though. JavaProjectConstants.SOURCES_TYPE_RESOURCES
    SourceGroup[] sourceGroups = ProjectUtils.getSources(project).getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
    for (SourceGroup sourceGroup : sourceGroups) {
        return JavaSource.create(ClasspathInfo.create(sourceGroup.getRootFolder()));
    }
    return null;
}
 
Example 3
Source File: J2SEActionProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@NonNull
private static JavaSource createSource() {
    final ClasspathInfo cpInfo = ClasspathInfo.create(
            ClassPath.EMPTY,
            ClassPath.EMPTY,
            ClassPath.EMPTY);
    final JavaSource js = JavaSource.create(cpInfo);
    return js;
}
 
Example 4
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Wait until scanning is finished.
 *
 * @param projectDir File pointing to project root or root of several
 * projects
 * @throws java.lang.Exception
 */
public static void waitScanningFinished(File projectDir) throws Exception {
    JavaSource src = JavaSource.create(ClasspathInfo.create(projectDir));
    src.runWhenScanFinished(new Task<CompilationController>() {

        @Override()
        public void run(CompilationController controller) throws Exception {
            controller.toPhase(JavaSource.Phase.RESOLVED);
        }
    }, false).get();
}
 
Example 5
Source File: CodeGeneratorTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void performFromClassTest(String test, final String golden) throws Exception {
    clearWorkDir();
    beginTx();
    FileObject wd = FileUtil.toFileObject(getWorkDir());

    assertNotNull(wd);

    FileObject src   = FileUtil.createFolder(wd, "src");
    FileObject build = FileUtil.createFolder(wd, "build");
    FileObject cache = FileUtil.createFolder(wd, "cache");

    SourceUtilsTestUtil.prepareTest(src, build, cache);
    FileObject testFile = FileUtil.createData(src, "test/Test.java");
    TestUtilities.copyStringToFile(testFile, test);
    SourceUtilsTestUtil.compileRecursively(src);
    final FileObject testOutFile = FileUtil.createData(src, "out/Test.java");
    final ClasspathInfo cpInfo = ClasspathInfoAccessor.getINSTANCE().create(testOutFile, null, true, true, false, true);
    JavaSource testSource = JavaSource.create(cpInfo, testOutFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {
        @Override
        public void run(final WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);

            TypeElement t = workingCopy.getElements().getTypeElement("test.Test");

            assertNotNull(t);

            workingCopy.rewrite(workingCopy.getCompilationUnit(), CodeGenerator.generateCode(workingCopy, t));
        }
    };

    ModificationResult mr = testSource.runModificationTask(task);

    mr.commit();

    assertEquals(normalizeWhitespaces(golden), normalizeWhitespaces(TestUtilities.copyFileToString(FileUtil.toFile(testOutFile))));
}
 
Example 6
Source File: JavacParserTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testMultiSource() throws Exception {
    FileObject f1 = createFile("test/Test1.java", "package test; class Test1");
    FileObject f2 = createFile("test/Test2.java", "package test; class Test2{}");
    FileObject f3 = createFile("test/Test3.java", "package test; class Test3{}");

    ClasspathInfo cpInfo = ClasspathInfo.create(f2);
    JavaSource js = JavaSource.create(cpInfo, f2, f3);

    SourceUtilsTestUtil.compileRecursively(sourceRoot);

    js.runUserActionTask(new Task<CompilationController>() {
        TypeElement storedJLObject;
        public void run(CompilationController parameter) throws Exception {
            if ("Test3".equals(parameter.getFileObject().getName())) {
                TypeElement te = parameter.getElements().getTypeElement("test.Test1");
                assertNotNull(te);
                assertNotNull(parameter.getTrees().getPath(te));
            }
            assertEquals(Phase.PARSED, parameter.toPhase(Phase.PARSED));
            assertNotNull(parameter.getCompilationUnit());
            TypeElement jlObject = parameter.getElements().getTypeElement("java.lang.Object");

            if (storedJLObject == null) {
                storedJLObject = jlObject;
            } else {
                assertEquals(storedJLObject, jlObject);
            }
        }
    }, true);
}
 
Example 7
Source File: ComponentMethodModel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void removeListeners() {
    try {
        JavaSource javaSource = JavaSource.create(cpInfo);
        javaSource.runUserActionTask(new Task<CompilationController>() {
            @Override
            public void run(CompilationController controller) throws IOException {
                controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                ClassIndex classIndex = controller.getClasspathInfo().getClassIndex();
                classIndex.removeClassIndexListener(classIndexListener);
            }
        }, true);
    } catch (IOException ioe) {
        Exceptions.printStackTrace(ioe);
    }
}
 
Example 8
Source File: CompilationUnitTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void test157760b() throws Exception {
    testFile = new File(getWorkDir(), "package-info.java");
    TestUtilities.copyStringToFile(testFile, "@AA\n@BB\n@CC\npackage foo;");

    FileObject testSourceFO = FileUtil.toFileObject(testFile);
    assertNotNull(testSourceFO);
    ClassPath sourcePath = ClassPath.getClassPath(testSourceFO, ClassPath.SOURCE);
    assertNotNull(sourcePath);
    FileObject[] roots = sourcePath.getRoots();
    assertEquals(1, roots.length);
    final FileObject sourceRoot = roots[0];
    assertNotNull(sourceRoot);
    ClassPath compilePath = ClassPath.getClassPath(testSourceFO, ClassPath.COMPILE);
    assertNotNull(compilePath);
    ClassPath bootPath = ClassPath.getClassPath(testSourceFO, ClassPath.BOOT);
    assertNotNull(bootPath);
    ClasspathInfo cpInfo = ClasspathInfo.create(bootPath, compilePath, sourcePath);

    String golden = "@EE\n@CC\n@DD\npackage foo;";

    JavaSource javaSource = JavaSource.create(cpInfo, FileUtil.toFileObject(testFile));

    Task<WorkingCopy> task = new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws Exception {
            workingCopy.toPhase(JavaSource.Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            CompilationUnitTree nue = make.addPackageAnnotation(workingCopy.getCompilationUnit(), make.Annotation(make.Identifier("DD"), Collections.<ExpressionTree>emptyList()));
            nue = make.insertPackageAnnotation(nue, 0, make.Annotation(make.Identifier("EE"), Collections.<ExpressionTree>emptyList()));
            nue = make.removePackageAnnotation(nue, 1);
            nue = make.removePackageAnnotation(nue, workingCopy.getCompilationUnit().getPackageAnnotations().get(1));
            workingCopy.rewrite(workingCopy.getCompilationUnit(), nue);
        }
    };
    ModificationResult result = javaSource.runModificationTask(task);
    result.commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example 9
Source File: CreateClassFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public ChangeInfo implement() throws Exception {
    //use the original cp-info so it is "sure" that the target can be resolved:
    JavaSource js = JavaSource.create(cpInfo, targetFile);
    
    ModificationResult diff = js.runModificationTask(new Task<WorkingCopy>() {

        public void run(final WorkingCopy working) throws IOException {
            working.toPhase(Phase.RESOLVED);
            TypeElement targetType = target.resolve(working);
            
            if (targetType == null) {
                ErrorHintsProvider.LOG.log(Level.INFO, "Cannot resolve target."); // NOI18N
                return;
            }
            
            TreePath targetTree = working.getTrees().getPath(targetType);
            
            if (targetTree == null) {
                ErrorHintsProvider.LOG.log(Level.INFO, "Cannot resolve target tree: " + targetType.getQualifiedName() + "."); // NOI18N
                return;
            }
            
            TreeMaker make = working.getTreeMaker();
            MethodTree constr = make.Method(make.Modifiers(EnumSet.of(Modifier.PUBLIC)), "<init>", null, Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), "{}" /*XXX*/, null); // NOI18N
            ClassTree innerClass = make.Class(make.Modifiers(modifiers), name, Collections.<TypeParameterTree>emptyList(), null, Collections.<Tree>emptyList(), Collections.<Tree>singletonList(constr));
            
            innerClass = createConstructor(working, new TreePath(targetTree, innerClass));
            
            working.rewrite(targetTree.getLeaf(), GeneratorUtilities.get(working).insertClassMember((ClassTree)targetTree.getLeaf(), innerClass));
        }
    });
    
    return Utilities.commitAndComputeChangeInfo(targetFile, diff, null);
}
 
Example 10
Source File: JPQLInternalEditorCodeCompletionProvider.java    From jeddict with Apache License 2.0 4 votes vote down vote up
@Override
        protected void query(CompletionResultSet resultSet, Document doc, int caretOffset) {
            {
                try {
                    this.caretOffset = caretOffset;
                    {
                        results = null;
                        anchorOffset = -1;
                        Source source = Source.create(doc);
                        PUDataObject puObject;
                        JavaSource js;
                        if (source != null) {
                            ModelerPanel tc = (ModelerPanel) SwingUtilities.getAncestorOfClass(ModelerPanel.class, component);
//                            puObject = tc.getDataObject();
                             final Project project = tc.getModelerFile().getProject();//FileOwnerQuery.getOwner(pXml);
                             puObject = ProviderUtil.getPUDataObject(project);
                            final FileObject pXml = puObject.getPrimaryFile();
                            if (project == null) {
                                return;
                            }
                            // XXX this only works correctly with projects with a single sourcepath,
                            // but we don't plan to support another kind of projects anyway (what about Maven?).
                            // mkleint: Maven has just one sourceroot for java sources, the config files are placed under
                            // different source root though. JavaProjectConstants.SOURCES_TYPE_RESOURCES
                            SourceGroup[] sourceGroups = ProjectUtils.getSources(project).getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
                            js = JavaSource.create(ClasspathInfo.create(sourceGroups[0].getRootFolder()));

                            js.runUserActionTask((CompilationController parameter) -> {
                                JPACodeCompletionQuery.this.run(parameter, project, pXml);
                            }, false);
                            if ((queryType & COMPLETION_QUERY_TYPE) != 0) {
                                if (results != null) {
                                    resultSet.addAllItems(results);
                                }
                                resultSet.setHasAdditionalItems(hasAdditionalItems > 0);
                                if (hasAdditionalItems == 1) {
                                    resultSet.setHasAdditionalItemsText(NbBundle.getMessage(JPQLInternalEditorCodeCompletionProvider.class, "JCP-imported-items")); //NOI18N
                                }
                                if (hasAdditionalItems == 2) {
                                    resultSet.setHasAdditionalItemsText(NbBundle.getMessage(JPQLInternalEditorCodeCompletionProvider.class, "JCP-instance-members")); //NOI18N
                                }
                            }
                            if (anchorOffset > -1) {
                                resultSet.setAnchorOffset(anchorOffset);
                            }
                        }
                    }
                } catch (Exception e) {
                    Exceptions.printStackTrace(e);
                } finally {
                    resultSet.finish();
                }
            }

        }
 
Example 11
Source File: SourceGroupSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static FileObject getFileObjectFromClassName(String qualifiedClassName, 
        Project project) throws IOException 
{
    final ElementHandle<TypeElement> handle = getHandleClassName(qualifiedClassName,
            project);
    if ( handle == null ){
        return null;
    }
    ClassPathProvider provider = project.getLookup().lookup( 
            ClassPathProvider.class);
    FileObject root = MiscUtilities.findSourceRoot(project);
    ClassPath sourceCp = provider.findClassPath(root, ClassPath.SOURCE);
    final ClassPath compileCp = provider.findClassPath(root, ClassPath.COMPILE);
    ClassPath bootCp = provider.findClassPath(root, ClassPath.BOOT);
    ClasspathInfo cpInfo = ClasspathInfo.create(bootCp, compileCp, sourceCp);
    if (qualifiedClassName.equals(handle.getQualifiedName())) {
        FileObject fo = SourceUtils.getFile(handle, cpInfo);
        if (fo != null) {
            return fo;
        }
        JavaSource javaSource  = JavaSource.create(cpInfo);
        final FileObject classFo[] = new FileObject[1];
        javaSource.runUserActionTask(new Task<CompilationController>() {

            @Override
            public void run( CompilationController controller )
                    throws Exception
            {
                TypeElement element = handle.resolve(controller);
                if (element == null) {
                    return;
                }
                PackageElement pack = controller.getElements()
                        .getPackageOf(element);
                if (pack == null) {
                    return;
                }
                String packageName = pack.getQualifiedName().toString();
                String fqn = ElementUtilities.getBinaryName(element);
                String className = fqn.substring(packageName.length());
                if (className.length() > 0 && className.charAt(0) == '.') {
                    className = className.substring(1);
                }
                else {
                    return;
                }
                int dotIndex = className.indexOf('.');
                if (dotIndex != -1) {
                    className = className.substring(0, dotIndex);
                }

                String path = packageName.replace('.', '/') + '/'
                        + className + ".class"; // NOI18N
                classFo[0] = compileCp.findResource(path);
            }

        }, true);
        return classFo[0];
    }
    return null;
}
 
Example 12
Source File: ELCodeCompletionHandler.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public CodeCompletionResult complete(final CodeCompletionContext context) {
    final List<CompletionProposal> proposals = new ArrayList<>(50);
    CodeCompletionResult result = new DefaultCompletionResult(proposals, false);
    final ELElement element = getElementAt(context.getParserResult(), context.getCaretOffset());
    if (element == null || !element.isValid()) {
        return CodeCompletionResult.NONE;
    }
    final Node target = getTargetNode(element, context.getCaretOffset());
    if(target == null) {
        //completion called outside of the EL content, resp. inside the
        //delimiters #{ or } area
        return CodeCompletionResult.NONE;
    }
    AstPath path = new AstPath(element.getNode());
    final List<Node> rootToNode = path.rootToNode(target);
    if (rootToNode.isEmpty()) {
        return result;
    }
    final PrefixMatcher prefixMatcher = PrefixMatcher.create(target, context);
    if (prefixMatcher == null) {
        return CodeCompletionResult.NONE;
    }
    // see if it is bundle key in the array notation and if so complete them
    if (target instanceof AstString) {
        ResourceBundles bundle = ResourceBundles.get(getFileObject(context));
        String bundleIdentifier = bundle.findResourceBundleIdentifier(path);
        if (bundleIdentifier != null) {
            proposeBundleKeysInArrayNotation(context, prefixMatcher, element, bundleIdentifier, (AstString) target, proposals);
            return proposals.isEmpty() ? CodeCompletionResult.NONE : result;
        }
    }

    final Node nodeToResolve = getNodeToResolve(target, rootToNode);
    final Map<AstIdentifier, Node> assignments = getAssignments(context.getParserResult(), context.getCaretOffset());
    final FileObject file = context.getParserResult().getSnapshot().getSource().getFileObject();
    JavaSource jsource = JavaSource.create(ELTypeUtilities.getElimplExtendedCPI(file));
    try {
        jsource.runUserActionTask(new Task<CompilationController>() {

            @Override
            public void run(CompilationController info) throws Exception {
                info.toPhase(JavaSource.Phase.RESOLVED);
                CompilationContext ccontext = CompilationContext.create(file, info);

                // assignments to resolve
                Node node = nodeToResolve instanceof AstIdentifier && assignments.containsKey((AstIdentifier) nodeToResolve) ?
                        assignments.get((AstIdentifier) nodeToResolve) : nodeToResolve;

                // fetch information from the JSF editor for resolving beans if necessary for cc:interface elements
                List<VariableInfo> attrsObjects = Collections.<VariableInfo>emptyList();
                if (ELTypeUtilities.isRawObjectReference(ccontext, node, false)) {
                    attrsObjects = ELVariableResolvers.getRawObjectProperties(ccontext, "attrs", context.getParserResult().getSnapshot()); //NOI18N
                }

                Element resolved = null;
                if (!isInLambda(rootToNode)) {
                    // resolve the element
                    resolved = ELTypeUtilities.resolveElement(ccontext, element, nodeToResolve, assignments, attrsObjects);
                }

                if (ELTypeUtilities.isStaticIterableElement(ccontext, node)) {
                    proposeStream(ccontext, context, prefixMatcher, proposals);
                } else if (ELTypeUtilities.isRawObjectReference(ccontext, node, true)) {
                    proposeRawObjectProperties(ccontext, context, prefixMatcher, node, proposals);
                } else if (ELTypeUtilities.isScopeObject(ccontext, node)) {
                    // seems to be something like "sessionScope.^", so complete beans from the scope
                    proposeBeansFromScope(ccontext, context, prefixMatcher, element, node, proposals);
                } else if (ELTypeUtilities.isResourceBundleVar(ccontext, node)) {
                    proposeBundleKeysInDotNotation(context, prefixMatcher, element, node, proposals);
                } else if (resolved == null) {
                    if (target instanceof AstDotSuffix == false && node instanceof AstFunction == false) {
                        proposeFunctions(ccontext, context, prefixMatcher, element, proposals);
                        proposeManagedBeans(ccontext, context, prefixMatcher, element, proposals);
                        proposeBundles(ccontext, context, prefixMatcher, element, proposals);
                        proposeVariables(ccontext, context, prefixMatcher, element, proposals);
                        proposeImpicitObjects(ccontext, context, prefixMatcher, proposals);
                        proposeKeywords(context, prefixMatcher, proposals);
                        proposeAssignements(context, prefixMatcher, assignments, proposals);
                    }
                    if (ELStreamCompletionItem.STREAM_METHOD.equals(node.getImage())) {
                        proposeOperators(ccontext, context, prefixMatcher, element, proposals, rootToNode, isBracketProperty(target, rootToNode));
                    }
                    ELJavaCompletion.propose(ccontext, context, element, target, proposals);
                } else {
                    proposeMethods(ccontext, context, resolved, prefixMatcher, element, proposals, rootToNode, isBracketProperty(target, rootToNode));
                    if (ELTypeUtilities.isIterableElement(ccontext, resolved)) {
                        proposeStream(ccontext, context, prefixMatcher, proposals);
                    }
                }
            }
        }, true);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    
    

    return proposals.isEmpty() ? CodeCompletionResult.NONE : result;
}
 
Example 13
Source File: EntityMappingsMetadataImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public JavaSource createJavaSource() {
    return JavaSource.create(cpi);
}
 
Example 14
Source File: CompilationUnitTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testNewCompilationUnitFromTemplate() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");

    File fakeFile = new File(getWorkDir(), "Fake.java");
    FileObject fakeFO = FileUtil.createData(fakeFile);

    FileObject emptyJava = FileUtil.createData(FileUtil.getConfigRoot(), "Templates/Classes/Empty.java");
    emptyJava.setAttribute("template", Boolean.TRUE);

    FileObject classJava = FileUtil.createData(FileUtil.getConfigRoot(), "Templates/Classes/Class.java");
    classJava.setAttribute("template", Boolean.TRUE);
    classJava.setAttribute("verbatim-create-from-template", Boolean.TRUE);
    Writer w = new OutputStreamWriter(classJava.getOutputStream(), "UTF-8");
    w.write("/*\n * License\n */\npackage zoo;\n\n/**\n * trida\n */\npublic class Template {\n}");
    w.close();

    FileObject packageJava = FileUtil.createData(FileUtil.getConfigRoot(), "Templates/Classes/package-info.java");
    packageJava.setAttribute("template", Boolean.TRUE);
    packageJava.setAttribute("verbatim-create-from-template", Boolean.TRUE);
    Writer w2 = new OutputStreamWriter(packageJava.getOutputStream(), "UTF-8");
    w2.write("/*\n * License\n */\npackage zoo;\n");
    w2.close();

    FileObject testSourceFO = FileUtil.createData(testFile); assertNotNull(testSourceFO);
    ClassPath sourcePath = ClassPath.getClassPath(testSourceFO, ClassPath.SOURCE); assertNotNull(sourcePath);
    FileObject[] roots = sourcePath.getRoots(); assertEquals(1, roots.length);
    final FileObject sourceRoot = roots[0]; assertNotNull(sourceRoot);
    ClassPath compilePath = ClassPath.getClassPath(testSourceFO, ClassPath.COMPILE); assertNotNull(compilePath);
    ClassPath bootPath = ClassPath.getClassPath(testSourceFO, ClassPath.BOOT); assertNotNull(bootPath);
    ClasspathInfo cpInfo = ClasspathInfo.create(bootPath, compilePath, sourcePath);
    JavaSource javaSource = JavaSource.create(cpInfo, fakeFO);

    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void cancel() {
        }

        public void run(WorkingCopy workingCopy) throws Exception {
            workingCopy.toPhase(JavaSource.Phase.PARSED);
            TreeMaker make = workingCopy.getTreeMaker();
            String path = "zoo/Krtek.java";
            GeneratorUtilities genUtils = GeneratorUtilities.get(workingCopy);
            CompilationUnitTree newTree = genUtils.createFromTemplate(sourceRoot, path, ElementKind.CLASS);
            MethodTree nju = make.Method(
                    make.Modifiers(Collections.<Modifier>emptySet()),
                    "m",
                    make.PrimitiveType(TypeKind.VOID), // return type - void
                    Collections.<TypeParameterTree>emptyList(),
                    Collections.<VariableTree>emptyList(),
                    Collections.<ExpressionTree>emptyList(),
                    make.Block(Collections.<StatementTree>emptyList(), false),
                    null // default value - not applicable
            );
            ClassTree clazz = make.Class(
                    make.Modifiers(Collections.<Modifier>singleton(Modifier.PUBLIC)),
                    "Krtek",
                    Collections.<TypeParameterTree>emptyList(),
                    null,
                    Collections.<Tree>emptyList(),
                    Collections.singletonList(nju)
            );
            if(newTree.getTypeDecls().isEmpty()) {
                newTree = make.addCompUnitTypeDecl(newTree, clazz);
            } else {
                Tree templateClass = newTree.getTypeDecls().get(0);
                genUtils.copyComments(templateClass, clazz, true);
                genUtils.copyComments(templateClass, clazz, false);
                newTree = make.removeCompUnitTypeDecl(newTree, 0);
                newTree = make.insertCompUnitTypeDecl(newTree, 0, clazz);
            }
            workingCopy.rewrite(null, newTree);

            String packagePath = "zoo/package-info.java";
            CompilationUnitTree newPackageTree = genUtils.createFromTemplate(sourceRoot, packagePath, ElementKind.PACKAGE);
            workingCopy.rewrite(null, newPackageTree);
        }
    };
    ModificationResult result = javaSource.runModificationTask(task);
    result.commit();

    String goldenClass =
        "/*\n * License\n */\n" +
        "package zoo;\n" +
        "\n" +
        "/**\n * trida\n */\n" +
        "public class Krtek {\n" +
        "\n" +
        "    void m() {\n" +
        "    }\n" +
        "}";
    String res = TestUtilities.copyFileToString(new File(getDataDir().getAbsolutePath() + "/zoo/Krtek.java"));
    assertEquals(goldenClass, res);

    String goldenPackage =
        "/*\n * License\n */\n" +
        "package zoo;\n";
    res = TestUtilities.copyFileToString(new File(getDataDir().getAbsolutePath() + "/zoo/package-info.java"));
    assertEquals(goldenPackage, res);
}
 
Example 15
Source File: CompilationUnitTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testRemoveClassFromCompUnit() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
            "package zoo;\n"
            + "\n"
            + "public class A {\n"
            + "  /** Something about a */\n"
            + "  int a;\n"
            + "  public class Krtek {\n"
            + "    public void foo() {\n"
            + "      int c=a;\n"
            + "    }\n"
            + "  }\n"
            + "}\n"
            + "class B {\n"
            + "    int a = 42;\n"
            + "}\n");
    
    FileObject testSourceFO = FileUtil.toFileObject(testFile);
    assertNotNull(testSourceFO);
    ClassPath sourcePath = ClassPath.getClassPath(testSourceFO, ClassPath.SOURCE);
    assertNotNull(sourcePath);
    FileObject[] roots = sourcePath.getRoots();
    assertEquals(1, roots.length);
    final FileObject sourceRoot = roots[0];
    assertNotNull(sourceRoot);
    ClassPath compilePath = ClassPath.getClassPath(testSourceFO, ClassPath.COMPILE);
    assertNotNull(compilePath);
    ClassPath bootPath = ClassPath.getClassPath(testSourceFO, ClassPath.BOOT);
    assertNotNull(bootPath);
    ClasspathInfo cpInfo = ClasspathInfo.create(bootPath, compilePath, sourcePath);
    
    String golden1 = 
        "package zoo;\n" +
        "\n" +
        "class B {\n" +
        "    int a = 42;\n" +
        "}\n";
    JavaSource javaSource = JavaSource.create(cpInfo, FileUtil.toFileObject(testFile));
    
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void cancel() {
        }

        public void run(WorkingCopy workingCopy) throws Exception {
            workingCopy.toPhase(JavaSource.Phase.PARSED);
            TreeMaker make = workingCopy.getTreeMaker();
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            CompilationUnitTree ccut = GeneratorUtilities.get(workingCopy).importComments(cut, cut);
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            CompilationUnitTree newTree = make.removeCompUnitTypeDecl(ccut, clazz);
            workingCopy.rewrite(cut, newTree);
        }
    };
    ModificationResult result = javaSource.runModificationTask(task);
    result.commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden1, res);
}
 
Example 16
Source File: ImportAnalysis2Test.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testTooSoon206957b() throws Exception {
    assertTrue(new File(getWorkDir(), "test").mkdirs());
    testFile = new File(getWorkDir(), "test/Entry.java");
    TestUtilities.copyStringToFile(testFile,
        "package test;\n" +
        "\n" +
        "import java.util.Map;\n" +
        "\n" +
        "public abstract class Entry implements Map {\n" +
        "}\n"
        );
    String golden =
        "package test;\n" +
        "\n" +
        "import java.util.Map;\n" +
        "\n" +
        "public abstract class Entry implements Map.Entry, Map {\n" +
        "}\n";

    final TransactionContext ctx = TransactionContext.beginStandardTransaction(Utilities.toURI(getWorkDir()).toURL(), true, ()->true, false);
    try {
        ClasspathInfo cpInfo = ClasspathInfoAccessor.getINSTANCE().create (BootClassPathUtil.getBootClassPath(), ClassPath.EMPTY, ClassPath.EMPTY, ClassPath.EMPTY, ClassPath.EMPTY, ClassPathSupport.createClassPath(getSourcePath()), ClassPath.EMPTY, null, true, false, false, true, false, null);
        JavaSource src = JavaSource.create(cpInfo, FileUtil.toFileObject(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();
                ClassTree clazz = (ClassTree) node.getTypeDecls().get(0);
                workingCopy.rewrite(clazz, make.insertClassImplementsClause(clazz, 0, make.QualIdent("java.util.Map.Entry")));
            }

        };
        src.runModificationTask(task).commit();
        String res = TestUtilities.copyFileToString(testFile);
        //System.err.println(res);
        assertEquals(golden, res);
    } finally {
        ctx.commit();
    }
}
 
Example 17
Source File: CreateEnumConstant.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public ChangeInfo implement() throws Exception {
        JavaSource js = JavaSource.create(cpInfo, targetFile);

        ModificationResult diff = js.runModificationTask(new Task<WorkingCopy>() {
            public void run(final WorkingCopy working) throws IOException {
                working.toPhase(Phase.RESOLVED);
                TypeElement targetType = target.resolve(working);

                if (targetType == null) {
                    ErrorHintsProvider.LOG.log(Level.INFO, "Cannot resolve target."); // NOI18N
                    return;
                }

                ClassTree targetTree = working.getTrees().getTree(targetType);

                if (targetTree == null) {
                    ErrorHintsProvider.LOG.log(Level.INFO, "Cannot resolve target tree: " + targetType.getQualifiedName() + "."); // NOI18N
                    return;
                }
                
                TypeMirror proposedType = CreateEnumConstant.this.proposedType.resolve(working);
                TreeMaker make = working.getTreeMaker();

                int mods = 1<<14; //XXX enum flag. Creation of enum constant should be part of TreeMaker
                ModifiersTree modds = make.Modifiers(mods, Collections.<AnnotationTree>emptyList());
                VariableTree var = make.Variable(modds, name, make.Type(proposedType), null);

                List<? extends Tree> members = targetTree.getMembers();
                ArrayList<Tree> newMembers = new ArrayList<Tree>(members);
                int pos = -1;
                for (Iterator<? extends Tree> it = members.iterator(); it.hasNext();) {
                    Tree t = it.next();
                    if (t.getKind() == Kind.VARIABLE && working.getTreeUtilities().isEnumConstant((VariableTree)t) ) {
                        pos = members.indexOf(t);
                    }
                }

                newMembers.add(pos+1, var);
                ClassTree enumm = make.Enum(targetTree.getModifiers(), targetTree.getSimpleName(), targetTree.getImplementsClause(), newMembers);
//                ClassTree decl = GeneratorUtilities.get(working).insertClassMember(targetTree, var);
                working.rewrite(targetTree, enumm);
            }
        });

        return Utilities.commitAndComputeChangeInfo(targetFile, diff, null);
    }
 
Example 18
Source File: HintTestBase.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private CompilationInfo parse(FileObject file) throws DataObjectNotFoundException, IllegalArgumentException, IOException {
    DataObject od = DataObject.find(file);
    EditorCookie ec = od.getLookup().lookup(EditorCookie.class);

    assertNotNull(ec);

    Document doc = ec.openDocument();

    doc.putProperty(Language.class, JavaTokenId.language());
    doc.putProperty("mimeType", "text/x-java");

    JavaSource js = JavaSource.create(ClasspathInfo.create(file), file);

    assertNotNull("found JavaSource for " + file, js);

    final DeadlockTask bt = new DeadlockTask(Phase.RESOLVED);

    js.runUserActionTask(bt, true);
    
    return bt.info;
}
 
Example 19
Source File: ElementUtilitiesEx.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the JavaSource repository for given source roots
 */
private static JavaSource getSources(FileObject[] roots) {
    // create the javasource repository for all the source files
    return JavaSource.create(getClasspathInfo(roots), Collections.<FileObject>emptyList());
}
 
Example 20
Source File: CompilationUnitTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void test157760a() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, "package foo; public @interface YY {}");

    FileObject emptyJava = FileUtil.createData(FileUtil.getConfigRoot(), "Templates/Classes/Empty.java");
    emptyJava.setAttribute("template", Boolean.TRUE);
    FileObject testSourceFO = FileUtil.toFileObject(testFile);
    assertNotNull(testSourceFO);
    ClassPath sourcePath = ClassPath.getClassPath(testSourceFO, ClassPath.SOURCE);
    assertNotNull(sourcePath);
    FileObject[] roots = sourcePath.getRoots();
    assertEquals(1, roots.length);
    final FileObject sourceRoot = roots[0];
    assertNotNull(sourceRoot);
    ClassPath compilePath = ClassPath.getClassPath(testSourceFO, ClassPath.COMPILE);
    assertNotNull(compilePath);
    ClassPath bootPath = ClassPath.getClassPath(testSourceFO, ClassPath.BOOT);
    assertNotNull(bootPath);
    ClasspathInfo cpInfo = ClasspathInfo.create(bootPath, compilePath, sourcePath);

    String golden =
        "@YY\n" +
        "package zoo;\n\n" +
        "import foo.YY;\n" + /*XXX:*/"\n";

    JavaSource javaSource = JavaSource.create(cpInfo, FileUtil.toFileObject(testFile));

    Task<WorkingCopy> task = new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws Exception {
            workingCopy.toPhase(JavaSource.Phase.RESOLVED);
            TypeElement yyAnnotation = workingCopy.getElements().getTypeElement("foo.YY");
            assertNotNull(yyAnnotation);
            TreeMaker make = workingCopy.getTreeMaker();
            CompilationUnitTree newTree = make.CompilationUnit(
                    Collections.singletonList(make.Annotation(make.QualIdent(yyAnnotation), Collections.<ExpressionTree>emptyList())),
                    sourceRoot,
                    "zoo/package-info.java",
                    Collections.<ImportTree>emptyList(),
                    Collections.<Tree>emptyList()
            );
            workingCopy.rewrite(null, newTree);
        }
    };
    ModificationResult result = javaSource.runModificationTask(task);
    result.commit();
    String res = TestUtilities.copyFileToString(new File(getDataDir().getAbsolutePath() + "/zoo/package-info.java"));
    //System.err.println(res);
    assertEquals(golden, res);
}