Java Code Examples for org.netbeans.api.java.classpath.ClassPath#getRoots()

The following examples show how to use org.netbeans.api.java.classpath.ClassPath#getRoots() . 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: JShellEnvironment.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private String addRoots(String prev, ClassPath cp) {
    FileObject[] roots = cp.getRoots();
    StringBuilder sb = new StringBuilder(prev);
    
    for (FileObject r : roots) {
        FileObject ar = FileUtil.getArchiveFile(r);
        if (ar == null) {
            ar = r;
        }
        File f = FileUtil.toFile(ar);
        if (f != null) {
            if (sb.length() > 0) {
                sb.append(File.pathSeparatorChar);
            }
            sb.append(f.getPath());
        }
    }
    return sb.toString();
}
 
Example 2
Source File: AppClientModuleProviderImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public File[] getRequiredLibraries() {
    ProjectSourcesClassPathProvider cppImpl = project.getLookup().lookup(ProjectSourcesClassPathProvider.class);
    // do not use COMPILE classpath here because it contains dependencies
    // with *provided* scope which should not be deployed
    ClassPath cp = cppImpl.getProjectSourcesClassPath(ClassPath.EXECUTE);
    List<File> files = new ArrayList<File>();
    for (FileObject fo : cp.getRoots()) {
        fo = FileUtil.getArchiveFile(fo);
        if (fo == null) {
            continue;
        }
        files.add(FileUtil.toFile(fo));
    }
    return files.toArray(new File[files.size()]);
}
 
Example 3
Source File: ClassSourceResolver.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public List<URL> getClasspath() {
    Sources sources = ProjectUtils.getSources(project);
    SourceGroup[] sgs = sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
    List<URL> list = new ArrayList<URL>();
    for (SourceGroup sg : sgs) {
        try {
            ClassPath cp = ClassPath.getClassPath(sg.getRootFolder(), ClassPath.SOURCE);
            if (cp != null) {
                for (FileObject fob : cp.getRoots()) {
                    URL[] urls = UnitTestForSourceQuery.findSources(fob);
                    if (urls.length == 0) {
                        BinaryForSourceQuery.Result result = BinaryForSourceQuery.findBinaryRoots(fob.getURL());
                        list.addAll(Arrays.asList(result.getRoots()));
                    }
                }
            }
        } catch (FileStateInvalidException fsiex) {
            FormUtils.LOGGER.log(Level.INFO, fsiex.getMessage(), fsiex);
        }
    }
    return list;
}
 
Example 4
Source File: AndroidClassPathProvider.java    From NBANDROID-V2 with Apache License 2.0 6 votes vote down vote up
@Override
public URL[] getRoots() {
    List<URL> tmp = new ArrayList<>();
    if (androidProjectModel != null && !androidProjectModel.getBootClasspath().isEmpty()) {
        String next = androidProjectModel.getBootClasspath().iterator().next();
        AndroidJavaPlatform findPlatform = AndroidJavaPlatformProvider.findPlatform(next, androidProjectModel.getCompileTarget());
        if (findPlatform != null) {
            ClassPath bootstrapLibraries = findPlatform.getBootstrapLibraries();
            FileObject[] roots = bootstrapLibraries.getRoots();
            for (FileObject root : roots) {
                tmp.add(root.toURL());
            }
        }
    }
    //Refresh Platforms, workaround to handle new platform downloaded by Gradle
    if (tmp.isEmpty()) {
        AndroidSdk sdk = project.getLookup().lookup(AndroidSdk.class);
        if (sdk != null) {
            Runnable runnable = () -> {
                sdk.updateSdkPlatformPackages();
            };
            RequestProcessor.getDefault().schedule(runnable, 5, TimeUnit.SECONDS);
        }
    }
    return tmp.toArray(new URL[tmp.size()]);
}
 
Example 5
Source File: SrcFinder.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static FileObject searchBinaryPath(String classPathID, String respath, URL url) {
    Set<ClassPath> cpaths = GlobalPathRegistry.getDefault().getPaths(classPathID);
    for (ClassPath cpath: cpaths) {
        FileObject[] cpRoots = cpath.getRoots();
        for (int i = 0; i < cpRoots.length; i++) {
            SourceForBinaryQuery.Result result = SourceForBinaryQuery.findSourceRoots(URLMapper.findURL(cpRoots[i], URLMapper.EXTERNAL));
            FileObject[] srcRoots = result.getRoots();
            for (int j = 0; j < srcRoots.length; j++) {
                FileObject fo = srcRoots[j].getFileObject(respath);
                if (fo != null && isJavadocAssigned(cpath, url)) {
                    return fo; 
                }
            }
        }
    }
    return null;
}
 
Example 6
Source File: AddGoogleDependencyAction.java    From NBANDROID-V2 with Apache License 2.0 6 votes vote down vote up
private void findCompileTimeDependencies(NbAndroidProject project, List<ArtifactData> compileDependecies) {
    final ClassPathProvider cpProvider = project.getLookup().lookup(ClassPathProvider.class);
    if (cpProvider != null) {
        Sources srcs = ProjectUtils.getSources(project);
        SourceGroup[] sourceGroups = srcs.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
        Set<FileObject> roots = Sets.newHashSet();
        for (SourceGroup sg : sourceGroups) {
            roots.add(sg.getRootFolder());
        }
        Iterable<ClassPath> compileCPs = Iterables.transform(roots, new Function<FileObject, ClassPath>() {

            @Override
            public ClassPath apply(FileObject f) {
                return cpProvider.findClassPath(f, ClassPath.COMPILE);
            }
        });
        ClassPath compileCP
                = ClassPathSupport.createProxyClassPath(Lists.newArrayList(compileCPs).toArray(new ClassPath[0]));
        if (cpProvider instanceof AndroidClassPath) {
            for (FileObject cpRoot : compileCP.getRoots()) {
                ArtifactData lib = ((AndroidClassPath) cpProvider).getArtifactData(cpRoot.toURL());
                compileDependecies.add(lib);
            }
        }
    }
}
 
Example 7
Source File: ClassPathProviderImplTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void assertRtJar(ClassPath cp, boolean shouldBeThere) {
    for (FileObject fo : cp.getRoots()) {
        if (fo.getNameExt().equals("rt.jar")) {
            if (shouldBeThere) {
                return;
            }
            fail("We don't want rt.jar on boot classpath: " + fo);
        }
        FileObject archive = FileUtil.getArchiveFile(fo);
        if (archive != null && archive.getNameExt().equals("rt.jar")) {
            if (shouldBeThere) {
                return;
            }
            fail("We don't want rt.jar on boot classpath: " + archive);
        }
    }
    assertFalse("We don't want rt.jar on cp, right?", shouldBeThere);
}
 
Example 8
Source File: SourcePathImplementationTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testSourcePathImplementation () throws Exception {
    ClassPathProviderImpl cpProvider = pp.getClassPathProvider();
    ClassPath[] cps = cpProvider.getProjectClassPaths(ClassPath.SOURCE);
    ClassPath cp = cps[0];
    FileObject[] roots = cp.getRoots();
    assertNotNull ("Roots can not be null",roots);
    assertEquals("There must be one source root", 1, roots.length);
    assertEquals("There must be src root",roots[0],sources);
    TestListener tl = new TestListener();
    cp.addPropertyChangeListener (tl);
    FileObject newRoot = SourceRootsTest.addSourceRoot(helper, projdir,"src.other.dir","other");
    assertTrue("Classpath must fire PROP_ENTRIES and PROP_ROOTS", tl.getEvents().containsAll(Arrays.asList(ClassPath.PROP_ENTRIES, ClassPath.PROP_ROOTS)));
    roots = cp.getRoots();
    assertNotNull ("Roots can not be null",roots);
    assertEquals("There must be two source roots", 2, roots.length);
    assertEquals("There must be src root",roots[0],sources);
    assertEquals("There must be other root",roots[1],newRoot);
    cp.removePropertyChangeListener(tl);
}
 
Example 9
Source File: AddDependencyAction.java    From NBANDROID-V2 with Apache License 2.0 6 votes vote down vote up
private void findCompileTimeDependencies(NbAndroidProject project, List<ArtifactData> compileDependecies) {
    final ClassPathProvider cpProvider = project.getLookup().lookup(ClassPathProvider.class);
    if (cpProvider != null) {
        Sources srcs = ProjectUtils.getSources(project);
        SourceGroup[] sourceGroups = srcs.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
        Set<FileObject> roots = Sets.newHashSet();
        for (SourceGroup sg : sourceGroups) {
            roots.add(sg.getRootFolder());
        }
        Iterable<ClassPath> compileCPs = Iterables.transform(roots, new Function<FileObject, ClassPath>() {

            @Override
            public ClassPath apply(FileObject f) {
                return cpProvider.findClassPath(f, ClassPath.COMPILE);
            }
        });
        ClassPath compileCP
                = ClassPathSupport.createProxyClassPath(Lists.newArrayList(compileCPs).toArray(new ClassPath[0]));
        if (cpProvider instanceof AndroidClassPath) {
            for (FileObject cpRoot : compileCP.getRoots()) {
                ArtifactData lib = ((AndroidClassPath) cpProvider).getArtifactData(cpRoot.toURL());
                compileDependecies.add(lib);
            }
        }
    }
}
 
Example 10
Source File: ClassPathProviderImplTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void checkJSPSourceClassPath59055(ClassPath cp) {
    FileObject[] roots = cp.getRoots();
    assertEquals(3, roots.length);
    assertTrue(cp.getRoots()[0].equals(webRoot59055));
    assertTrue(cp.getRoots()[1].equals(sourceRoot59055_1));
    assertTrue(cp.getRoots()[2].equals(sourceRoot59055_2));
}
 
Example 11
Source File: JavaCustomIndexer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isAptBuildGeneratedFolder(
        @NonNull final URL root,
        @NonNull final ClassPath srcPath) {
    Parameters.notNull("root", root);       //NOI18N
    Parameters.notNull("srcPath", srcPath); //NOI18N
    for (FileObject srcRoot : srcPath.getRoots()) {
        if (root.equals(AnnotationProcessingQuery.getAnnotationProcessingOptions(srcRoot).sourceOutputDirectory())) {
           return true;
        }
    }
    return false;
}
 
Example 12
Source File: JsfIndex.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance of JsfIndex
 */
private JsfIndex(ClassPath sourceCp, ClassPath compileCp, ClassPath executeCp, ClassPath bootCp) {
    //#179930 - merge compile and execute classpath, remove once #180183 resolved
    Collection<FileObject> cbRoots = new HashSet<>();
    cbRoots.addAll(Arrays.asList(compileCp.getRoots()));
    cbRoots.addAll(Arrays.asList(executeCp.getRoots()));
    binaryRoots = cbRoots.toArray(new FileObject[]{});

    Collection<FileObject> croots = new HashSet<>();
    //add source roots
    croots.addAll(Arrays.asList(sourceCp.getRoots()));
    //add boot and compile roots (sources if available)
    for(ClassPath cp : new ClassPath[]{compileCp, bootCp}) {
        for(FileObject root : cp.getRoots()) {
            URL rootUrl = root.toURL();
            FileObject[] sourceRoots = SourceForBinaryQuery.findSourceRoots(rootUrl).getRoots();
            if(sourceRoots.length == 0) {
                //add the binary root
                croots.add(root);
            } else {
                //add the found source roots
                croots.addAll(Arrays.asList(sourceRoots));
            }
        }
    }
    
    roots = croots.toArray(new FileObject[]{});
}
 
Example 13
Source File: CompilationUnitTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testNewCompilationUnitFromNonExistingTemplate() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");

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

    FileObject template = FileUtil.getConfigFile("Templates/Classes/Class.java");
    if (template != null) template.delete();
    template = FileUtil.getConfigFile("Templates/Classes/Empty.java");
    if(template != null) template.delete();

    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);
            workingCopy.rewrite(null, newTree);
        }
    };
    ModificationResult result = javaSource.runModificationTask(task);
    result.commit();

    String res = TestUtilities.copyFileToString(new File(getDataDir().getAbsolutePath() + "/zoo/Krtek.java"));
    assertEquals(res, "package zoo;\n\n");
}
 
Example 14
Source File: ClasspathsTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testSourcePath() throws Exception {
    ClassPath cp = ClassPath.getClassPath(myAppJava, ClassPath.SOURCE);
    assertNotNull("have some SOURCE classpath for src/", cp);
    FileObject[] roots = cp.getRoots();
    assertEquals("have one entry in " + cp, 1, roots.length);
    assertEquals("that is src/", simple.getProjectDirectory().getFileObject("src"), roots[0]);
    cp = ClassPath.getClassPath(specialTaskJava, ClassPath.SOURCE);
    assertNotNull("have some SOURCE classpath for antsrc/", cp);
    roots = cp.getRoots();
    assertEquals("have one entry", 1, roots.length);
    assertEquals("that is antsrc/", simple.getProjectDirectory().getFileObject("antsrc"), roots[0]);
    cp = ClassPath.getClassPath(buildProperties, ClassPath.SOURCE);
    assertNull("have no SOURCE classpath for build.properties", cp);
}
 
Example 15
Source File: CompilationUnitTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void test157760c() throws Exception {
    testFile = new File(getWorkDir(), "package-info.java");
    TestUtilities.copyStringToFile(testFile, "/*\n a\n */\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 = "/*\n a\n */\n@AA\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("AA"), Collections.<ExpressionTree>emptyList()));
            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 16
Source File: ClassPathProviderImplTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void checkJSPSourceClassPath(ClassPath cp) {
    FileObject[] roots = cp.getRoots();
    assertEquals(2, roots.length);
    assertTrue(cp.getRoots()[0].equals(webRoot));
    assertTrue(cp.getRoots()[1].equals(sourceRoot));
}
 
Example 17
Source File: CompilationUnitTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void test204638() throws Exception {
    setupJavaTemplates();
    FileObject testSourceFO = FileUtil.toFileObject(testFile);
    assertNotNull(testSourceFO);
    DataObject created = DataObject.find(classJava).createFromTemplate(DataFolder.findFolder(testSourceFO.getParent()));
    assertEquals(template, created.getPrimaryFile().asText());
    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 =
        "/*\n" +
        "initial\n" +
        "comment\n" +
        "*/\n" +
        "package zoo;\n" +
        "public class Krtek {\n" +
        "    public Krtek() {}\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.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            CompilationUnitTree newTree = make.CompilationUnit(
                    sourceRoot,
                    "zoo/Krtek.java",
                    Collections.<ImportTree>emptyList(),
                    Collections.<Tree>emptyList()
            );
            MethodTree constr = make.Method(make.Modifiers(EnumSet.of(Modifier.PUBLIC)), "Krtek", null, Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), "{}", null);
            newTree = make.addCompUnitTypeDecl(newTree, make.Class(make.Modifiers(EnumSet.of(Modifier.PUBLIC)), "Krtek", Collections.<TypeParameterTree>emptyList(), null, Collections.<Tree>emptyList(), Collections.<Tree>singletonList(constr)));
            workingCopy.rewrite(null, newTree);
        }
    };
    ModificationResult result = javaSource.runModificationTask(task);
    result.commit();
    String res = TestUtilities.copyFileToString(new File(getDataDir().getAbsolutePath() + "/zoo/Krtek.java"));
    //System.err.println(res);
    assertEquals(res, golden1);
}
 
Example 18
Source File: SourcePathProviderImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Translates a relative path ("java/lang/Thread.java") to url 
 * ("file:///C:/Sources/java/lang/Thread.java"). Uses GlobalPathRegistry
 * if global == true.
 *
 * @param relativePath a relative path (java/lang/Thread.java)
 * @param global true if global path should be used
 * @return url or <code>null</code>
 */
@Override
public String getURL (String relativePath, boolean global) {    if (verbose) System.out.println ("SPPI: getURL " + relativePath + " global " + global);
    relativePath = normalize(relativePath);
    if (global) {
        synchronized (urlCacheGlobal) {
            if (urlCacheGlobal.containsKey(relativePath)) {
                if (verbose) System.out.println("Have cached global path for '"+relativePath+"' url = "+urlCacheGlobal.get(relativePath));
                return urlCacheGlobal.get(relativePath);    // URL or null
            }
        }
    } else {
        synchronized (urlCache) {
            if (urlCache.containsKey(relativePath)) {
                if (verbose) System.out.println("Have cached path for '"+relativePath+"' url = "+urlCache.get(relativePath));
                return urlCache.get(relativePath);  // URL or null
            }
        }
    }
    FileObject fo;
    ClassPath ss = null;
    ClassPath os = null;
    synchronized (this) {
        if (originalSourcePath != null) {
            ss = smartSteppingSourcePath;
            os = originalSourcePath;
        }
    }
    if (ss != null && os != null) {
        fo = ss.findResource(relativePath);
        if (fo == null && global) {
            fo = os.findResource(relativePath);
        }
        if (fo == null && global) {
            fo = GlobalPathRegistry.getDefault().findResource(relativePath);
        }
    } else {
        fo = GlobalPathRegistry.getDefault().findResource(relativePath);
    }
    if (fo == null && global) {
        Set<ClassPath> cpaths = GlobalPathRegistry.getDefault().getPaths(ClassPath.COMPILE);
        for (ClassPath cp : cpaths) {
            fo = cp.findResource(relativePath);
            if (fo != null) {
                FileObject[] roots = cp.getRoots();
                for (FileObject r : roots) {
                    if (FileUtil.isParentOf(r, fo)) {
                        addToSourcePath(r, false);
                        break;
                    }
                }
                break;
            }
        }
    }
    
    if (verbose) System.out.println ("SPPI:   fo " + fo);

    String url;
    if (fo == null) {
        url = null;
    } else {
        url = fo.toURL ().toString ();
    }
    if (global) {
        synchronized (urlCacheGlobal) {
            if (verbose) System.out.println("Storing path into global cache for '"+relativePath+"' url = "+url);
            urlCacheGlobal.put(relativePath, url);
            if (verbose) System.out.println("  Global cache ("+urlCacheGlobal.size()+") = "+urlCacheGlobal);
        }
    } else {
        synchronized (urlCache) {
            if (verbose) System.out.println("Storing path into cache for '"+relativePath+"' url = "+url);
            urlCache.put(relativePath, url);
            if (verbose) System.out.println("  Cache = ("+urlCache.size()+") "+urlCache);
        }
    }
    return url;
}
 
Example 19
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 20
Source File: ClassPathProviderImplTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void checkSourceSourceClassPath(ClassPath cp) {
    FileObject[] roots = cp.getRoots();
    assertEquals(1, roots.length);
    assertTrue(cp.getRoots()[0].equals(sourceRoot));
}