Java Code Examples for org.openide.filesystems.FileUtil#archiveOrDirForURL()

The following examples show how to use org.openide.filesystems.FileUtil#archiveOrDirForURL() . 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: DeclarativeHintsParser.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static ClassPath getJavacApiJarClasspath() {
    Reference<ClassPath> r = javacApiClasspath;
    ClassPath res = r.get();
    if (res != null) {
        return res;
    }
    if (r == NONE) {
        return null;
    }
    CodeSource codeSource = Modifier.class.getProtectionDomain().getCodeSource();
    URL javacApiJar = codeSource != null ? codeSource.getLocation() : null;
    if (javacApiJar != null) {
        Logger.getLogger(DeclarativeHintsParser.class.getName()).log(Level.FINE, "javacApiJar={0}", javacApiJar);
        File aj = FileUtil.archiveOrDirForURL(javacApiJar);
        if (aj != null) {
            res = ClassPathSupport.createClassPath(FileUtil.urlForArchiveOrDir(aj));
            javacApiClasspath = new WeakReference<>(res);
            return res;
        }
    }
    javacApiClasspath = NONE;
    return null;
}
 
Example 2
Source File: AbstractJavadocForBinaryQuery.java    From NBANDROID-V2 with Apache License 2.0 6 votes vote down vote up
@Override
public JavadocForBinaryQuery.Result findJavadoc(URL binaryRoot) {
    File binaryRootFile = FileUtil.archiveOrDirForURL(binaryRoot);
    if (binaryRootFile == null) {
        return null;
    }

    JavadocForBinaryQuery.Result result = cache.get(binaryRootFile);
    if (result != null) {
        return result;
    }

    result = tryFindJavadoc(binaryRootFile);
    if (result == null) {
        return null;
    }

    JavadocForBinaryQuery.Result oldResult = cache.putIfAbsent(binaryRootFile, result);
    return oldResult != null ? oldResult : result;
}
 
Example 3
Source File: AbstractSourceForBinaryQuery.java    From NBANDROID-V2 with Apache License 2.0 6 votes vote down vote up
@Override
public final Result findSourceRoots2(URL binaryRoot) {
    File binaryRootFile = FileUtil.archiveOrDirForURL(binaryRoot);
    if (binaryRootFile == null) {
        return null;
    }

    File normBinaryRoot = normalizeBinaryPath(binaryRootFile);
    if (normBinaryRoot == null) {
        return null;
    }

    Result result = cache.get(normBinaryRoot);
    if (result != null) {
        return result;
    }

    result = tryFindSourceRoot(normBinaryRoot);
    if (result == null) {
        return null;
    }

    Result oldResult = cache.putIfAbsent(normBinaryRoot, result);
    return oldResult != null ? oldResult : result;
}
 
Example 4
Source File: ProjectRunnerImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static FileObject buildScript(String actionName, boolean forceCopy) throws IOException {
    URL script = locateScript(actionName);

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

    URL thisClassSource = ProjectRunnerImpl.class.getProtectionDomain().getCodeSource().getLocation();
    File jarFile = FileUtil.archiveOrDirForURL(thisClassSource);
    File scriptFile = Places.getCacheSubfile("executor-snippets/" + actionName + ".xml");
    
    if (forceCopy || !scriptFile.canRead() || (jarFile != null && jarFile.lastModified() > scriptFile.lastModified())) {
        try {
            URLConnection connection = script.openConnection();
            FileObject target = FileUtil.createData(scriptFile);

            copyFile(connection, target);
            return target;
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
            return null;
        }
    }

    return FileUtil.toFileObject(scriptFile);
}
 
Example 5
Source File: ProjectRunnerImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@NonNull
private static String pathToString(@NonNull final ClassPath path) {
    final StringBuilder cpBuilder = new StringBuilder();
    for (ClassPath.Entry entry : path.entries()) {
        final URL u = entry.getURL();
        boolean folder = "file".equals(u.getProtocol());
        File f = FileUtil.archiveOrDirForURL(u);
        if (f != null) {
            if (cpBuilder.length() > 0) {
                cpBuilder.append(File.pathSeparatorChar);
            }
            cpBuilder.append(f.getAbsolutePath());
            if (folder) {
                cpBuilder.append(File.separatorChar);
            }
        }
    }
    return cpBuilder.toString();
}
 
Example 6
Source File: CPExtender.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public @Override boolean addRoots(final URL[] urls, SourceGroup grp, String type) throws IOException {
    final AtomicBoolean added = new AtomicBoolean();
    final String scope = findScope(grp, type);
    ModelOperation<POMModel> operation = new ModelOperation<POMModel>() {
        public @Override void performOperation(POMModel model) {
            for (URL url : urls) {
                File jar = FileUtil.archiveOrDirForURL(url);
                if (jar != null && jar.isFile()) {
                    try {
                        added.compareAndSet(false, addRemoveJAR(jar, model, scope, true));
                    } catch (IOException ex) {
                        Exceptions.printStackTrace(ex);
                    }
                } else {
                    Logger.getLogger(CPExtender.class.getName()).log(Level.INFO, "Adding non-jar root to Maven projects makes no sense. ({0})", url); //NOI18N
                }
            }
        }
    };
    FileObject pom = project.getProjectDirectory().getFileObject(POM_XML);//NOI18N
    org.netbeans.modules.maven.model.Utilities.performPOMModelOperations(pom, Collections.singletonList(operation));
    if (added.get()) {
        project.getLookup().lookup(NbMavenProject.class).triggerDependencyDownload();
    }
    return added.get();
}
 
Example 7
Source File: APTUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(@NonNull final URL url) {
    synchronized (this) {
        load();
        if (used == null || used == TOMBSTONE) {
            used = new LongHashMap<>();
        }
        final File f = FileUtil.archiveOrDirForURL(url);
        if (f != null) {
            final long size = f.isFile() ?
                    f.length() :
                    -1;
            if (!used.containsKey(f)) {
                used.put(f, size);
                saveTask.schedule(DEFERRED_SAVE);
            }
        }
    }
}
 
Example 8
Source File: APTUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@NonNull
private static StringBuilder append (
        @NonNull final StringBuilder builder,
        @NonNull final URL url) {
    final File f = FileUtil.archiveOrDirForURL(url);
    if (f != null) {
        if (builder.length() > 0) {
            builder.append(File.pathSeparatorChar);
        }
        builder.append(f.getAbsolutePath());
    } else {
        if (builder.length() > 0) {
            builder.append(File.pathSeparatorChar);
        }
        builder.append(url);
    }
    return builder;
}
 
Example 9
Source File: Hacks.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static Iterable<? extends File> toFiles(ClassPath cp) {
    List<File> result = new LinkedList<File>();

    for (Entry e : cp.entries()) {
        File f = FileUtil.archiveOrDirForURL(e.getURL());

        if (f == null) {
            Logger.getLogger(Hacks.class.getName()).log(Level.INFO, "file == null, url={0}", e.getURL());
            continue;
        }

        result.add(f);
    }

    return result;
}
 
Example 10
Source File: DeclarativeHintsTestBase.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static Collection<String> listTests(Class<?> clazz) {
    File dirOrArchive = FileUtil.archiveOrDirForURL(clazz.getProtectionDomain().getCodeSource().getLocation());

    assertTrue(dirOrArchive.exists());

    if (dirOrArchive.isFile()) {
        return listTestsFromJar(dirOrArchive);
    } else {
        Collection<String> result = new LinkedList<String>();

        listTestsFromFilesystem(dirOrArchive, "", result);

        return result;
    }
}
 
Example 11
Source File: PlatformComponentFactory.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public @Override Component getListCellRendererComponent(JList list, Object value,
        int index, boolean isSelected, boolean cellHasFocus) {
    URL u = (URL) value;
    File f = FileUtil.archiveOrDirForURL(u);
    String text = f != null ? f.getAbsolutePath() : u.toString();
    return super.getListCellRendererComponent(list, text, index, isSelected, cellHasFocus);
}
 
Example 12
Source File: JSFUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Use {@link JSFVersion#get(org.netbeans.modules.web.api.webmodule.WebModule, boolean) } instead.
 */
@Deprecated
private static boolean isJSFPlus(WebModule webModule, boolean includingPlatformCP, String versionSpecificClass) {
    if (webModule == null) {
        return false;
    }

    final ClassPath compileCP = ClassPath.getClassPath(webModule.getDocumentBase(), ClassPath.COMPILE);
    if (compileCP == null) {
        return false;
    }

    if (includingPlatformCP) {
        return compileCP.findResource(versionSpecificClass.replace('.', '/') + ".class") != null; //NOI18N
    } else {
        Project project = FileOwnerQuery.getOwner(getFileObject(webModule));
        if (project == null) {
            return false;
        }
        List<File> platformClasspath = Arrays.asList(ClasspathUtil.getJ2eePlatformClasspathEntries(project, ProjectUtil.getPlatform(project)));
        List<URL> projectDeps = new ArrayList<URL>();
        for (ClassPath.Entry entry : compileCP.entries()) {
            File archiveOrDir = FileUtil.archiveOrDirForURL(entry.getURL());
            if (archiveOrDir == null || !platformClasspath.contains(archiveOrDir)) {
                projectDeps.add(entry.getURL());
            }
        }
        try {
            return ClasspathUtil.containsClass(projectDeps, versionSpecificClass); //NOI18N
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    return false;
}
 
Example 13
Source File: GeneratedFilesHelper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Find the time the file this URL represents was last modified xor its size, if possible. */
private static long checkFootprint(URL u) {
    File f = FileUtil.archiveOrDirForURL(u);
    if (f != null) {
        return f.lastModified() ^ f.length();
    } else {
        return 0L;
    }
}
 
Example 14
Source File: GradleSourceForBinaryQuery.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
private List<FileObject> update() {
    Result r = findAarLibraryRoots(binaryRoot);
    if (r != null) {
        return Collections.EMPTY_LIST;
    }
    if (androidProjectModel == null) {
        return Collections.EMPTY_LIST;
    }
    final File binRootDir = FileUtil.archiveOrDirForURL(binaryRoot);
    if (binRootDir == null) {
        return null;
    }

    Variant variant = Iterables.find(
            androidProjectModel.getVariants(),
            new Predicate<Variant>() {
        @Override
        public boolean apply(Variant input) {
            return binRootDir.equals(input.getMainArtifact().getClassesFolder());
        }
    },
            null);
    if (variant != null) {
        Iterable<FileObject> srcRoots = Iterables.filter(
                Iterables.transform(
                        sourceRootsForVariant(variant),
                        new Function<File, FileObject>() {
                    @Override
                    public FileObject apply(File f) {
                        return FileUtil.toFileObject(f);
                    }
                }),
                Predicates.notNull());
        return Lists.newArrayList(srcRoots);
    }
    return Collections.EMPTY_LIST;
}
 
Example 15
Source File: SelectRootsPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@NonNull
private static String getDisplayName(@NonNull final URL root) {
    final File f = FileUtil.archiveOrDirForURL(root);
    return f == null ?
        root.toString() :
        f.isFile() ?
            f.getName() :
            f.getAbsolutePath();
}
 
Example 16
Source File: ApplVisualPanel1.java    From nb-springboot with Apache License 2.0 5 votes vote down vote up
private void updateResourceFolder(boolean isTest) {
    final URI[] resources = nbProj.getResources(isTest);
    if (resources.length > 0) {
        try {
            resourceFolder = FileUtil.archiveOrDirForURL(resources[0].toURL());
        } catch (MalformedURLException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
}
 
Example 17
Source File: DebugPluginSourceAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void doLoad(final AtomicBoolean cancel) {
        URL[] urls = mojo.getClasspathURLs();
        String impl = mojo.getImplementationClass();
        if (urls != null) {
            List<URL> normalizedUrls = new ArrayList<URL>();
            //first download the source files for the binaries..
            MavenSourceJavadocAttacher attacher = new MavenSourceJavadocAttacher();
            for (URL url : urls) {
                //the urls are not normalized and can contain ../ path parts
                try {
                    url = FileUtil.urlForArchiveOrDir(FileUtil.normalizeFile(Utilities.toFile(url.toURI())));
                    if (url == null) {
                        continue; //#242324
                    }
                    normalizedUrls.add(url);
                    List<? extends URL> ret = attacher.getSources(url, new Callable<Boolean>() {
                        @Override
                        public Boolean call() throws Exception {
                            return cancel.get();
                        }
                    });
                    SourceForBinaryQuery.Result2 result = SourceForBinaryQuery.findSourceRoots2(url);
                    if (result.getRoots().length == 0 && !ret.isEmpty()) {
                        //binary not in repository, we need to hardwire the mapping here to have sfbq pick it up.
                        Set<File> fls = new HashSet<File>();
                        for (URL u : ret) {
                            File f = FileUtil.archiveOrDirForURL(u);
                            if (f != null) {
                                fls.add(f);
                            }
                        }
                        if (!fls.isEmpty()) {
                            SourceJavadocByHash.register(url, fls.toArray(new File[0]), false);
                        }
                    }
                    if (cancel.get()) {
                        return;
                    }
                } catch (URISyntaxException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
            if (cancel.get()) {
                return;
            }
            ClassPath cp = Utils.convertToSourcePath(normalizedUrls.toArray(new URL[0]));
            RunConfig clone = RunUtils.cloneRunConfig(config);
            clone.setInternalProperty("jpda.additionalClasspath", cp);
            clone.setInternalProperty("jpda.stopclass", impl);
//stop method sometimes doesn't exist when inherited
            clone.setInternalProperty("jpda.stopmethod", "execute");
            clone.setProperty(Constants.ACTION_PROPERTY_JPDALISTEN, "maven");
            if (cancel.get()) {
                return;
            }
            RunUtils.run(clone);
        }
    }
 
Example 18
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 19
Source File: GlobalSourceForBinaryImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public FileObject[] getRoots() {
    final List<FileObject> candidates = new ArrayList<FileObject>();
    try {
        for (URL root : srp.getSourceRoots()) {
            if (root.getProtocol().equals("jar")) { // NOI18N
                // suppose zipped sources
                File nbSrcF = FileUtil.archiveOrDirForURL(root);
                if (nbSrcF == null || !nbSrcF.exists()) {
                    continue;
                }
                NetBeansSourcesParser nbsp;
                try {
                    nbsp = NetBeansSourcesParser.getInstance(nbSrcF);
                } catch (ZipException e) {
                    if (!quiet) {
                        Util.err.annotate(e, ErrorManager.UNKNOWN, nbSrcF + " does not seem to be a valid ZIP file.", null, null, null); // NOI18N
                        Util.err.notify(ErrorManager.INFORMATIONAL, e);
                    }
                    continue;
                }
                if (nbsp == null) {
                    continue;
                }
                String pathInZip = nbsp.findSourceRoot(cnb);
                if (pathInZip == null) {
                    continue;
                }
                URL u = new URL(root, pathInZip);
                FileObject entryFO = URLMapper.findFileObject(u);
                if (entryFO != null) {
                    candidates.add(entryFO);
                }
            } else {
                // Does not resolve nbjunit and similar from ZIPped
                // sources. Not a big issue since the default distributed
                // sources do not contain them anyway.
                String relPath = resolveRelativePath(root);
                if (relPath == null) {
                    continue;
                }
                URL url = new URL(root, relPath);
                FileObject dir = URLMapper.findFileObject(url);
                if (dir != null) {
                    candidates.add(dir);
                } // others dirs are currently resolved by o.n.m.apisupport.project.queries.SourceForBinaryImpl
            }
        }
    } catch (IOException ex) {
        throw new AssertionError(ex);
    }
    return candidates.toArray(new FileObject[candidates.size()]);
}