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

The following examples show how to use org.openide.filesystems.FileObject#getFileSystem() . 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: JSFClientGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static void createFile(final FileObject jsfRoot, final String content, final String name, final Charset encoding) throws IOException{
    FileSystem fs = jsfRoot.getFileSystem();

    fs.runAtomicAction(new FileSystem.AtomicAction() {
        public void run() throws IOException {
            FileObject detailForm = FileUtil.createData(jsfRoot, name);//NOI18N
            FileLock lock = detailForm.lock();
            try {
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(detailForm.getOutputStream(lock), encoding));
                bw.write(content);
                bw.close();
            }
            finally {
                lock.releaseLock();
            }
        }
    });
}
 
Example 2
Source File: SpringBinaryIndexer.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private String findVersion(FileObject classpathRoot) {
    ClassPath cp = ClassPath.getClassPath(classpathRoot, ClassPath.COMPILE);
    if (cp == null) {
        return null;
    }
    String classRelativePath = SpringUtilities.SPRING_CLASS_NAME.replace('.', '/') + ".class"; //NOI18N
    try {
        FileObject resource = cp.findResource(classRelativePath);  //NOI18N
        if (resource==null) {
            return null;
        }
        FileObject ownerRoot = cp.findOwnerRoot(resource);

        if (ownerRoot !=null) { //NOI18N
            if (ownerRoot.getFileSystem() instanceof JarFileSystem) {
                JarFileSystem jarFileSystem = (JarFileSystem) ownerRoot.getFileSystem();
                return SpringUtilities.getImplementationVersion(jarFileSystem);
            }
        }
    } catch (FileStateInvalidException e) {
        Exceptions.printStackTrace(e);
    }
    return null;
}
 
Example 3
Source File: BaseFileObjectTestHid.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public String annotateName (String name, java.util.Set files) {
    StringBuilder sb = new StringBuilder (name);
    Iterator it = files.iterator ();
    while (it.hasNext()) {                    
        FileObject fo = (FileObject)it.next();
        try {
            if (fo.getFileSystem() instanceof IgnoreDirFileSystem) {
                sb.append(",").append (fo.getNameExt());//NOI18N
            }
        } catch (Exception ex) {
            fail ();
        }
    }
                    
    return sb.toString () ;
}
 
Example 4
Source File: WSUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static void removeImplClass(Project project, String implClass) {
    Sources sources = project.getLookup().lookup(Sources.class);
    String resource = implClass.replace('.','/')+".java"; //NOI18N
    if (sources!=null) {
        SourceGroup[] srcGroup = sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
        for (int i=0;i<srcGroup.length;i++) {
            final FileObject srcRoot = srcGroup[i].getRootFolder();
            final FileObject implClassFo = srcRoot.getFileObject(resource);
            if (implClassFo!=null) {
                try {
                    FileSystem fs = implClassFo.getFileSystem();
                    fs.runAtomicAction(new AtomicAction() {
                        public void run() {
                            deleteFile(implClassFo);
                        }
                    });
                } catch (IOException ex) {
                    ErrorManager.getDefault().notify(ex);
                }
                return;
            }
        }
    }
}
 
Example 5
Source File: SourceURLMapper.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public @Override URL getURL(FileObject fo, int type) {
    if (type != URLMapper.INTERNAL) {
        return null;
    }
    try {
        FileSystem fs = fo.getFileSystem();
        if (fs instanceof SourceFS) {
            String path = fo.getPath();
            if (fo.isFolder() && !fo.isRoot()) {
                path += '/';
            }
            return url((SourceFS) fs, path);
        }
    } catch (FileStateInvalidException x) {
        // ignore
    }
    return null;
}
 
Example 6
Source File: BaseFileObjectTestHid.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testValidRoots () throws Exception {
    assertNotNull(testedFS.getRoot());    
    assertTrue(testedFS.getRoot().isValid());            
    
    FileSystemView fsv = FileSystemView.getFileSystemView();                
    File[] roots = File.listRoots();
    boolean validRoot = false;
    for (int i = 0; i < roots.length; i++) {
        FileObject root1 = FileUtil.toFileObject(roots[i]);
        if (!roots[i].exists()) {
           assertNull(root1);
           continue; 
        }
        
        assertNotNull(roots[i].getAbsolutePath (),root1);
        assertTrue(root1.isValid());
        if (testedFS == root1.getFileSystem()) {
            validRoot = true;
        }
    }
    assertTrue(validRoot);
}
 
Example 7
Source File: FileStateManager.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public int getFileState (FileObject mfo, int layer) {
    // check if the FileObject is from SystemFileSystem
    FileSystem fs = null;
    FileInfo finf = null;

    try {
        fs = mfo.getFileSystem ();
    } catch (FileStateInvalidException e) {
        // ignore, will be handled later
    }

    if (fs == null || !fs.isDefault())
        throw new IllegalArgumentException ("FileObject has to be from DefaultFileSystem - " + mfo);
    
    synchronized (info) {
        if (null == (finf = info.get(mfo))) {
            finf = new FileInfo(mfo);
            info.put(mfo, finf);
        }
    }

    return finf.getState (layer);
}
 
Example 8
Source File: FolderObjTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testDeleteNoParent() throws IOException {
    FileObject parent = FileBasedFileSystem.getFileObject(testFile).getParent();
    FileObject fobj = FileBasedFileSystem.getFileObject(testFile);
    assertNotNull(fobj);
    //parent not exists + testFile not exists
    EventsEvaluator ev = new EventsEvaluator(fobj.getFileSystem());
    Reference<FileObject> ref = new WeakReference<FileObject>(parent);
    parent = null;
    assertGC("", ref);                                
    fobj.delete();
    ev.assertDeleted(1);
}
 
Example 9
Source File: ErrorAnnotator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void ensureListensOnFS(FileObject f) {
    try {
        FileSystem fs = f.getFileSystem();
        if (!system2RecursiveListener.containsKey(fs)) {
            FileChangeListener l = new RootAddedDeletedListener();
            system2RecursiveListener.put(fs, l);
            fs.addFileChangeListener(l);
        }
    } catch (FileStateInvalidException ex) {
        LOG.log(Level.FINE, null, ex);
    }
}
 
Example 10
Source File: FolderObjTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testRefresh109490() throws Exception {
    final File wDir = getWorkDir();
    final FileObject wDirFo = FileBasedFileSystem.getFileObject(wDir);
    final List<FileEvent> fileEvents = new ArrayList<FileEvent>();
    FileSystem fs = wDirFo.getFileSystem();
    FileChangeListener fListener = new FileChangeAdapter() {

        @Override
        public void fileDataCreated(FileEvent fe) {
            super.fileDataCreated(fe);
            fileEvents.add(fe);
        }
    };
    try {
        fs.addFileChangeListener(fListener);

        File file = new File(wDir, "testao.f");
        File file2 = new File(wDir, "testc1.f");
        assertEquals(file.hashCode(), file2.hashCode());
        wDirFo.getChildren();
        assertTrue(file.createNewFile());
        assertTrue(file2.createNewFile());
        assertEquals(0, fileEvents.size());
        fs.refresh(true);
        assertEquals(2, fileEvents.size());
        assertEquals(Arrays.asList(wDirFo.getChildren()).toString(), 2,wDirFo.getChildren().length);
        assertTrue(Arrays.asList(wDirFo.getChildren()).toString().indexOf(file.getName()) != -1);            
        assertTrue(Arrays.asList(wDirFo.getChildren()).toString().indexOf(file2.getName()) != -1);                        
    } finally {
        fs.removeFileChangeListener(fListener);
    }
}
 
Example 11
Source File: EarDataObject.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void refreshSourceFolders () {
    ArrayList srcRootList = new ArrayList ();
    
    Project project = FileOwnerQuery.getOwner (getPrimaryFile ());
    if (project != null) {
        Sources sources = ProjectUtils.getSources(project);
        sources.removeChangeListener (this);
        sources.addChangeListener (this);
        SourceGroup[] groups = sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
        for (int i = 0; i < groups.length; i++) {
            org.netbeans.modules.j2ee.api.ejbjar.EjbJar ejbModule = org.netbeans.modules.j2ee.api.ejbjar.EjbJar.getEjbJar(groups[i].getRootFolder());

            if (ejbModule != null && ejbModule.getDeploymentDescriptor() != null) {
                try {
                    FileObject fo = groups[i].getRootFolder();

                    srcRootList.add(groups[i].getRootFolder());
                    FileSystem fs = fo.getFileSystem();

                    fs.removeFileChangeListener(this);
                    fs.addFileChangeListener(this);
                } catch (FileStateInvalidException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        }
    }
    srcRoots = (FileObject []) srcRootList.toArray (new FileObject [srcRootList.size ()]);
}
 
Example 12
Source File: Hk2DatasourceManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void writeXmlResourceToFile(final File sunResourcesXml, final Document doc) throws IOException {

        FileObject parentFolder = FileUtil.createFolder(sunResourcesXml.getParentFile());
        FileSystem fs = parentFolder.getFileSystem();

         fs.runAtomicAction(new FileSystem.AtomicAction() {
            @Override
            public void run() throws IOException {
                FileLock lock = null;
                OutputStream os = null;
                try {
                    FileObject sunResourcesFO = FileUtil.createData(sunResourcesXml);
                    lock = sunResourcesFO.lock();
                    os = sunResourcesFO.getOutputStream(lock);

                    XMLUtil.write(doc, os, doc.getXmlEncoding());
                } finally {
                    if(os !=null ){
                        os.close();
                    }
                    if(lock != null) {
                        lock.releaseLock();
                    }
                }
            }
        });
    }
 
Example 13
Source File: BuildImageWizard.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void setDockerfile(FileObject dockerfile) {
    this.dockerfile = dockerfile;
    try {
        this.fileSystem = dockerfile.getFileSystem();
    } catch (FileStateInvalidException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example 14
Source File: DiskFileKey.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public boolean equals(Object o) {
    if (this == o) return true;

    if (o instanceof DiskFileKey) {

        DiskFileKey key = (DiskFileKey) o;

        if (hashCode != key.hashCode) return false;
        FileObject fo2 = key.fileObject;
        FileObject fo = fileObject;

        if (fo == fo2) return true;

        try {
            FileSystem fs = fo.getFileSystem();
            FileSystem fs2 = fo2.getFileSystem();
            if (fs.equals(fs2)) {
                return fo.equals(fo2);
            } else {
                // fallback use absolute paths (cache them)
                if (absolutePath == null) {
                    File f = FileUtil.toFile(fo);
                    absolutePath = f.getAbsolutePath();
                }
                if (key.absolutePath == null) {
                    File f2 = FileUtil.toFile(fo2);
                    key.absolutePath = f2.getAbsolutePath();
                }
                return absolutePath.equals(key.absolutePath);
            }
        } catch (FileStateInvalidException e) {
            ErrorManager err = ErrorManager.getDefault();
            err.notify(e);
        }
    }
    return false;
}
 
Example 15
Source File: HudsonRemoteFileSystem.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static URL doGetURL(FileObject fo) {
    try {
        FileSystem fs = fo.getFileSystem();
        if (fs instanceof HudsonRemoteFileSystem) {
            return new URL(((HudsonRemoteFileSystem) fs).baseURL, Utilities.uriEncode(fo.getPath()));
        }
    } catch (IOException x) {
        LOG.log(Level.INFO, "trying to get URL for " + fo, x);
    }
    return null;
}
 
Example 16
Source File: SvnFileSystemTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected FileSystem[] createFileSystem(String testName, String[] resources) throws IOException {        
    setupWorkdir();
    setupUserdir();

    try {                                 
        repoinit();
    } catch (Exception ex) {
        throw new IOException(ex.getMessage());
    } 
                
    FileObjectFactory.reinitForTests();
    FileObject workFo = FileBasedFileSystem.getFileObject(getWorkDir());
    assertNotNull(workFo);
    List<File> files = new ArrayList<File>(resources.length);
    for (int i = 0; i < resources.length; i++) {            
        String res = resources[i];
        FileObject fo;
        if (res.endsWith("/")) {
            fo = FileUtil.createFolder(workFo,res);
            assertNotNull(fo);
        } else {
            fo = FileUtil.createData(workFo,res);
            assertNotNull(fo);
        }            
        files.add(FileUtil.toFile(fo));            
    }        
    commit(files, testName);
    return new FileSystem[]{workFo.getFileSystem()};
}
 
Example 17
Source File: AbstractSourceFileObject.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private long getFileLastModified() {
    final FileObject file = handle.resolveFileObject(false);
    try {
        //Prefer class files to packed sources, the packed sources may have wrong time stamps.
        if (file == null || file.getFileSystem() instanceof JarFileSystem) {
            return 0L;
        }
    } catch (FileStateInvalidException e) {
        //Handled below
    }
    return file.lastModified().getTime();
}
 
Example 18
Source File: XMLWizardIterator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public Set instantiate(TemplateWizard templateWizard) throws IOException {
    final DataFolder folder = templateWizard.getTargetFolder();
    
    final File pobj = FileUtil.toFile(folder.getPrimaryFile());
           
    final String extension = XML_EXT;

    // #22812 we do not control validity constrains of target panel
    // assure uniquess to "<default>" name
    
    String targetName = templateWizard.getTargetName();
    if (targetName == null || "null".equals(targetName)) {                  // NOI18N
        targetName = "XMLDocument";                                         // NOI18N
    }
    final FileObject targetFolder = folder.getPrimaryFile();
    String uniqueTargetName = targetName;
    int i = 2;
    
    while (targetFolder.getFileObject(uniqueTargetName, extension) != null) {
        uniqueTargetName = targetName + i;
        i++;
    }

    final String name = uniqueTargetName;
    String nameExt = name + "." + extension;

    // in atomic action create data object and return it
    
    FileSystem filesystem = targetFolder.getFileSystem();
    final Map<String, Object> params = prepareParameters(folder);
    
    FileObject template = Templates.getTemplate(templateWizard);        
    final DataObject dTemplate = DataObject.find(template);                

    DataObject dobj = dTemplate.createFromTemplate(folder, 
            name, params);
    FileObject f = dobj.getPrimaryFile();
    // perform default action and return
    Set set = new HashSet(1);                
    DataObject createdObject = DataObject.find(f);        
    GuiUtil.performDefaultAction(createdObject);
    set.add(createdObject);    
    
    formatXML(f);
    return set;
}
 
Example 19
Source File: ResourceModifier.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static void writeResourceFile(final File sunResourcesXml, final String content) throws IOException {
    FileObject parentFolder = FileUtil.createFolder(sunResourcesXml.getParentFile());
    FileSystem fs = parentFolder.getFileSystem();
    writeResourceFile(fs, sunResourcesXml, content);
}
 
Example 20
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);
        }
    }