Java Code Examples for org.openide.filesystems.FileObject.toURL()

The following are Jave code examples for showing how to use toURL() of the org.openide.filesystems.FileObject class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: incubator-netbeans   File: ProjectServicesImpl.java   Source Code and License Vote up 6 votes
@Override
public synchronized boolean addDeleteListener(DeleteListener l) {
    boolean added = super.addDeleteListener(l);
    if (added && projectDeleteListener == null) {
        Project p = getProject(getURL());
        if (p != null) {
            FileObject projDir = p.getProjectDirectory();
            projectDeleteListener = new ProjectDeleteListener(projDir.toURL(), this);
            projDir.addFileChangeListener(projectDeleteListener);
        } else {
            super.removeDeleteListener(l);
            added = false;
        }
    }
    return added;
}
 
Example 2
Project: incubator-netbeans   File: RepositoryUpdater.java   Source Code and License Vote up 6 votes
@org.netbeans.api.annotations.common.SuppressWarnings(
value="DMI_BLOCKING_METHODS_ON_URL",
justification="URLs have never host part")
private static ClassPath.Entry getClassPathEntry (final FileObject root) {
    if (root != null) {
        Set<String> ids = PathRegistry.getDefault().getSourceIdsFor(root.toURL());
        if (ids != null) {
            for (String id : ids) {
                ClassPath cp = ClassPath.getClassPath(root, id);
                if (cp != null) {
                    URL rootURL = root.toURL();
                    for (ClassPath.Entry e : cp.entries()) {
                        if (rootURL.equals(e.getURL())) {
                            return e;
                        }
                    }
                }
            }
        }
    }
    return null;
}
 
Example 3
Project: incubator-netbeans   File: ProjectClassLoader.java   Source Code and License Vote up 6 votes
@Override
protected URL findResource(String name) {
    // In design time some resources added/changed by the user might not be propagated
    // to execution classpath yet (until the project is rebuilt), so not found by
    // custom components. That's why we prefer to look for them on sources classpath
    // first (bug 69377). An exception is use of @NbBundle.Messages annotations which
    // fills the properties file only in built results. If the same file is also
    // present in sources then it is incomplete and we should not use it (bug 238094).
    if ((!name.equals("Bundle.properties") && !name.endsWith("/Bundle.properties")) // NOI18N
            || !isProjectWithNbBundle()) {
        FileObject fo = sources.findResource(name);
        if (fo != null) {
            return fo.toURL();
        }
    }
    return projectClassLoaderDelegate.getResource(name);
}
 
Example 4
Project: incubator-netbeans   File: QuerySupport.java   Source Code and License Vote up 6 votes
private static void collectClasspathRoots(FileObject file, Collection<String> pathIds, boolean binaryPaths, Collection<FileObject> roots) {
    for(String id : pathIds) {
        Collection<FileObject> classpathRoots = getClasspathRoots(file, id);
        if (binaryPaths) {
            // Filter out roots that do not have source files available
            for(FileObject binRoot : classpathRoots) {
                final URL binRootUrl = binRoot.toURL();
                URL[] srcRoots = PathRegistry.getDefault().sourceForBinaryQuery(binRootUrl, null, false);
                if (srcRoots != null) {
                    LOG.log(Level.FINE, "Translating {0} -> {1}", new Object [] { binRootUrl, srcRoots }); //NOI18N
                    for(URL srcRootUrl : srcRoots) {
                        FileObject srcRoot = URLCache.getInstance().findFileObject(srcRootUrl, false);
                        if (srcRoot != null) {
                            roots.add(srcRoot);
                        }
                    }
                } else {
                    LOG.log(Level.FINE, "No sources for {0}, adding bin root", binRootUrl); //NOI18N
                    roots.add(binRoot);
                }
            }
        } else {
            roots.addAll(classpathRoots);
        }
    }
}
 
Example 5
Project: incubator-netbeans   File: APTUtils.java   Source Code and License Vote up 6 votes
private APTUtils(@NonNull final FileObject root) {
    this.root = root;
    bootPath = ClassPath.getClassPath(root, ClassPath.BOOT);
    compilePath = ClassPath.getClassPath(root, ClassPath.COMPILE);
    processorPath = new AtomicReference<>(ClassPath.getClassPath(root, JavaClassPathConstants.PROCESSOR_PATH));
    processorModulePath = new AtomicReference<>(ClassPath.getClassPath(root, JavaClassPathConstants.MODULE_PROCESSOR_PATH));
    aptOptions = AnnotationProcessingQuery.getAnnotationProcessingOptions(root);
    sourceLevel = SourceLevelQuery.getSourceLevel2(root);
    compilerOptions = CompilerOptionsQuery.getOptions(root);
    this.slidingRefresh = RP.create(() -> {
        IndexingManager.getDefault().refreshIndex(
                root.toURL(),
                Collections.<URL>emptyList(),
                false);
    });
    usedRoots = new UsedRoots(root.toURL());
}
 
Example 6
Project: incubator-netbeans   File: DocumentInputSource.java   Source Code and License Vote up 6 votes
/**
     * Get InputSource system ID. Use ordered logic:
     * <ul>
     *  <li>use client's <code>setSystemId()</code>, or
     *  <li>try to derive it from <code>Document</code>
     *      <p>e.g. look at <code>Document.StreamDescriptionProperty</code> for
     *      {@link DataObject} and use URL of its primary file.
     * </ul>
     * @return entity system Id or <code>null</code>
     */
    public String getSystemId() {
        
        String system = super.getSystemId();
        
        // XML module specifics property, promote into this API
//        String system = (String) doc.getProperty(TextEditorSupport.PROP_DOCUMENT_URL);        
        
        if (system == null) {
            final FileObject fo = EditorDocumentUtils.getFileObject(doc);
            if (fo != null) {
                URL url = fo.toURL();
                system = url.toExternalForm();
            } else {
                LOG.info("XML:DocumentInputSource:No FileObject in stream description.");   //NOI18N
            }
        }
        return system;
    }
 
Example 7
Project: incubator-netbeans   File: GeneratedFilesHelper.java   Source Code and License Vote up 6 votes
/** Find (maybe cached) CRC for a file. Will open its own input stream. */
private static String getCrc32(FileObject fo) throws IOException {
    URL u = fo.toURL();
    fo.refresh();
    long footprint = fo.lastModified().getTime() ^ fo.getSize();
    String crc = findCachedCrc32(u, footprint);
    if (crc == null) {
        InputStream is = fo.getInputStream();
        try {
            crc = computeCrc32(new BufferedInputStream(is));
            cacheCrc32(crc, u, footprint);
        } finally {
            is.close();
        }
    }
    return crc;
}
 
Example 8
Project: incubator-netbeans   File: SourcePathProviderImpl.java   Source Code and License Vote up 6 votes
private static ClassPath createClassPath(FileObject[] froots) {
    List<PathResourceImplementation> pris = new ArrayList<PathResourceImplementation> ();
    for (FileObject fo : froots) {
        if (fo != null && fo.canRead()) {
            try {
                URL url = fo.toURL();
                pris.add(ClassPathSupport.createResource(url));
            } catch (IllegalArgumentException iaex) {
                // Can be thrown from ClassPathSupport.createResource()
                // Ignore - bad source root
                //logger.log(Level.INFO, "Invalid source root = "+fo, iaex);
                logger.warning(iaex.getLocalizedMessage());
            }
        }
    }
    return ClassPathSupport.createClassPath(pris);
}
 
Example 9
Project: incubator-netbeans   File: JavadocForBinaryQueryLibraryImpl.java   Source Code and License Vote up 5 votes
private URL getNormalizedURL (URL url) {
    //URL is already nornalized, return it
    final Boolean isNormalized = isNormalizedURL(url);
    if (isNormalized == null) {
        return null;
    }
    if (isNormalized == Boolean.TRUE) {
        return url;
    }
    //Todo: Should listen on the LibrariesManager and cleanup cache
    // in this case the search can use the cache onle and can be faster
    // from O(n) to O(ln(n))
    URI uri = null;
    try {
        uri = url.toURI();
    } catch (URISyntaxException e) {
        Exceptions.printStackTrace(e);
    }
    URL normalizedURL = uri == null ? null : normalizedURLCache.get(uri);
    if (normalizedURL == null) {
        final FileObject fo = URLMapper.findFileObject(url);
        if (fo != null) {
            normalizedURL = fo.toURL();
            if (uri != null) {
                this.normalizedURLCache.put (uri, normalizedURL);
            }
        }
    }
    return normalizedURL;
}
 
Example 10
Project: incubator-netbeans   File: CompileOnSaveActionQueryTest.java   Source Code and License Vote up 5 votes
@Before
@Override
public void setUp() throws IOException {
    clearWorkDir();
    final File wd = getWorkDir();
    final FileObject src1 = FileUtil.createFolder(FileUtil.normalizeFile(
            new File(wd,"src"))); //NOI18N
    final FileObject src2 = FileUtil.createFolder(FileUtil.normalizeFile(
            new File(wd,"src2"))); //NOI18N
    nonSrcUrl = BaseUtilities.toURI(wd).toURL();
    srcUrl1 = src1.toURL();
    srcUrl2 = src2.toURL();
    impl1 = new ActionImpl();
    impl2 = new ActionImpl();
    impl3 = new ActionImpl();
    MockLookup.setInstances(
        new ProviderImpl(srcUrl1, impl1),
        new ProviderImpl(srcUrl2, impl2),
        new ProviderImpl(srcUrl1, impl3));
    //Enable all
    impl1.setEnabled(true);
    impl1.setUpdateClasses(true);
    impl1.setUpdateResources(true);
    impl2.setEnabled(true);
    impl2.setUpdateClasses(true);
    impl2.setUpdateResources(true);
    impl3.setEnabled(true);
    impl3.setUpdateClasses(true);
    impl3.setUpdateResources(true);
}
 
Example 11
Project: incubator-netbeans   File: RepositoryUpdaterTest.java   Source Code and License Vote up 5 votes
public static void unregister (FileObject binRoot) throws IOException {
    URL url = binRoot.toURL();
    map.remove(url);
    Result r = results.get (url);
    if (r != null) {
        r.update (null);
    }
}
 
Example 12
Project: incubator-netbeans   File: SourceFilesCache.java   Source Code and License Vote up 5 votes
public URL getSourceFile(String name, int hash, SourceContent content) {
    String path = Integer.toHexString(hash) + '/' + name;
    FileObject fo = fs.findResource(path);
    if (fo == null) {
        fo = fs.createFile(path, content);
    }
    return fo.toURL();
}
 
Example 13
Project: incubator-netbeans   File: SourcePathProviderImpl.java   Source Code and License Vote up 5 votes
private void addToSourcePath(FileObject sourceRoot, boolean clearURLCaches) {
    URL newURL = sourceRoot.toURL();
    synchronized (SourcePathProviderImpl.this) {
        if (originalSourcePath == null) {
            return ;
        }
        List<URL> sourcePaths = getURLRoots(originalSourcePath);
        sourcePaths.add(newURL);
        originalSourcePath =
                SourcePathProviderImpl.createClassPath(
                    sourcePaths.toArray(new URL[0]));

        sourcePaths = getURLRoots(smartSteppingSourcePath);
        sourcePaths.add(newURL);
        smartSteppingSourcePath =
                SourcePathProviderImpl.createClassPath(
                    sourcePaths.toArray(new URL[0]));
    }
    if (clearURLCaches) {
        synchronized (urlCache) {
            urlCache.clear();
        }
        synchronized (urlCacheGlobal) {
            urlCacheGlobal.clear();
        }
    }
    pcs.firePropertyChange (PROP_SOURCE_ROOTS, null, null);
}
 
Example 14
Project: incubator-netbeans   File: FileObjectIndexable.java   Source Code and License Vote up 5 votes
@Override
public URL getURL() {
    if (url == null) {
        try {
            FileObject f = getFileObject();
            if (f != null) {
                url = f.toURL();
                if (LOG.isLoggable(Level.FINEST)) {
                    LOG.log(
                        Level.FINEST,
                        "URL from existing FileObject: {0} = {1}",  //NOI18N
                        new Object[] {
                            FileUtil.getFileDisplayName(f),
                            url
                        });
                }
            } else {
                url = Util.resolveUrl(root.toURL(), relativePath, false);
                if (LOG.isLoggable(Level.FINEST)) {
                    LOG.log(
                        Level.FINEST,
                        "URL from non existing FileObject root: {0} ({1}), relative path: {2} = {3}",  //NOI18N
                        new Object[] {
                            FileUtil.getFileDisplayName(root),
                            root.toURL(),
                            relativePath,
                            url
                        });
                }
            }
        } catch (MalformedURLException ex) {
            url = ex;
        }
    }

    return url instanceof URL ? (URL) url : null;
}
 
Example 15
Project: incubator-netbeans   File: MultiModule.java   Source Code and License Vote up 5 votes
@NonNull
private Optional<Pair<String,ClassPath>> findImpl(@NonNull final FileObject artifact) {
    final Map<String,Pair<ClassPath,CPImpl>> data = getCache();
    final URL artifactURL = artifact.toURL();
    for (Map.Entry<String,Pair<ClassPath,CPImpl>> e : data.entrySet()) {
        final ClassPath cp = e.getValue().first();
        for (ClassPath.Entry cpe : cp.entries()) {
            if (Utilities.isParentOf(cpe.getURL(), artifactURL)) {
                return Optional.of(Pair.of(e.getKey(), cp));
            }
        }
    }
    return Optional.empty();
}
 
Example 16
Project: incubator-netbeans   File: GeneratedFilesHelper.java   Source Code and License Vote up 5 votes
/** Find (maybe cached) CRC for a file, using a preexisting input stream (not closed by this method). */
private static String getCrc32(InputStream is, FileObject fo) throws IOException {
    URL u = fo.toURL();
    fo.refresh(); // in case was written on disk and we did not notice yet...
    long footprint = fo.lastModified().getTime() ^ fo.getSize();
    String crc = findCachedCrc32(u, footprint);
    if (crc == null) {
        crc = computeCrc32(is);
        cacheCrc32(crc, u, footprint);
    }
    return crc;
}
 
Example 17
Project: incubator-netbeans   File: SourcePathProviderImpl.java   Source Code and License Vote up 4 votes
private ArtifactsUpdatedImpl addArtifactsUpdateListenerFor(JPDADebugger debugger, FileObject src) {
    URL url = src.toURL();
    ArtifactsUpdatedImpl l = new ArtifactsUpdatedImpl(debugger, url, src);
    BuildArtifactMapper.addArtifactsUpdatedListener(url, l);
    return l;
}
 
Example 18
Project: incubator-netbeans   File: ProfileSupport.java   Source Code and License Vote up 4 votes
@CheckForNull
protected URL map(@NonNull final FileObject fo) {
    return fo.toURL();
}
 
Example 19
Project: incubator-netbeans   File: GeneratedSourceRootTest.java   Source Code and License Vote up 4 votes
public void testMiscellaneousQueries() throws Exception {
    final Project p = createTestProject(true);
    ProjectManager.mutex().writeAccess(() -> {
        try {
            final UpdateHelper h = p.getLookup().lookup(TestProject.class).getUpdateHelper();
            final EditableProperties ep = h.getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH);
            ep.setProperty("encoding", "ISO-8859-2");   //NOI18N
            h.putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH, ep);
            ProjectManager.getDefault().saveProject(p);
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    });
    FileObject d = p.getProjectDirectory();
    FileObject src = d.getFileObject("src");
    FileObject test = d.getFileObject("test");
    FileObject stuff = d.getFileObject("build/generated-sources/stuff");
    URL classes = new URL(d.toURL(), "build/classes/");
    URL testClasses = new URL(d.toURL(), "build/test/classes/");
    URL distJar = FileUtil.getArchiveRoot(BaseUtilities.toURI(FileUtil.normalizeFile(
            new File(FileUtil.toFile(d), "dist/x.jar".replace('/', File.separatorChar)))).toURL()); //NOI18N
    FileObject xgen = stuff.getFileObject("net/nowhere/XGen.java");
    assertEquals(Arrays.asList(src, stuff), Arrays.asList(SourceForBinaryQuery.findSourceRoots(classes).getRoots()));
    assertEquals(Arrays.asList(test), Arrays.asList(SourceForBinaryQuery.findSourceRoots(testClasses).getRoots()));
    assertEquals(Arrays.asList(classes, distJar), Arrays.asList(BinaryForSourceQuery.findBinaryRoots(src.toURL()).getRoots()));
    assertEquals(Collections.singletonList(testClasses), Arrays.asList(BinaryForSourceQuery.findBinaryRoots(test.toURL()).getRoots()));
    assertEquals(Arrays.asList(classes, distJar), Arrays.asList(BinaryForSourceQuery.findBinaryRoots(stuff.toURL()).getRoots()));
    assertEquals(Collections.singletonList(src.toURL()), Arrays.asList(UnitTestForSourceQuery.findSources(test)));
    assertEquals(Collections.singletonList(test.toURL()), Arrays.asList(UnitTestForSourceQuery.findUnitTests(src)));
    assertEquals("1.6", SourceLevelQuery.getSourceLevel(stuff));
    FileBuiltQuery.Status status = FileBuiltQuery.getStatus(xgen);
    assertNotNull(status);
    assertFalse(status.isBuilt());
    FileUtil.createData(d, "build/classes/net/nowhere/XGen.class");
    assertTrue(status.isBuilt());
    assertEquals("ISO-8859-2", FileEncodingQuery.getEncoding(xgen).name());
    // check also dynamic changes in set of gensrc roots:
    FileObject moreStuff = FileUtil.createFolder(d, "build/generated-sources/morestuff");
    FileObject ygen = FileUtil.createData(moreStuff, "net/nowhere/YGen.java");
    assertEquals(new HashSet<FileObject>(Arrays.asList(src, stuff, moreStuff)),
            new HashSet<FileObject>(Arrays.asList(SourceForBinaryQuery.findSourceRoots(classes).getRoots())));
    assertEquals(Arrays.asList(classes, distJar), Arrays.asList(BinaryForSourceQuery.findBinaryRoots(moreStuff.toURL()).getRoots()));
    // XXX should previously created Result objects fire changes? ideally yes, but probably unnecessary
    assertEquals("1.6", SourceLevelQuery.getSourceLevel(moreStuff));
    status = FileBuiltQuery.getStatus(ygen);
    assertNotNull(status);
    assertFalse(status.isBuilt());
    FileUtil.createData(d, "build/classes/net/nowhere/YGen.class");
    assertTrue(status.isBuilt());
    assertEquals("ISO-8859-2", FileEncodingQuery.getEncoding(ygen).name());
    d.getFileObject("build").delete();
    assertEquals(Arrays.asList(src), Arrays.asList(SourceForBinaryQuery.findSourceRoots(classes).getRoots()));
}
 
Example 20
Project: incubator-netbeans   File: RepositoryUpdaterTest.java   Source Code and License Vote up 4 votes
@Override
    protected void setUp() throws Exception {
//        TopLogging.initializeQuietly();
        super.setUp();
        this.clearWorkDir();
        final File _wd = this.getWorkDir();
        final FileObject wd = FileUtil.toFileObject(_wd);
        final FileObject cache = wd.createFolder("cache");
        CacheFolder.setCacheFolder(cache);
        RootsListener.setUseAsyncListneres(false);

        MockMimeLookup.setInstances(MimePath.EMPTY, binIndexerFactory);
//        MockMimeLookup.setInstances(MimePath.get(JARMIME), jarIndexerFactory);
        MockMimeLookup.setInstances(MimePath.get(MIME), indexerFactory);
        MockMimeLookup.setInstances(MimePath.get(EMIME), eindexerFactory, new EmbParserFactory());
        setMimeTypes(EMIME, MIME);

        assertNotNull("No masterfs",wd);
        srcRoot1 = wd.createFolder("src1");
        assertNotNull(srcRoot1);
        srcRoot2 = wd.createFolder("src2");
        assertNotNull(srcRoot2);
        srcRoot3 = wd.createFolder("src3");
        assertNotNull (srcRoot3);
        compRoot1 = wd.createFolder("comp1");
        assertNotNull (compRoot1);
        compRoot2 = wd.createFolder("comp2");
        assertNotNull (compRoot2);
        bootRoot1 = wd.createFolder("boot1");
        assertNotNull (bootRoot1);
        bootRoot2 = wd.createFolder("boot2");
        assertNotNull (bootRoot2);
        FileUtil.setMIMEType("jar", JARMIME);
        FileObject jarFile = FileUtil.toFileObject(getDataDir()).getFileObject("JavaApplication1.jar");
        assertNotNull(jarFile);
        assertTrue(FileUtil.isArchiveFile(jarFile));
        bootRoot3 = FileUtil.getArchiveRoot(jarFile);
        assertNotNull (bootRoot3);
        compSrc1 = wd.createFolder("cs1");
        assertNotNull (compSrc1);
        compSrc2 = wd.createFolder("cs2");
        assertNotNull (compSrc2);
        bootSrc1 = wd.createFolder("bs1");
        assertNotNull (bootSrc1);
        unknown1 = wd.createFolder("uknw1");
        assertNotNull (unknown1);
        unknown2 = wd.createFolder("uknw2");
        assertNotNull (unknown2);
        unknownSrc2 = wd.createFolder("uknwSrc2");
        assertNotNull(unknownSrc2);
        SFBQImpl.register (bootRoot1,bootSrc1);
        SFBQImpl.register (compRoot1,compSrc1);
        SFBQImpl.register (compRoot2,compSrc2);
        SFBQImpl.register (unknown2,unknownSrc2);

        srcRootWithFiles1 = wd.createFolder("srcwf1");
        assertNotNull(srcRootWithFiles1);
        FileUtil.setMIMEType("foo", MIME);
        f1 = FileUtil.createData(srcRootWithFiles1,"folder/a.foo");
        assertNotNull(f1);
        assertEquals(MIME, f1.getMIMEType());
        FileObject f2 = FileUtil.createData(srcRootWithFiles1,"folder/b.foo");
        assertNotNull(f2);
        assertEquals(MIME, f2.getMIMEType());
        customFiles = new URL[] {f1.toURL(), f2.toURL()};

        FileUtil.setMIMEType("emb", EMIME);
        f3 = FileUtil.createData(srcRootWithFiles1,"folder/a.emb");
        assertNotNull(f3);
        assertEquals(EMIME, f3.getMIMEType());
        FileObject f4 = FileUtil.createData(srcRootWithFiles1,"folder/b.emb");
        assertNotNull(f4);
        assertEquals(EMIME, f4.getMIMEType());
        embeddedFiles = new URL[] {f3.toURL(), f4.toURL()};


        waitForRepositoryUpdaterInit();
    }