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

The following examples show how to use org.openide.filesystems.FileObject#toURL() . 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: ProjectClassLoader.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@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 2
Source File: JavaBinaryIndexer.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static void preBuildArgs(
   @NonNull final FileObject root,
   @NonNull final FileObject file) throws IOException {
   
   final String relativePath = 
       FileObjects.convertFolder2Package(
           FileObjects.stripExtension(
               FileUtil.getRelativePath(root, file)));
   final TransactionContext txCtx = TransactionContext.beginTrans()
           .register(FileManagerTransaction.class, FileManagerTransaction.writeThrough())
           .register(ProcessorGenerated.class, ProcessorGenerated.nullWrite());
   try {
       final Collection<ClassPath.Entry> entries = JavaPlatform.getDefault().getBootstrapLibraries().entries();
       final URL[] roots = new URL[1+entries.size()];
       roots[0] = root.toURL();
       final Iterator<ClassPath.Entry> eit = entries.iterator();
       for (int i=1; eit.hasNext(); i++) {
           roots[i] = eit.next().getURL();
       }
       preBuildArgs(relativePath, roots);
   } finally {
       txCtx.commit();
   }
}
 
Example 3
Source File: DOMBreakpointCustomizer.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static DOMBreakpoint createBreakpoint() {
    Node node = Utilities.actionsGlobalContext().lookup(Node.class);
    DOMNode dn;
    URL url;
    if (node != null) {
        dn = DOMNode.create(node);
        url = DOMNode.findURL(node);
    } else {
        dn = DOMNode.create("[\u0003-1,]"); // root
        FileObject fo = Utilities.actionsGlobalContext().lookup(FileObject.class);
        if (fo == null) {
            fo = EditorContextDispatcher.getDefault().getMostRecentFile();
        }
        if (fo != null) {
            url = fo.toURL();
        } else {
            
            url = null;
        }
    }
    DOMBreakpoint b = new DOMBreakpoint(url, dn);
    return b;
}
 
Example 4
Source File: SourceForBinaryQueryImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private URL getNormalizedURL (URL url) {
    //URL is already nornalized, return it
    if (isNormalizedURL(url)) {
        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))
    URL normalizedURL = normalizedURLCache.get(url);
    if (normalizedURL == null) {
        FileObject fo = URLMapper.findFileObject(url);
        if (fo != null) {
            normalizedURL = fo.toURL();
            this.normalizedURLCache.put (url, normalizedURL);
        }
    }
    return normalizedURL;
}
 
Example 5
Source File: JavadocForBinaryQueryLibraryImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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 6
Source File: CustomIconEditor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
IconFileItem(FileObject file) {
    this.file = file;
    try {
        try {
            Image image = (file.getSize() < SIZE_LIMIT) ? ImageIO.read(file.toURL()) : null;
            icon = (image != null) ? new ImageIcon(image) : null;
        } catch (IllegalArgumentException iaex) { // Issue 178906
            Logger.getLogger(CustomIconEditor.class.getName()).log(Level.INFO, null, iaex);
            icon = new ImageIcon(file.toURL());
        }
    } catch (IOException ex) {
        Logger.getLogger(CustomIconEditor.class.getName()).log(Level.WARNING, null, ex);
    }
}
 
Example 7
Source File: RefreshAllIndexes.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("AssignmentToMethodParameter")
private FileObject findRoot(FileObject fobj, final Collection<? extends URL> roots) {
    while (fobj != null) {
        final URL url = fobj.toURL();
        if (roots.contains(url)) {
            return fobj;
        }
        fobj = fobj.getParent();
    }
    return null;
}
 
Example 8
Source File: AndroidStyleable.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
@Override
protected void query(CompletionResultSet resultSet, Document doc, int caretOffset) {
    //TODO code cleanup
    if (classFileURL == null) {
        //attempt to find the class in global classpath
        for (ClassPath cp : GlobalPathRegistry.getDefault().getPaths(ClassPath.COMPILE)) {
            FileObject f = cp.findResource(fullClassName.replace(".", "/") + ".class");
            if (f != null) {
                classFileURL = f.toURL();
                break;
            }
        }
        FileObject fo = GlobalPathRegistry.getDefault().findResource(fullClassName.replace(".", "/") + ".java");
        if (fo != null) {
            classFileURL = fo.toURL();
        }
    }
    if (classFileURL != null) {
        JavaSource javaSource = JavaSource.forFileObject(URLMapper.findFileObject(classFileURL));
        final CountDownLatch countDownLatch = new CountDownLatch(1);
        try {
            javaSource.runUserActionTask(new Task<CompilationController>() {
                @Override
                public void run(CompilationController p) throws Exception {
                    p.toPhase(Phase.ELEMENTS_RESOLVED);
                    List<? extends TypeElement> topLevelElements = p.getTopLevelElements();
                    ElementJavadoc javadoc = ElementJavadoc.create(p, topLevelElements.get(0));
                    resultSet.setDocumentation(new JavaDocItem(javadoc));
                    countDownLatch.countDown();
                }
            }, true);
            countDownLatch.await(10, TimeUnit.SECONDS);
        } catch (Exception ex) {
            Exceptions.printStackTrace(ex);
        }
    } else {
        resultSet.setDocumentation(new DocItem(createNotFoundJavaDoc()));
    }
    resultSet.finish();
}
 
Example 9
Source File: HtmlPreviewElement.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void reloadFromFile() {
    if( null == browser )
        return;

    final FileObject fileObject = lookup.lookup(FileObject.class);
    if( fileObject != null ) {
        URL url = fileObject.toURL();
        browser.setURL( url );
    }
}
 
Example 10
Source File: SourceFilesCache.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public URL getSourceFile(String name, long hash, URI uri, String content) throws IOException {
    String path = Long.toHexString(hash) + '/' + name;
    FileObject fo = fs.findResource(path);
    if (fo == null) {
        fo = fs.createFile(path, content);
        if (fo == null) {
            throw new IllegalArgumentException("Not able to create file with name '"+name+"'. Path = "+path);
        }
        fo.setAttribute(Source.ATTR_URI, uri);
    }
    return fo.toURL();
}
 
Example 11
Source File: ProfileSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
@CheckForNull
protected URL map(@NonNull final FileObject fo) {
    final String relative = FileObjects.convertFolder2Package(
            FileObjects.stripExtension(FileObjects.getRelativePath(cacheRoot, FileUtil.toFile(fo))), File.separatorChar);
    final FileObject sourceFile = SourceUtils.getFile(
        ElementHandleAccessor.getInstance().create(ElementKind.CLASS, relative),
        resolveCps);
    return sourceFile == null ? null : sourceFile.toURL();
}
 
Example 12
Source File: RepositoryUpdaterTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static void register (FileObject binRoot, FileObject sourceRoot) throws IOException {
    URL url = binRoot.toURL();
    map.put (url,sourceRoot);
    Result r = results.get (url);
    if (r != null) {
        r.update (sourceRoot);
    }
}
 
Example 13
Source File: FileObjectCrawler.java    From netbeans with Apache License 2.0 5 votes vote down vote up
FileObjectCrawler(
        @NonNull final FileObject root,
        @NullAllowed final FileObject[] files,
        final Set<? extends TimeStampAction> checkTimeStamps,
        @NullAllowed final ClassPath.Entry entry,
        @NonNull final CancelRequest cancelRequest,
        @NonNull final SuspendStatus suspendStatus) throws IOException {
    super (root.toURL(), checkTimeStamps, false, supportsAllFiles(root, files), cancelRequest, suspendStatus);
    this.root = root;
    this.entry = entry;
    this.files = files;
}
 
Example 14
Source File: BinaryForSourceQuery2Test.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testQuery2() throws Exception {
    MockServices.setServices(SampleQuery.class);
    SampleQuery sampleQuery = Lookup.getDefault().lookup(SampleQuery.class);
    assertNotNull("Instance of SampleQuery is registered", sampleQuery);

    FileSystem fs = FileUtil.createMemoryFileSystem();
    FileObject data = FileUtil.createData(fs.getRoot(), "fldr/data.txt");
    URL url = data.toURL();


    BinaryForSourceQuery.Result2 result = BinaryForSourceQuery.findBinaryRoots2(url);

    assertNotNull("Queried now", sampleQuery);
    assertTrue("prefers binaries", result.preferBinaries());

    URL[] roots = result.getRoots();
    assertEquals("One", 1, roots.length);
    assertEquals("Same", roots[0], url);

    SampleQuery.PrivateData privateData = (SampleQuery.PrivateData) BinaryForSourceQuery.CACHE.findRegistered(new SampleQuery.PrivateData(url, null));
    assertNotNull("Internal data found", privateData);

    ChangeListener listener = (ChangeEvent e) -> {};
    result.addChangeListener(listener);
    assertEquals(privateData.listener, listener);
    result.removeChangeListener(listener);
    assertNull(privateData.listener);

    BinaryForSourceQuery.Result2 result2 = BinaryForSourceQuery.findBinaryRoots2(url);
    assertSame("The result should be cached", result, result2);
}
 
Example 15
Source File: DeleteFile.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * 
 * @param fo
 * @param session
 */
public DeleteFile(FileObject fo, RefactoringElementsBag session) {
    this.res = fo.toURL();
    this.filename = fo.getNameExt();
    this.session = session;
}
 
Example 16
Source File: RepositoryUpdaterTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@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);
        bootRoot3 = wd.createFolder("boot3");
        assertNotNull (bootRoot3);
        
        FileUtil.setMIMEType("jar", JARMIME);
        jarFile = FileUtil.createData(bootRoot3, "JavaApplication1.jar");
        assertNotNull(jarFile);
        zipFileObject(jarFile);
        assertTrue(FileUtil.isArchiveFile(jarFile));
        
        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();
    }
 
Example 17
Source File: ProjectJAXWSClientSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public URL getCatalog() {
    FileObject catalog = getCatalogFileObject();
    return ((catalog==null) ? null : catalog.toURL());
}
 
Example 18
Source File: ProfileSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@CheckForNull
protected URL map(@NonNull final FileObject fo) {
    return fo.toURL();
}
 
Example 19
Source File: BuildArtifactMapperImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private Boolean performSync(@NonNull final Context ctx) throws IOException {
    final URL sourceRoot = ctx.getSourceRoot();
    final URL targetFolderURL = ctx.getTargetURL();
    final boolean copyResources = ctx.isCopyResources();
    final boolean keepResourceUpToDate = ctx.isKeepResourcesUpToDate();
    final Object context = ctx.getOwner();

    if (targetFolderURL == null) {
        return null;
    }

    final File targetFolder = FileUtil.archiveOrDirForURL(targetFolderURL);

    if (targetFolder == null) {
        return null;
    }

    try {
        SourceUtils.waitScanFinished();
    } catch (InterruptedException e) {
        //Not Important
        LOG.log(Level.FINE, null, e);
        return null;
    }

    if (JavaIndex.ensureAttributeValue(sourceRoot, DIRTY_ROOT, null)) {
        IndexingManager.getDefault().refreshIndexAndWait(sourceRoot, null);
    }

    if (JavaIndex.getAttribute(sourceRoot, DIRTY_ROOT, null) != null) {
        return false;
    }

    FileObject[][] sources = new FileObject[1][];

    if (!protectAgainstErrors(targetFolderURL, sources, context)) {
        return false;
    }
                
    File tagFile = new File(targetFolder, TAG_FILE_NAME);
    File tagUpdateResourcesFile = new File(targetFolder, TAG_UPDATE_RESOURCES);
    final boolean forceResourceCopy = copyResources && keepResourceUpToDate && !tagUpdateResourcesFile.exists();
    final boolean cosActive = tagFile.exists();
    if (cosActive && !forceResourceCopy) {
        return true;
    }

    if (!cosActive) {
        delete(targetFolder, false/*#161085: cleanCompletely*/);
    }

    if (!targetFolder.exists() && !targetFolder.mkdirs()) {
        throw new IOException("Cannot create destination folder: " + targetFolder.getAbsolutePath());
    }

    sources(targetFolderURL, sources);

    for (int i = sources[0].length - 1; i>=0; i--) {
        final FileObject sr = sources[0][i];
        if (!cosActive) {
            URL srURL = sr.toURL();
            File index = JavaIndex.getClassFolder(srURL, true);

            if (index == null) {
                //#181992: (not nice) ignore the annotation processing target directory:
                if (srURL.equals(AnnotationProcessingQuery.getAnnotationProcessingOptions(sr).sourceOutputDirectory())) {
                    continue;
                }

                return null;
            }

            copyRecursively(index, targetFolder);
        }

        if (copyResources) {
            Set<String> javaMimeTypes = COSSynchronizingIndexer.gatherJavaMimeTypes();
            String[]    javaMimeTypesArr = javaMimeTypes.toArray(new String[0]);

            copyRecursively(sr, targetFolder, javaMimeTypes, javaMimeTypesArr);
        }
    }

    if (!cosActive) {
        new FileOutputStream(tagFile).close();
    }

    if (keepResourceUpToDate)
        new FileOutputStream(tagUpdateResourcesFile).close();

    return true;
}
 
Example 20
Source File: PlatformJavadocForBinaryQuery.java    From netbeans with Apache License 2.0 2 votes vote down vote up
/**
 * Search for the actual root of the Javadoc containing the index-all.html or
 * index-files. In case when it is not able to find it, it returns the given Javadoc folder/file.
 * @param URL Javadoc folder/file
 * @return URL either the URL of folder containg the index or the given parameter if the index was not found.
 */
private static URL getIndexFolder (FileObject root) throws FileStateInvalidException {
    FileObject result = findIndexFolder (root);
    return result == null ? root.toURL() : result.toURL();
}