Java Code Examples for org.openide.filesystems.FileSystem#findResource()

The following examples show how to use org.openide.filesystems.FileSystem#findResource() . 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: LayerUtilsTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testXMLMultiFS() throws Exception {
    clearWorkDir();
    // b-layer.xml overrides a-layer.xml now and then:
    List<File> files = new ArrayList<File>(Arrays.asList(
            new File(getDataDir(), "layers/b-layer.xml"),
            new File(getDataDir(), "layers/a-layer.xml")
            ));

    FileSystem xfs0 = new XMLFileSystem(Utilities.toURI(files.get(0)).toURL());
    FileSystem xfs1 = new XMLFileSystem(Utilities.toURI(files.get(1)).toURL());
    FileSystem mfs = new MultiFileSystem(xfs0, xfs1);
    assertNotNull(xfs1.findResource("Menu/A Folder"));
    assertNotNull(mfs.findResource("Menu/File"));
    assertNotNull(mfs.findResource("Menu/A Folder"));
    assertNull(mfs.findResource("Menu/A Folder/org-example-a-AAction.shadow"));  // hidden by b-layer
    FileObject mf = mfs.findResource("Actions/File");
    assertEquals(2, mf.getChildren().length);
    FileObject ba = mfs.findResource("Actions/File/org-example-b-BAction.instance");
    assertEquals("BBBBB", ba.getAttribute("displayName"));
    FileObject aa = mfs.findResource("Actions/File/org-example-a-AAction.instance");
    assertEquals("AAAA", aa.getAttribute("displayName"));
}
 
Example 2
Source File: WritableXMLFileSystemTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testNBResLocURL() throws Exception {
    Map<String, String> files = new HashMap<String, String>();
    files.put("org/test/x.txt", "stuff");
    files.put("org/test/resources/y.txt", "more stuff");
    Layer orig = new Layer("<file name='x' url='nbres:/org/test/x.txt'/><file name='y' url='nbresloc:/org/test/resources/y.txt'/>", files);
    FileObject orgTest = FileUtil.createFolder(new File(orig.folder, "org/test"));
    FileObject lf = orig.f.copy(orgTest, "layer", "xml");
    SavableTreeEditorCookie cookie = LayerUtils.cookieForFile(lf);
    FileSystem fs = new WritableXMLFileSystem(lf.toURL(), cookie,
            ClassPathSupport.createClassPath(new FileObject[] { FileUtil.toFileObject(orig.folder) } ));
    FileObject x = fs.findResource("x");
    assertNotNull(x);
    assertTrue(x.isData());
    assertEquals(5L, x.getSize());
    assertEquals("stuff", x.asText("UTF-8"));

    FileObject y = fs.findResource("y");
    assertNotNull(y);
    assertTrue(y.isData());
    assertEquals(10L, y.getSize());
    assertEquals("more stuff", y.asText("UTF-8"));
}
 
Example 3
Source File: LayerUtilsTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testMasks() throws Exception {
        NbModuleProject project = TestBase.generateStandaloneModule(getWorkDir(), "module");
        FileSystem fs = LayerUtils.getEffectiveSystemFilesystem(project);
        Set<String> optionInstanceNames = new HashSet<String>();
        FileObject toolsMenu = fs.findResource("Menu/Tools");
        assertNotNull(toolsMenu);
        for (FileObject kid : toolsMenu.getChildren()) {
            String name = kid.getNameExt();
            if (name.contains("Options") && !name.contains("separator")) {
                optionInstanceNames.add(name);
            }
        }
        assertEquals("#63295: masks work",
                new HashSet<String>(Arrays.asList(
            "org-netbeans-modules-options-OptionsWindowAction.shadow"
            // org-netbeans-core-actions-OptionsAction.instance should be masked
        )), optionInstanceNames);
// catalogs registered by annotation
//        assertNotNull("system FS has xml/catalog", fs.findResource("Services/Hidden/CatalogProvider/org-netbeans-modules-xml-catalog-impl-XCatalogProvider.instance"));
        assertNull("but one entry hidden by apisupport/project", fs.findResource("Services/Hidden/org-netbeans-modules-xml-catalog-impl-SystemCatalogProvider.instance"));
    }
 
Example 4
Source File: CopyFilesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Test
   public void testCopyDeep() throws Exception {
ArrayList<String> fileList = new ArrayList<String>();
fileList.addAll(Arrays.asList(new java.lang.String[]{"source/foo/X.txt",
	    "source/foo/A.txt", "source/foo/B.txt", "source/foo/foo2/C.txt"}));

FileSystem fs = createLocalFileSystem(fileList.toArray(new String[fileList.size()]));

FileObject path = fs.findResource("source");
assertNotNull(path);
FileObject tg = fs.getRoot().createFolder("target");
assertNotNull(tg);
FileObject patterns = FileUtil.createData(fs.getRoot(), "source/foo/etc/patterns.import");
assertNotNull(patterns);
String pattern = "# ignore comment\n"
	+ "include foo/.*\n"
	+ "translate foo=>bar\n";
writeTo(fs, "source/foo/etc/patterns.import", pattern);

org.netbeans.upgrade.CopyFiles.copyDeep(FileUtil.toFile(path), FileUtil.toFile(tg), FileUtil.toFile(patterns));

assertNotNull("file not copied: " + "foo/X.txt", tg.getFileObject("bar/X.txt"));
assertNotNull("file not copied: " + "foo/A.txt", tg.getFileObject("bar/A.txt"));
assertNotNull("file not copied: " + "foo/B.txt", tg.getFileObject("bar/B.txt"));
assertNotNull("file not copied: " + "foo/foo2/C.txt", tg.getFileObject("bar/foo2/C.txt"));
   }
 
Example 5
Source File: I18nOptions.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static FileObject findFileObject(DataObject srcDataObject, String path) {
    FileObject pfo = srcDataObject.getPrimaryFile();
    ClassPath cp = ClassPath.getClassPath(pfo, ClassPath.EXECUTE);

    // #167334
    if(cp == null) {
        LOG.info("Unable to find FileObject due to ClassPath is null");
        return null;
    }

    for(FileObject fo : getRoots(cp)) {
        try {
            FileSystem fs = fo.getFileSystem();
            if (fs != null) {
                FileObject retval = fs.findResource(path);
                if (retval != null) {
                    return retval;
                }
            }
        } catch (FileStateInvalidException ex) {
            LOG.log(Level.INFO, null, ex);
        }
    }
    
    return null;
}
 
Example 6
Source File: Util.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new PropertiesDataObject (properties file).
 * @param folder FileObject folder where to create the properties file
 * @param fileName String name of the file without the extension, can include
 *        relative path underneath the folder
 * @return created PropertiesDataObjet
 */
public static PropertiesDataObject createPropertiesDataObject(FileObject folder, String fileName)
    throws IOException
{
    int idx = fileName.lastIndexOf('/');
    if (idx > 0) {
        String folderPath = fileName.substring(0, idx);
        folder = FileUtil.createFolder(folder, folderPath);
        fileName = fileName.substring(idx + 1);
    }
    FileSystem defaultFS = Repository.getDefault().getDefaultFileSystem();
    FileObject templateFO = defaultFS.findResource("Templates/Other/properties.properties"); // NOI18N
    DataObject template = DataObject.find(templateFO);
    return (PropertiesDataObject)
           template.createFromTemplate(DataFolder.findFolder(folder), fileName);
}
 
Example 7
Source File: LocalFileSystemEx133616Test.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Simulates deadlock issue 133616
 * - create MultiFileSystem
 * - create lookup to set our MultiFileSystem and system filesystem
 * - create handler to manage threads
 * - put test FileObject to 'potentialLock' set
 * - call hasLocks
 *   - it call LocalFileSystemEx.getInvalid which ends in our DeadlockHandler
 *   - it starts lockingThread which calls FileObject.lock which locks our FileObject
 *   - when we in LocalFileSystemEx.lock, we notify main thread which continues
 *     in getInvalid and tries to accuire lock on FileObject and it dead locks
 */
public void testLocalFileSystemEx133616() throws Exception {
    System.setProperty("workdir", getWorkDirPath());
    clearWorkDir();

    FileSystem lfs = TestUtilHid.createLocalFileSystem("mfs1" + getName(), new String[]{"/fold/file1"});
    LocalFileSystemEx exfs = new LocalFileSystemEx();
    exfs.setRootDirectory(FileUtil.toFile(lfs.getRoot()));
    FileSystem xfs = TestUtilHid.createXMLFileSystem(getName(), new String[]{});
    FileSystem mfs = new MultiFileSystem(exfs, xfs);
    testedFS = mfs;
    Lookup l = Lookup.getDefault();
    if (!(l instanceof Lkp)) {
        fail("Wrong lookup: " + l);
    }
    ((Lkp)l).init();

    final FileObject file1FO = mfs.findResource("/fold/file1");
    File file1File = FileUtil.toFile(file1FO);

    Logger.getLogger(LocalFileSystemEx.class.getName()).setLevel(Level.FINEST);
    Logger.getLogger(LocalFileSystemEx.class.getName()).addHandler(new DeadlockHandler(file1FO));
    LocalFileSystemEx.potentialLock(file1FO.getPath());
    LocalFileSystemEx.hasLocks();
}
 
Example 8
Source File: WritableXMLFileSystemTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testBasicStructureReads() throws Exception {
    FileSystem fs = new Layer("<file name='x'/>").read();
    FileObject[] top = fs.getRoot().getChildren();
    assertEquals(1, top.length);
    FileObject x = top[0];
    assertEquals("x", x.getNameExt());
    assertEquals(0L, x.getSize());
    assertTrue(x.isData());
    fs = new Layer("<folder name='x'><file name='y'/></folder><file name='z'/>").read();
    top = fs.getRoot().getChildren();
    assertEquals(2, top.length);
    FileObject z = fs.findResource("z");
    assertNotNull(z);
    assertTrue(z.isData());
    FileObject y = fs.findResource("x/y");
    assertNotNull(y);
    assertTrue(y.isData());
    x = fs.findResource("x");
    assertEquals(x, y.getParent());
    assertTrue(x.isFolder());
    assertEquals(1, x.getChildren().length);
}
 
Example 9
Source File: FileStateManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * @param mfo FileObject from default file system
 * @param layer the layer where notifier will be searched on
 * @return true if attached notifier is the delegate FO
 */
private synchronized boolean attachNotifier (FileObject mfo, int layer) {
    FileSystem fsLayer = getLayer (layer);
    String fn = mfo.getPath();
    FileObject fo = null;
    boolean isDelegate = true;

    if (fsLayer == null)
        return false;

    // find new notifier - the FileObject with closest match to getFile ()
    while (fn.length () > 0 && null == (fo = fsLayer.findResource (fn))) {
        int pos = fn.lastIndexOf ('/');
        isDelegate = false;

        if (-1 == pos)
            break;
        
        fn = fn.substring (0, pos);
    }
    
    if (fo == null)
        fo = fsLayer.getRoot ();

    if (fo != notifiers [layer]) {
        // remove listener from existing notifier if any
        if (notifiers [layer] != null)
            notifiers [layer].removeFileChangeListener (weakL [layer]);

        // create new listener and attach it to new notifier
        weakL [layer] = FileUtil.weakFileChangeListener (this, fo);
        fo.addFileChangeListener (weakL [layer]);
        notifiers [layer] = fo;
    }
    
    return isDelegate;
}
 
Example 10
Source File: FileStateManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void deleteImpl (FileObject mfo, FileSystem fsLayer) throws IOException {
    FileObject fo = fsLayer.findResource (mfo.getPath());
    if (fo != null) {
        FileLock lock = null;
        try {
            lock = fo.lock ();
            fo.delete (lock);
        } finally {
            if (lock != null)
                lock.releaseLock ();
        }
    }
}
 
Example 11
Source File: WritableXMLFileSystemTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testExternalFileReads() throws Exception {
    Layer l = new Layer("<file name='x' url='x.txt'/>", Collections.singletonMap("x.txt", "stuff"));
    FileSystem fs = l.read();
    FileObject x = fs.findResource("x");
    assertNotNull(x);
    assertTrue(x.isData());
    assertEquals(5L, x.getSize());
    assertEquals("stuff", x.asText("UTF-8"));
    assertEquals("x.txt", x.getAttribute("WritableXMLFileSystem.url"));
    assertEquals("[" + l.f.toURL() + "]", Arrays.toString((URL[]) x.getAttribute("layers")));
    fs = new Layer("<file name='x' url='subdir/x.txt'/>", Collections.singletonMap("subdir/x.txt", "more stuff")).read();
    x = fs.findResource("x");
    assertNotNull(x);
    assertEquals("more stuff", x.asText("UTF-8"));
}
 
Example 12
Source File: AutomaticExtraClasspathTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    URL u = getClass().getResource("AutomaticExtraClasspathTest.xml");
    FileSystem fs = new XMLFileSystem(u);
    fo = fs.findResource("testAutoProvider");
    assertNotNull("There is the resource", fo);
    bad = fs.findResource("brokenURL");
    assertNotNull("There is the bad", bad);
}
 
Example 13
Source File: I18nOptions.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Deprecated
private static FileObject findFileObject(String path) {
    for (FileSystem fileSystem : getFileSystems()) {
        FileObject retval = fileSystem.findResource(path);
        if (retval != null) {
            return retval;
        }
    }
    return null;
}
 
Example 14
Source File: ArchetypeTemplateHandlerTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Before
public void setUpMethod() throws Exception {
    FileSystem fs = FileUtil.createMemoryFileSystem();
    FileUtil.createData(fs.getRoot(), "root/wizard/src/main/java/com/yourorg/somepkg/MyClass.java");
    FileUtil.createData(fs.getRoot(), "root/wizard/src/main/java/com/yourorg/somepkg/Main.java");
    FileUtil.createData(fs.getRoot(), "root/wizard/src/main/webapp/index.html");
    root = fs.findResource("root");
    assertNotNull(root);
}
 
Example 15
Source File: ArchetypeWizardUtilsTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testOpeningOfProjectsSkipsTargetDirectory() throws IOException {
    FileSystem fs = FileUtil.createMemoryFileSystem();
    FileUtil.createData(fs.getRoot(), "MyPrj/pom.xml");
    FileUtil.createData(fs.getRoot(), "MyPrj/a/pom.xml");
    FileUtil.createData(fs.getRoot(), "MyPrj/b/pom.xml");
    FileUtil.createData(fs.getRoot(), "MyPrj/c/pom.xml");
    FileUtil.createData(fs.getRoot(), "MyPrj/target/x/pom.xml");
    FileUtil.createData(fs.getRoot(), "MyPrj/target/y/pom.xml");
    FileUtil.createData(fs.getRoot(), "MyPrj/target/z/pom.xml");
    FileObject root = fs.findResource("MyPrj");
    
   Set<FileObject> res = ArchetypeWizardUtils.openProjects(root, null);
    
    assertEquals("Four projects found: " + res, 4, res.size());
}
 
Example 16
Source File: ArchetypeWizardUtilsTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testFindsAllDirectories() throws IOException {
    FileSystem fs = FileUtil.createMemoryFileSystem();
    FileUtil.createData(fs.getRoot(), "MyPrj/pom.xml");
    FileUtil.createData(fs.getRoot(), "MyPrj/a/pom.xml");
    FileUtil.createData(fs.getRoot(), "MyPrj/a/b/pom.xml");
    FileUtil.createData(fs.getRoot(), "MyPrj/a/b/c/pom.xml");
    FileObject root = fs.findResource("MyPrj");
    
    Set<FileObject> res = ArchetypeWizardUtils.openProjects(root, null);
    
    assertEquals("Four projects found: " + res, 4, res.size());
}
 
Example 17
Source File: GrammarManager.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
     * Async grammar fetching
     */
    private void loadGrammar() {
        
        
        GrammarQuery loaded = null;
        try {
            
            String status = NbBundle.getMessage(GrammarManager.class, "MSG_loading");
            StatusDisplayer.getDefault().setStatusText(status);
            
            // prepare grammar environment
            
            try {
                
                LinkedList ctx = getEnvironmentElements();
                InputSource inputSource = new DocumentInputSource(doc);
                FileObject fileObject = null;
                Object obj = doc.getProperty(Document.StreamDescriptionProperty);
                if (obj instanceof DataObject) {
                    DataObject dobj = (DataObject) obj;
                    fileObject = dobj.getPrimaryFile();
                }
                GrammarEnvironment env = new GrammarEnvironment(Collections.enumeration(ctx), inputSource, fileObject);
                
                // lookup for grammar
                
                GrammarQueryManager g = GrammarQueryManager.getDefault();
                Enumeration en = g.enabled(env);
                if (en == null) return;
                
                // set guarded regions
                
                List positions = new ArrayList(10);
                int max = 0;
                
                while (en.hasMoreElements()) {
                    Node next = (Node) en.nextElement();
                    if (next instanceof SyntaxElement) {
                        SyntaxElement node = (SyntaxElement) next;
                        int start = node.getElementOffset();
                        int end = start + node.getElementLength();
                        if (end > max) max = end;
                        Position startPosition =
                                NbDocument.createPosition(doc, start, Position.Bias.Forward);
                        positions.add(startPosition);
                        Position endPosition =
                                NbDocument.createPosition(doc, end, Position.Bias.Backward);
                        positions.add(endPosition);
                    }
                }
                
                guarded = (Position[]) positions.toArray(new Position[positions.size()]);
                maxGuarded = NbDocument.createPosition(doc, max, Position.Bias.Backward);
                
                
                // retrieve the grammar and start invalidation listener
                
                loaded = g.getGrammar(env);
                
                if(loaded instanceof ExtendedGrammarQuery) {
                    //attach listeners to external files and if any of them changes then reload this grammar
                    for(String resolvedEntity : (List<String>)((ExtendedGrammarQuery)loaded).getResolvedEntities()) {
                        //filter non-files resolved entities
                        if(!resolvedEntity.startsWith(FILE_PROTOCOL_URI_PREFIX)) continue;
                        
                        DataObject docDo = NbEditorUtilities.getDataObject(doc);
                        if(docDo != null) {
                            FileObject docFo = docDo.getPrimaryFile();
                            if(docFo != null) {
                                try {
                                    FileSystem fs = docFo.getFileSystem();
                                    FileObject fo = fs.findResource(resolvedEntity.substring(FILE_PROTOCOL_URI_PREFIX.length())); //NOI18N
                                    if(fo != null) {
                                        externalDTDs.add(fo);
                                        //add a week listener to the fileobject - detach when document is being disposed
                                        fo.addFileChangeListener((FileChangeListener)WeakListeners.create(FileChangeListener.class, this, doc));
//                                        System.out.println("[GrammarManager] added FileObjectListener to " + fo.getPath());
                                    }
                                }catch(IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
                
            } catch (BadLocationException ex) {
                loaded = null;
            }
            
        } finally {
            
            doc.addDocumentListener(GrammarManager.this);
            
            grammarLoaded(loaded);
        }
    }
 
Example 18
Source File: FileReferenceCompletion.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public List<T> getItems(FileObject orig, int offset, String valuePart) {
    List<T> result = new ArrayList<>();

    String path = "";   // NOI18N
    String fileNamePart = valuePart;
    int lastSlash = valuePart.lastIndexOf('/');
    if (lastSlash == 0) {
        path = "/"; // NOI18N
        fileNamePart = valuePart.substring(1);
    } else if (lastSlash > 0) { // not a leading slash?
        path = valuePart.substring(0, lastSlash);
        fileNamePart = (lastSlash == valuePart.length()) ? "" : valuePart.substring(lastSlash + 1);    // NOI18N
    }

    int anchor = offset + lastSlash + 1;  // works even with -1

    try {
        FileObject documentBase = ProjectWebRootQuery.getWebRoot(orig);
        // need to normalize fileNamePart with respect to orig
        String aaaa = orig.isFolder() ? orig.getPath() + "/" : orig.getPath(); 
        String ctxPath = resolveRelativeURL("/"+aaaa, path);  // NOI18N
        //is this absolute path?
        if (path.startsWith("/")) {
            if (documentBase == null) {
                //abosolute path but no web root, cannot complete
                return Collections.emptyList();
            } else {
                ctxPath = documentBase.getPath() + path;
            }
        } else {
            ctxPath = ctxPath.substring(1);
        }

        FileSystem fs = orig.getFileSystem();

        FileObject folder = fs.findResource(ctxPath);
        if (folder != null) {
            //add all accessible files from current context
            result.addAll(files(anchor, folder, fileNamePart));

            //add go up in the directories structure item
            if (!(documentBase != null && folder.equals(documentBase)) && !path.startsWith("/") // NOI18N
                    && (fileNamePart.isEmpty() // ../| case
                    || fileNamePart.equals(".") // ../.| case
                    || fileNamePart.equals("..")) //../..| case
                    ) { // NOI18N
                result.add(createGoUpItem(anchor, Color.BLUE, PACKAGE_ICON)); // NOI18N
            }
        }
    } catch (FileStateInvalidException | IllegalArgumentException ex) {
        // unreachable FS - disable completion
    }

    return result;
}
 
Example 19
Source File: FileStateManager.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private boolean isOnLayer (FileObject mfo, int layer) {
    FileSystem fsLayer = getLayer (layer);
    return fsLayer == null ? false : null != fsLayer.findResource (mfo.getPath());
}
 
Example 20
Source File: BinaryUsagesTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private FileObject[] findFileObjectsInRepository(File f) {
    if (!f.equals(FileUtil.normalizeFile(f))) {
        throw new IllegalArgumentException(
            "Parameter file was not " + // NOI18N
            "normalized. Was " + f + " instead of " + FileUtil.normalizeFile(f)
        ); // NOI18N
    }

    @SuppressWarnings("deprecation") // keep for backward compatibility w/ NB 3.x
    Enumeration<? extends FileSystem> en = Repository.getDefault().getFileSystems();
    List<FileObject> list = new LinkedList<FileObject>();
    String fileName = f.getAbsolutePath();

    while (en.hasMoreElements()) {
        FileSystem fs = en.nextElement();
        String rootName = null;
        FileObject fsRoot = fs.getRoot();
        File root = findFileInRepository(fsRoot);

        if (root == null) {
            Object rootPath = fsRoot.getAttribute("FileSystem.rootPath"); //NOI18N

            if ((rootPath != null) && (rootPath instanceof String)) {
                rootName = (String) rootPath;
            } else {
                continue;
            }
        }

        if (rootName == null) {
            rootName = root.getAbsolutePath();
        }

        /**root is parent of file*/
        if (fileName.indexOf(rootName) == 0) {
            String res = fileName.substring(rootName.length()).replace(File.separatorChar, '/');
            FileObject fo = fs.findResource(res);
            File file2Fo = (fo != null) ? findFileInRepository(fo) : null;
            if ((fo != null) && (file2Fo != null) && f.equals(file2Fo)) {
                list.add(fo);
            }
        }
    }
    FileObject[] results = new FileObject[list.size()];
    list.toArray(results);
    return results;
}