Java Code Examples for org.openide.filesystems.URLMapper#findFileObject()

The following examples show how to use org.openide.filesystems.URLMapper#findFileObject() . 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: EditorContextImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static DataObject getDataObject (String url) {
    FileObject file;
    try {
        file = URLMapper.findFileObject (new URL (url));
    } catch (MalformedURLException e) {
        return null;
    }

    if (file == null) {
        return null;
    }
    try {
        return DataObject.find (file);
    } catch (DataObjectNotFoundException ex) {
        return null;
    }
}
 
Example 2
Source File: J2EEUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Updates project classpath with the JARs specified by the <code>urls</code>.
 * The classpath is not updated if the given reference class (<code>refClassName</code>)
 * is on the classpath.
 *
 * @param urls URLs of the JARs that should be added to the classpath.
 * @param refClassName name of the class that determines wheter the classpath
 * should be updated or not.
 * @param fileInProject file in the project whose classpath should be updated.
 * @return <code>true</code> if the classpath has been updated,
 * returns <code>false</code> otherwise.
 */
public static boolean updateProjectWithJARs(URL[] urls, String refClassName, FileObject fileInProject) {
    try {
        ClassPath classPath = ClassPath.getClassPath(fileInProject, ClassPath.EXECUTE);
        String resourceName = refClassName.replace('.', '/') + ".class"; // NOI18N
        FileObject fob = classPath.findResource(resourceName); // NOI18N
        if (fob == null) {
            List<ClassSource.Entry> cpEntries = new ArrayList<ClassSource.Entry>(urls.length);
            for (URL url : urls) {
                FileObject jar = URLMapper.findFileObject(url);
                if (jar != null) {
                    cpEntries.add(new ClassSourceResolver.JarEntry(FileUtil.toFile(jar)));
                }
            }
            return ClassPathUtils.updateProject(fileInProject, new ClassSource("", cpEntries)); // NOI18N
        }
    } catch (IOException ex) {
        Logger.getLogger(J2EEUtils.class.getName()).log(Level.INFO, ex.getMessage(), ex);
    }
    return false;
}
 
Example 3
Source File: LibrariesNode.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static SourceGroup createFileSourceGroup (File file, Collection<? super URL> rootsList) {
    Icon icon;
    Icon openedIcon;
    String displayName;
    final URL url = FileUtil.urlForArchiveOrDir(file);
    if (url == null) {
        return null;
    }
    else if ("jar".equals(url.getProtocol())) {  //NOI18N
        icon = openedIcon = ImageUtilities.loadImageIcon(ARCHIVE_ICON, false);
        displayName = file.getName();
    }
    else {                                
        icon = getFolderIcon (false);
        openedIcon = getFolderIcon (true);
        displayName = file.getAbsolutePath();
    }
    rootsList.add (url);
    FileObject root = URLMapper.findFileObject (url);
    if (root != null) {
        return new LibrariesSourceGroup (root,displayName,icon,openedIcon);
    }
    return null;
}
 
Example 4
Source File: SourceForBinaryQueryImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public synchronized FileObject[] getRoots () {
    if (this.cache == null) {
        // entry is not resolved so directly volume content can be searched for it:
        boolean contains = false;
        for (String type : CLASSPATH_VOLUMES) {
            if (this.lib.getContent(type).contains(entry)) {
                contains = true;
                break;
            }
        }

        if (contains) {
            List<FileObject> result = new ArrayList<FileObject>();
            for (URL u : lib.getContent(ServerLibraryTypeProvider.VOLUME_SOURCE)) {
                FileObject sourceRootURL = URLMapper.findFileObject(u);
                if (sourceRootURL != null) {
                    result.add(sourceRootURL);
                }
            }
            this.cache = result.toArray(new FileObject[result.size()]);
        } else {
            this.cache = new FileObject[0];
        }
    }
    return this.cache;
}
 
Example 5
Source File: DebuggerTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Line getLine(int line, String remoteFileName, SessionId id) {
    Breakpoint[] breakpoints = DebuggerManager.getDebuggerManager().getBreakpoints();
    for (Breakpoint breakpoint : breakpoints) {
        if (breakpoint instanceof TestLineBreakpoint) {
            TestLineBreakpoint lineBreakpoint = (TestLineBreakpoint) breakpoint;
            Line lineObj = lineBreakpoint.getLine();
            Lookup lkp = lineObj.getLookup();
            FileObject fo = lkp.lookup(FileObject.class);
            try {
                URL remoteURL = new URL(remoteFileName);
                FileObject remoteFo = URLMapper.findFileObject(remoteURL);
                if (remoteFo == fo && line == lineObj.getLineNumber() + 1) {
                    return lineObj;
                }
            } catch (MalformedURLException ex) {
                break;
            }
        }
    }
    return super.getLine(line, remoteFileName, id);
}
 
Example 6
Source File: XMLResultItem.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public CompletionDocumentation resolveLink(String link) {
    try {
        DescriptionSource target = src.resolveLink(link);
        if (target != null) {
            return new ExtDocum(target, null);
        }
        
        URL base = src.getContentURL();
        if (base == null) {
            // sorry, cannot resolve.
            return null;
        }
        
        URL targetURL = new URL(base, link);
        
        // leave the VM as soon as possible. This hack uses URLMappers
        // to find out whether URL (converted to FO and back) can be
        // represented outside the VM
        boolean external = true;
        FileObject f = URLMapper.findFileObject(targetURL);
        if (f != null) {
            external = URLMapper.findURL(f, URLMapper.EXTERNAL) != null;
        }
        return new URLDocum(targetURL, external);
    } catch (MalformedURLException ex) {
        Exceptions.printStackTrace(ex);
        return null;
    }
}
 
Example 7
Source File: ShellProjectUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Collects project modules and packages from them.
 * For each modules, provides a list of (non-empty) packages from that module.
 * @param project
 * @return 
 */
public static Map<String, Collection<String>>   findProjectModulesAndPackages(Project project) {
    Map<String, Collection<String>> result = new HashMap<>();
    if (project == null) {
        return result;
    }
    for (SourceGroup sg : org.netbeans.api.project.ProjectUtils.getSources(project).getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA)) {
        if (isNormalRoot(sg)) {
            URL u = URLMapper.findURL(sg.getRootFolder(), URLMapper.INTERNAL);
            BinaryForSourceQuery.Result r = BinaryForSourceQuery.findBinaryRoots(u);
            for (URL u2 : r.getRoots()) {
                String modName = SourceUtils.getModuleName(u2, true);
                if (modName != null) {
                    FileObject root = URLMapper.findFileObject(u);
                    Collection<String> pkgs = getPackages(root); //new HashSet<>();
                    if (!pkgs.isEmpty()) {
                        Collection<String> oldPkgs = result.get(modName);
                        if (oldPkgs != null) {
                            oldPkgs.addAll(pkgs);
                        } else {
                            result.put(modName, pkgs);
                        }
                    }
                }
            }
        }
    }
    return result;
}
 
Example 8
Source File: ActionFilterNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@CheckForNull
static FileObject rebase(
        @NonNull final FileObject binRoot,
        @NonNull final FileObject sourceTarget) {

    if (shouldIgnore(sourceTarget.toURI(), binRoot.toURI())) {
        return null;
    }
    final URL providedBinRootURL = (URL) sourceTarget.getAttribute("classfile-root");    //NOI18N
    final String providedBinaryName = (String) sourceTarget.getAttribute("classfile-binaryName");   //NOI18N
    if (providedBinRootURL != null && providedBinaryName != null) {
        final FileObject providedBinRoot = URLMapper.findFileObject(providedBinRootURL);
        if (binRoot.equals(providedBinRoot)) {
            return binRoot.getFileObject(providedBinaryName + SUBST);
        }
    } else {
        for (FileObject srcRoot : SourceForBinaryQuery.findSourceRoots(binRoot.toURL()).getRoots()) {
            if (FileUtil.isParentOf(srcRoot, sourceTarget)) {
                final FileObject[] newTarget = ActionUtils.regexpMapFiles(
                    new FileObject[]{sourceTarget},
                    srcRoot,
                    SRCDIRJAVA,
                    binRoot,
                    SUBST,
                    true);
                if (newTarget != null) {
                    return newTarget[0];
                }
            }
        }
    }
    if (FileUtil.isParentOf(binRoot, sourceTarget) || binRoot.equals(sourceTarget))  {
        return sourceTarget;
    }
    ignore(sourceTarget.toURI(), binRoot.toURI());
    return null;
}
 
Example 9
Source File: DeclarativeHintsTestBase.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static TestSuite suite(Class<?> clazz, String filePattern) {
    NbTestSuite result = new NbTestSuite();
    Pattern patt = Pattern.compile(filePattern);

    for (String test : listTests(clazz)) {
        if (!patt.matcher(test).matches()) {
            continue;
        }
        
        //TODO:
        URL testURL = clazz.getClassLoader().getResource(test);
        
        assertNotNull(testURL);

        FileObject testFO = URLMapper.findFileObject(testURL);

        assertNotNull(testFO);

        String hint = test.substring(0, test.length() - ".test".length()) + ".hint";
        URL hintURL = clazz.getClassLoader().getResource(hint);

        assertNotNull(hintURL);
        
        FileObject hintFO = URLMapper.findFileObject(hintURL);

        assertNotNull(hintFO);

        try {
            for (TestCase tc : TestParser.parse(testFO.asText("UTF-8"))) {
                result.addTest(new DeclarativeHintsTestBase(hintFO, testFO, tc));
            }
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
        }
    }

    return result;
}
 
Example 10
Source File: ArchiveURLMapperTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void doFunnyZipEntryNames(String file) throws Exception {
    File docx = new File(getWorkDir(), "ms-docx.jar");
    JarOutputStream jos = new JarOutputStream(new FileOutputStream(docx));
    ZipEntry entry = new ZipEntry(file);
    jos.putNextEntry(entry);
    jos.write("content".getBytes());
    jos.close();
    
    FileObject docxFO = URLMapper.findFileObject(Utilities.toURI(docx).toURL());
    assertNotNull(docxFO);
    assertTrue(FileUtil.isArchiveFile(docxFO));
    
    FileObject docxRoot = FileUtil.getArchiveRoot(docxFO);
    assertNotNull("Root found", docxRoot);
    FileObject content = docxRoot.getFileObject(file);
    assertNotNull("content.xml found", content);
    
    assertEquals("Has right bytes", "content", content.asText());
    
    CharSequence log = Log.enable("", Level.WARNING);
    URL u = URLMapper.findURL(content, URLMapper.EXTERNAL);
    InputStream is = u.openStream();
    byte[] arr = new byte[30];
    int len = is.read(arr);
    assertEquals("Len is content", "content".length(), len);
    assertEquals("OK", "content", new String(arr, 0, len));
    
    assertEquals("No warnings:\n" + log, 0, log.length());
    assertEquals(u.toString(), content, URLMapper.findFileObject(u));
}
 
Example 11
Source File: PersistenceManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized Breakpoint[] initBreakpoints () {
    Properties p = Properties.getDefault ().getProperties ("debugger").
        getProperties (DebuggerManager.PROP_BREAKPOINTS);
    Breakpoint[] breakpoints = (Breakpoint[]) p.getArray (
        "jpda", 
        new Breakpoint [0]
    );
    for (int i = 0; i < breakpoints.length; i++) {
        if (breakpoints[i] instanceof LineBreakpoint) {
            LineBreakpoint lb = (LineBreakpoint) breakpoints[i];
            try {
                FileObject fo = URLMapper.findFileObject(new URL(lb.getURL()));
                if (fo == null) {
                    // The file is gone - we should remove the breakpoint as well.
                    Breakpoint[] breakpoints2 = new Breakpoint[breakpoints.length - 1];
                    if (i > 0) {
                        System.arraycopy(breakpoints, 0, breakpoints2, 0, i);
                    }
                    if (i < breakpoints2.length) {
                        System.arraycopy(breakpoints, i + 1, breakpoints2, i, breakpoints2.length - i);
                    }
                    breakpoints = breakpoints2;
                    i--;
                    continue;
                }
            } catch (MalformedURLException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
        breakpoints[i].addPropertyChangeListener(this);
    }
    this.breakpoints = breakpoints;
    return breakpoints;
}
 
Example 12
Source File: TemplateManager.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
public static FileObject getRootFolder() {
    URL location = AndroidTemplateLocator.class.getProtectionDomain().getCodeSource().getLocation();
    FileObject fo = URLMapper.findFileObject(location);
    FileObject archiveFile = FileUtil.getArchiveRoot(fo);
    if (archiveFile == null && fo.isRoot()) {
        archiveFile = fo;
    }
    return archiveFile.getFileObject("/android/studio/imports/templates/");
}
 
Example 13
Source File: ProfileSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@NonNull
private Union2<Profile,String> findProfileInManifest(@NonNull URL root) {
    final ArchiveCache ac = context.getArchiveCache();
    Union2<Profile,String> res;
    final ArchiveCache.Key key = ac.createKey(root);
    if (key != null) {
        res = ac.getProfile(key);
        if (res != null) {
            return res;
        }
    }
    String profileName = null;
    final FileObject rootFo = URLMapper.findFileObject(root);
    if (rootFo != null) {
        final FileObject manifestFile = rootFo.getFileObject(RES_MANIFEST);
        if (manifestFile != null) {
            try {
                try (InputStream in = manifestFile.getInputStream()) {
                    final Manifest manifest = new Manifest(in);
                    final Attributes attrs = manifest.getMainAttributes();
                    profileName = attrs.getValue(ATTR_PROFILE);
                }
            } catch (IOException ioe) {
                LOG.log(
                    Level.INFO,
                    "Cannot read Profile attribute from: {0}", //NOI18N
                    FileUtil.getFileDisplayName(manifestFile));
            }
        }
    }
    final Profile profile = Profile.forName(profileName);
    res = profile != null ?
            Union2.<Profile,String>createFirst(profile) :
            Union2.<Profile,String>createSecond(profileName);
    if (key != null) {
        ac.putProfile(key, res);
    }
    return res;
}
 
Example 14
Source File: GroovyLineBreakpointFactory.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static FileObject getFileObjectFromUrl(String url) {

        FileObject fo = null;

        try {
            fo = URLMapper.findFileObject(new URL(url));
        } catch (MalformedURLException e) {
            //noop
        }
        return fo;
    }
 
Example 15
Source File: WhiteListIndexerPlugin.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public JavaIndexerPlugin create(final URL root, final FileObject cacheFolder) {
    try {
        File whiteListDir = roots2whiteListDirs.get(root);
        if (whiteListDir == null) {
            //First time
            final FileObject whiteListFolder = FileUtil.createFolder(cacheFolder, WHITE_LIST_INDEX);
            whiteListDir = FileUtil.toFile(whiteListFolder);
            if (whiteListDir == null) {
                return null;
            }
        }
        final FileObject rootFo = URLMapper.findFileObject(root);
        if (rootFo == null) {
            delete(whiteListDir);
            return null;
        } else {
            final WhiteListQuery.WhiteList wl = WhiteListQuery.getWhiteList(rootFo);
            if (wl == null) {
                return null;
            }
            return new WhiteListIndexerPlugin(
                root,
                wl,
                whiteListDir);
        }
    } catch (IOException ioe) {
        Exceptions.printStackTrace(ioe);
        return null;
    }
}
 
Example 16
Source File: J2SELibrarySourceLevelQueryImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private FileObject getClassFile (List cpRoots) {
    for (Iterator<URL> it = cpRoots.iterator(); it.hasNext();) {
        FileObject root = URLMapper.findFileObject(it.next());
        if (root == null) {
            continue;
        }
        FileObject cf = findClassFile (root);
        if (cf != null) {
            return cf;
        }
    }
    return null;
}
 
Example 17
Source File: SourceForBinaryQueryImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Result findSourceRoots(URL binaryRoot) {
    if (FileUtil.getArchiveFile(binaryRoot) != null) {
        binaryRoot = FileUtil.getArchiveFile(binaryRoot);
    }
    SourceForBinaryQuery.Result res = cache.get(binaryRoot.toExternalForm());
    if (res != null) {
        return res;
    }

    FileObject fo = URLMapper.findFileObject(binaryRoot);
    if (fo == null || fo.isFolder()) {
        return null;
    }

    String buildDir = p.evaluator().evaluate("${build.dir}/lib");
    if (buildDir == null) {
        return null;
    }
    FileObject libRoot = p.getAntProjectHelper().resolveFileObject(buildDir);
    if (libRoot == null) {
        return null;
    }
    if (!fo.getParent().equals(libRoot)) {
        return null;
    }
    String libFile = fo.getNameExt();

    for (Project subProject : p.getLookup().lookup(SubprojectProvider.class).getSubprojects()) {
        SourceGroup sgp[] = ProjectUtils.getSources(subProject).getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
        if (sgp.length == 0) {
            continue;
        }
        ClassPath cp = ClassPath.getClassPath(sgp[0].getRootFolder(), ClassPath.COMPILE);
        if (cp == null) {
            continue;
        }
        for (ClassPath.Entry entry : cp.entries()) {
            URL u = entry.getURL();
            if (FileUtil.getArchiveFile(u) != null) {
                u = FileUtil.getArchiveFile(u);
            }
            // #213372:
            if (u.toExternalForm().equals(binaryRoot.toExternalForm())) {
                continue;
            }
            FileObject cpItem = URLMapper.findFileObject(u);
            if (cpItem == null || cpItem.isFolder()) {
                continue;
            }
            if (cpItem.getNameExt().equals(libFile)) {
                res = SourceForBinaryQuery.findSourceRoots(entry.getURL());
                if (res != null) {
                    cache.put(binaryRoot.toExternalForm(), res);
                    return res;
                }
            }
        }
    }

    return null;
}
 
Example 18
Source File: URLCache.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@CheckForNull
public FileObject findFileObject(
        final @NonNull URL url,
        final boolean validate) {
    URI uri = null;
    try {
        uri  = url.toURI();
    } catch (URISyntaxException e) {
        Exceptions.printStackTrace(e);
    }
    FileObject f = null;
    if (uri != null) {
        Reference<FileObject> ref = cache.get(uri);
        if (ref != null) {
            f = ref.get();
        }
        if (f != null && f.isValid() && (!validate || f.toURI().equals(uri))) {
            if (LOG.isLoggable(Level.FINEST)) {
                LOG.log(
                    Level.FINEST,
                    "Found: {0} in cache for: {1}", //NOI18N
                    new Object[]{
                        f,
                        url
                    });
            }
            return f;
        }
    }

    f = URLMapper.findFileObject(url);

    if (uri != null && f != null && f.isValid()) {
        if (LOG.isLoggable(Level.FINEST)) {
            LOG.log(
               Level.FINEST,
               "Caching: {0} for: {1}", //NOI18N
               new Object[]{
                   f,
                   url
               });
        }
        cache.put(uri, new CleanReference(f,uri));
    }

    return f;
}
 
Example 19
Source File: BinaryForSourceQuery2Test.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public PrivateData findBinaryRoots2(URL sourceRoot) {
    final FileObject fo = URLMapper.findFileObject(sourceRoot);
    assertNotNull("FileObject found", fo);
    return new PrivateData(sourceRoot, fo);
}
 
Example 20
Source File: ArchiveRootProvider.java    From netbeans with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a FileObject representing the root folder of an archive.
 * Clients may need to first call {@link #isArchiveFile(FileObject)} to determine
 * if the file object refers to an archive file.
 * The default implementation delegates to {@link ArchiveRootProvider#getArchiveRoot(URL)},
 * it can be overridden by an implementation in more efficient way.
 * @param fo an java archive file
 * @return a virtual archive root folder, or null if the file is not actually an archive
 */
default FileObject getArchiveRoot(FileObject fo) {
    final URL archiveURL = URLMapper.findURL(fo, URLMapper.EXTERNAL);
    if (archiveURL == null) {
        return null;
    }
    return URLMapper.findFileObject(FileUtil.getArchiveRoot(archiveURL));
}