Java Code Examples for org.openide.util.BaseUtilities#toFile()

The following examples show how to use org.openide.util.BaseUtilities#toFile() . 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: RootsListener.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@org.netbeans.api.annotations.common.SuppressWarnings(
value="DMI_COLLECTION_OF_URLS",
justification="URLs have never host part")
synchronized boolean addSource(
        @NonNull final URL root,
        @NullAllowed ClassPath.Entry entry) {
    if (sourcesListener != null) {
        if (!sourceRoots.containsKey(root) && root.getProtocol().equals("file")) { //NOI18N
            try {
                final File f = BaseUtilities.toFile(root.toURI());
                safeAddRecursiveListener(sourcesListener, f, entry);
                sourceRoots.put(root, f);
            } catch (URISyntaxException use) {
                LOG.log(Level.INFO, null, use);
            }
        }
    }
    return listens;
}
 
Example 2
Source File: OutputFileManager.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private File getClassFolderForApt(
           final Location l,
           final String baseName) {
       String[] parentName = splitParentName(baseName);
       final Collection<? extends URL> roots = getLocationRoots(l);
       for (ClassPath.Entry entry : this.apt.entries()) {
           FileObject root = entry.getRoot();
           if (root != null) {
               FileObject parentFile = root.getFileObject(parentName[0]);
               if (parentFile != null) {
                   if (parentFile.getFileObject(parentName[1], FileObjects.JAVA) != null) {
                       final URL classFolder = AptCacheForSourceQuery.getClassFolder(entry.getURL());
                       if (classFolder != null && roots.contains(classFolder)) {
                           try {
                               return BaseUtilities.toFile(classFolder.toURI());
                           } catch (URISyntaxException ex) {
                               Exceptions.printStackTrace(ex);
                           }
                       }
                   }
               }
           }
       }
return null;
   }
 
Example 3
Source File: CachingArchiveProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if the given boot classpath root has the the ct.sym equivalent.
 * @param root the root to check
 * @return true if there is a ct.sym folder corresponding to given boot classpath
 * root
 */
public boolean hasCtSym (@NonNull final URL root) {
    final URL fileURL = FileUtil.getArchiveFile(root);
    if (fileURL == null) {
        return false;
    }
    final File f;
    try {
        f = BaseUtilities.toFile(fileURL.toURI());
    } catch (URISyntaxException ex) {
        return false;
    }
    if (f == null || !f.exists()) {
        return false;
    }
    final Pair<File, String> res = mapJarToCtSym(f);
    return res.second() != null;

}
 
Example 4
Source File: StandardAntArtifactQueryImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public AntArtifact findArtifact(File file) {
    Project p = FileOwnerQuery.getOwner(BaseUtilities.toURI(file));
    if (p == null) {
        return null;
    }
    AntArtifactProvider prov = p.getLookup().lookup(AntArtifactProvider.class);
    if (prov == null) {
        return null;
    }
    AntArtifact[] artifacts = prov.getBuildArtifacts();
    for (int i = 0; i < artifacts.length; i++) {
        URI uris[] = artifacts[i].getArtifactLocations();
        for (int y = 0; y < uris.length; y++) {
            File testFile = BaseUtilities.toFile(BaseUtilities.toURI(artifacts[i].getScriptLocation()).resolve(uris[y]));
            if (file.equals(testFile)) {
                return artifacts[i];
            }
        }
    }
    return null;
}
 
Example 5
Source File: FileUtil.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Convert a classpath-type URL to a corresponding file.
 * If it is a <code>jar</code> URL representing the root folder of a local disk archive,
 * that archive file will be returned.
 * If it is a <code>file</code> URL representing a local disk folder,
 * that folder will be returned.
 * @param entry a classpath entry or similar URL
 * @return a corresponding file, or null for e.g. a network URL or non-root JAR folder entry
 * @since org.openide.filesystems 7.8
 */
public static File archiveOrDirForURL(URL entry) {
    final String u = entry.toString();
    if (isArchiveArtifact(entry)) {
        entry = getArchiveFile(entry);
        try {
            return u.endsWith("!/") && entry != null && "file".equals(entry.getProtocol()) ?  //NOI18N
                BaseUtilities.toFile(entry.toURI()):
                null;
        } catch (URISyntaxException e) {
            LOG.log(
                    Level.WARNING,
                    "Invalid URI: {0} ({1})",   //NOI18N
                    new Object[]{
                        entry,
                        e.getMessage()
                    });
            return null;
        }
    } else if (u.startsWith("file:")) { // NOI18N
        return BaseUtilities.toFile(URI.create(u));
    } else {
        return null;
    }
}
 
Example 6
Source File: CollocationQuery2Test.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public boolean areCollocated(URI uri1, URI uri2) {
    if (uri1.equals(uri2)) {
        return true;
    }
    File file1 = BaseUtilities.toFile(uri1);
    File file2 = BaseUtilities.toFile(uri2);
    String f1 = file1.getPath();
    if ((file1.isDirectory() || !file1.exists()) && !f1.endsWith(File.separator)) {
        f1 += File.separatorChar;
    }
    String f2 = file2.getAbsolutePath();
    if ((file2.isDirectory() || !file2.exists()) && !f2.endsWith(File.separator)) {
        f2 += File.separatorChar;
    }
    return f1.startsWith(f2) || f2.startsWith(f1);
}
 
Example 7
Source File: OutputFileManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private File getClassFolderForApt(final @NonNull URL surl) {
    for (ClassPath.Entry entry : apt.entries()) {
        if (FileObjects.isParentOf(entry.getURL(), surl)) {
            final URL classFolder = AptCacheForSourceQuery.getClassFolder(entry.getURL());
            if (classFolder != null) {
                try {
                    return BaseUtilities.toFile(classFolder.toURI());
                } catch (URISyntaxException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        }
    }
    return null;
}
 
Example 8
Source File: RootsListener.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@org.netbeans.api.annotations.common.SuppressWarnings(
value="DMI_COLLECTION_OF_URLS",
justification="URLs have never host part")
synchronized boolean addBinary(@NonNull final URL root) {
    if (binariesListener != null && !binaryRoots.containsKey(root)) {
        File f = null;
        final URL archiveUrl = FileUtil.getArchiveFile(root);
        try {
            final URI uri = archiveUrl != null ? archiveUrl.toURI() : root.toURI();
            if (uri.getScheme().equals("file")) { //NOI18N
                f = BaseUtilities.toFile(uri);
            }
        } catch (URISyntaxException use) {
            LOG.log (
                Level.INFO,
                "Can't convert: {0} to java.io.File, due to: {1}, (archive url: {2}).", //NOI18N
                new Object[]{
                    root,
                    use.getMessage(),
                    archiveUrl
                });
        }
        if (f != null) {
            if (archiveUrl != null) {
                // listening on an archive file
                safeAddFileChangeListener(binariesListener, f);
            } else {
                // listening on a folder
                safeAddRecursiveListener(binariesListener, f, null);
            }
            binaryRoots.put(root, Pair.of(f, archiveUrl != null));
        }
    }
    return listens;
}
 
Example 9
Source File: ProjectLibraryProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public ProjectLibraryArea loadArea(URL location) {
    if (location.getProtocol().equals("file") && location.getPath().endsWith(".properties")) { // NOI18N
        try {
            return new ProjectLibraryArea(BaseUtilities.toFile(location.toURI()));
        } catch (URISyntaxException x) {
            Exceptions.printStackTrace(x);
        }
    }
    return null;
}
 
Example 10
Source File: FileEncodingQueryTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testLongUnicode2 () throws IOException {
    URL url = FileEncodingQueryTest.class.getResource("data");        
    File dataFolder = BaseUtilities.toFile(URI.create(url.toExternalForm()));
    assertTrue(dataFolder.isDirectory());
    File dataFile = new File (dataFolder, "longUnicode2.txt");
    assertTrue (dataFile.exists());
    File test = new File(getWorkDir(), "longUnicode2.orig");
    copyToWorkDir(dataFile, test);
    FileObject from = FileUtil.toFileObject(test);
    assertNotNull(from);
    FileObject to = from.getParent().createData("longUnicode2","res");
    assertNotNull(to);
    copyFile (from, to);
    assertEquals (from, to);        
}
 
Example 11
Source File: FileEncodingQueryTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testLongUnicode () throws IOException {
    URL url = FileEncodingQueryTest.class.getResource("data");        
    File dataFolder = BaseUtilities.toFile(URI.create(url.toExternalForm()));
    assertTrue(dataFolder.isDirectory());
    File dataFile = new File (dataFolder, "longUnicode.txt");
    assertTrue (dataFile.exists());
    File test = new File(getWorkDir(), "longUnicode.orig");
    copyToWorkDir(dataFile, test);
    FileObject from = FileUtil.toFileObject(test);
    assertNotNull(from);
    FileObject to = from.getParent().createData("longUnicode","res");
    assertNotNull(to);
    copyFile (from, to);
    assertEquals (from, to);        
}
 
Example 12
Source File: JavadocRegistry.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Copied and modified from {@link org.netbeans.modules.java.classpath.SimplePathResourceImplementation}
 * @param root
 */
private static boolean verify(final URL root) {
    if (root == null) {
        return false;
    }
    final String rootS = root.toString();
    if (rootS.matches("file:.+[.]jar/?")) { //NOI18N
        File f = null;
        boolean dir = false;
        try {
            f = BaseUtilities.toFile(root.toURI());
            dir = f.isDirectory();
        } catch (URISyntaxException use) {
            //pass - handle as non dir
        }
        if (!dir) {
            //Special case for /tmp/build/.jar/ see issue #235695
            if (f == null || f.exists() || !f.getName().equals(".jar")) {   //NOI18N
                return false;
            }
        }
    }
    if (!rootS.endsWith("/")) {
        return false;
    }
    if (rootS.contains("/../") || rootS.contains("/./")) {  //NOI18N
        return false;
    }
    return true;
}
 
Example 13
Source File: MultiModuleFileBuiltQueryImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void collectRoots (
        @NonNull final MultiModule modules,
        @NonNull final String buildDirProp,
        @NonNull final List<? super String> from,
        @NonNull final List<? super String> to,
        @NonNull final Set<? super ClassPath> cps) {
    for (String moduleName : modules.getModuleNames()) {
        final String dest = String.format(
                "${%s}/%s/*.class", //NOI18N
                buildDirProp,
                moduleName);
        final ClassPath scp = modules.getModuleSources(moduleName);
        if (scp != null) {
            for (ClassPath.Entry e : scp.entries()) {
                try {
                    final File f = BaseUtilities.toFile(e.getURL().toURI());
                    String source = String.format(
                            "%s/*.java",       //NOI18N
                            f.getAbsolutePath());
                    from.add(source);
                    to.add(dest);
                } catch (IllegalArgumentException | URISyntaxException exc) {
                    LOG.log(
                            Level.WARNING,
                            "Cannot convert source root: {0} to file.", //NOI18N
                            e.getURL());
                }
            }
            cps.add(scp);
        }
    }
}
 
Example 14
Source File: LibrariesNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@CheckForNull
private static URL resolveAntArtifact(
        @NonNull final AntArtifact art,
        @NonNull final URI loc) {
    final FileObject prj = art.getProject().getProjectDirectory();
    final File f = BaseUtilities.toFile(prj.toURI().resolve(loc));
    return FileUtil.urlForArchiveOrDir(f);
}
 
Example 15
Source File: AbstractSourceFileObject.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
@NonNull
public final String toString () {
    final URI uri = toUri();
    try {
        final File file = BaseUtilities.toFile(uri);
        return file.getAbsolutePath();
    } catch (IllegalArgumentException iae) {
        return uri.toString();
    }
}
 
Example 16
Source File: JavaCustomIndexer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static Collection<? extends CompileTuple> translateVirtualSources(final Collection<? extends Indexable> virtualSources, final URL rootURL) throws IOException {
    if (virtualSources.isEmpty()) {
        return Collections.<CompileTuple>emptySet();
    }
    try {
        final File root = BaseUtilities.toFile(URI.create(rootURL.toString()));
        return VirtualSourceProviderQuery.translate(virtualSources, root);
    } catch (IllegalArgumentException e) {
        //Called on non local fs => not supported, log and ignore.
        JavaIndex.LOG.log(Level.WARNING, "Virtual sources in the root: {0} are ignored due to: {1}", new Object[]{rootURL, e.getMessage()}); //NOI18N
        return Collections.<CompileTuple>emptySet();
    }
}
 
Example 17
Source File: VersioningQueryTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public String getRemoteLocation(URI uri) {
    File file = BaseUtilities.toFile(uri);
    String path = file.getAbsolutePath();
    return path.endsWith(".vcs") ? uri.toString() : null;
}
 
Example 18
Source File: VersioningQueryTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isManaged(URI uri) {
    File file = BaseUtilities.toFile(uri);
    String path = file.getAbsolutePath();
    return path.endsWith(".vcs");
}
 
Example 19
Source File: J2SEActionProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@CheckForNull
private Boolean performUpdate(@NonNull final Context ctx) {
    final String target = getTarget();
    if (target != null) {
        final FileObject buildXml = owner.findBuildXml();
        if (buildXml != null) {
            if (checkImportantFiles(buildXml)) {
                try {
                    final FileObject cosScript = getCosScript();
                    final Iterable<? extends File> updated = ctx.getUpdated();
                    final Iterable<? extends File> deleted = ctx.getDeleted();
                    final File root = ctx.isCopyResources() ?
                            BaseUtilities.toFile(ctx.getSourceRoot().toURI()) :
                            ctx.getCacheRoot();
                    final String includes = createIncludes(root, updated);
                    if (includes != null) {
                        final Properties props = new Properties();
                        props.setProperty(PROP_TARGET, target);
                        props.setProperty(PROP_SCRIPT, FileUtil.toFile(buildXml).getAbsolutePath());
                        props.setProperty(PROP_SRCDIR, root.getAbsolutePath());
                        props.setProperty(PROP_INCLUDES, includes);
                        props.setProperty(COS_CUSTOM, getUpdatedFileSetProperty());
                        final Runnable work = () -> {
                            try {
                                final ExecutorTask task = runTargetInDedicatedTab(
                                        NbBundle.getMessage(J2SEActionProvider.class, "LBL_CompileOnSaveUpdate"),
                                        cosScript,
                                        new String[] {TARGET},
                                        props,
                                        null);
                                task.result();
                            } catch (IOException | IllegalArgumentException ex) {
                                LOG.log(
                                    Level.WARNING,
                                    "Cannot execute update targer: {0} in: {1} due to: {2}",   //NOI18N
                                    new Object[]{
                                        target,
                                        FileUtil.getFileDisplayName(buildXml),
                                        ex.getMessage()
                                    });
                            }
                        };
                        if (ctx.isAllFilesIndexing()) {
                            enqueueDeferred(work);
                        } else {
                            RUNNER.execute(work);
                        }
                    } else {
                        LOG.warning("BuildArtifactMapper artifacts do not provide attributes.");    //NOI18N
                    }
                } catch (IOException | URISyntaxException e) {
                    LOG.log(
                            Level.WARNING,
                            "Cannot execute update targer: {0} in: {1} due to: {2}",   //NOI18N
                            new Object[]{
                                target,
                                FileUtil.getFileDisplayName(buildXml),
                                e.getMessage()
                            });
                }
            }
        }
    }
    return true;
}
 
Example 20
Source File: ClassPath.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * The method returns the root folder represented by the Entry.
 * If the folder does not exist, or the folder is not readable,
 * the method may return null.
 * @return classpath entry root folder
 */
public  FileObject  getRoot() {
    FileObject _root = root.get();
    if (_root != null && _root.isValid()) {
        return _root;
    }
    for (int retryCount = 0; retryCount<=1; retryCount++) { //Bug 193086 : try to do refresh
        FileObject newRoot = URLMapper.findFileObject(this.url);
        _root = root.get();
        if (_root == null || !_root.isValid()) {
            if (newRoot == null) {
                this.lastError = new IOException(MessageFormat.format("The package root {0} does not exist or can not be read.",
                    new Object[] {this.url}));
                return null;
            } else if (isData(newRoot)) {
                if (retryCount == 0) {
                    Logger l = Logger.getLogger("org.netbeans.modules.masterfs"); // NOI18N
                    Level prev = l.getLevel();
                    try {
                        l.setLevel(Level.FINEST);
                        LOG.log(Level.WARNING, "Root is not folder {0}; about to refresh", newRoot); // NOI18N
                        newRoot.refresh();
                        FileObject parent = newRoot.getParent();
                        if (parent != null) {
                            LOG.log(Level.WARNING, "Refreshing its parent {0}", parent); // NOI18N
                            FileObject[] arr = parent.getChildren();
                            parent.refresh();
                        }
                    } finally {
                        l.setLevel(prev);
                        LOG.warning("End of refresh"); // NOI18N
                    }
                    continue;
                } else {
                    String fileState = null;
                    try {
                        final File file = BaseUtilities.toFile(this.url.toURI());
                        final boolean exists = file.exists();
                        final boolean isDirectory = file.isDirectory();
                        if (exists) {
                            if (isDirectory) {
                                fileState = "(exists: " +  exists +           //NOI18N
                                    " file: " + file.isFile() +             //NOI18N
                                    " directory: "+ isDirectory +    //NOI18N
                                    " read: "+ file.canRead() +             //NOI18N
                                    " write: "+ file.canWrite()+        //NOI18N
                                    " root: "+ _root +        //NOI18N
                                    " newRoot: "+ newRoot +")";        //NOI18N
                            } else {
                                LOG.log(
                                    Level.WARNING,
                                    "Ignoring non folder root : {0} on classpath ", //NOI18N
                                    file);
                                return null;
                            }
                        } else {
                            if (newRoot.isValid()) {
                                LOG.log(
                                    Level.WARNING,
                                    "URL mapper returned a valid FileObject for non existent File : {0}, ignoring.", //NOI18N
                                    file);
                                return null;
                            } else {
                                LOG.log(
                                    Level.WARNING,
                                    "URL mapper returned an invalid FileObject : {0}, ignoring.", //NOI18N
                                    file);
                                return null;
                            }
                        }
                    } catch (IllegalArgumentException | URISyntaxException e) {
                        //Non local file - keep file null (not log file state)
                    }
                    throw new IllegalArgumentException ("Invalid ClassPath root: "+this.url+". The root must be a folder." + //NOI18N
                            (fileState != null ? fileState : ""));
                }
            } else {
                if (!root.compareAndSet(_root, newRoot)) {
                    newRoot = root.get();
                }
                return newRoot;
            }
        } else {
            return _root;
        }
    }
    return null;
}